From e4287c28bb2dafedc81c66e63951d947cfbeb225 Mon Sep 17 00:00:00 2001 From: Rudolf Polzer Date: Tue, 27 Mar 2012 12:03:21 +0200 Subject: [PATCH] my own uncrustify run --- conftest.cpp | 3 +- contrib/bkgrnd2d/bkgrnd2d.cpp | 265 +- contrib/bkgrnd2d/bkgrnd2d.h | 81 +- contrib/bkgrnd2d/dialog.cpp | 429 +- contrib/bkgrnd2d/dialog.h | 30 +- contrib/bkgrnd2d/plugin.cpp | 312 +- contrib/bkgrnd2d/plugin.h | 46 +- contrib/bobtoolz/CPortals.h | 66 +- contrib/bobtoolz/DBobView.cpp | 266 +- contrib/bobtoolz/DBobView.h | 137 +- contrib/bobtoolz/DBrush.cpp | 742 +- contrib/bobtoolz/DBrush.h | 130 +- contrib/bobtoolz/DEPair.cpp | 41 +- contrib/bobtoolz/DEPair.h | 42 +- contrib/bobtoolz/DEntity.cpp | 676 +- contrib/bobtoolz/DEntity.h | 122 +- contrib/bobtoolz/DMap.cpp | 166 +- contrib/bobtoolz/DMap.h | 58 +- contrib/bobtoolz/DPatch.cpp | 535 +- contrib/bobtoolz/DPatch.h | 80 +- contrib/bobtoolz/DPlane.cpp | 282 +- contrib/bobtoolz/DPlane.h | 70 +- contrib/bobtoolz/DPoint.cpp | 42 +- contrib/bobtoolz/DPoint.h | 42 +- contrib/bobtoolz/DShape.cpp | 398 +- contrib/bobtoolz/DShape.h | 62 +- contrib/bobtoolz/DTrainDrawer.cpp | 332 +- contrib/bobtoolz/DTrainDrawer.h | 74 +- contrib/bobtoolz/DTreePlanter.cpp | 262 +- contrib/bobtoolz/DTreePlanter.h | 301 +- contrib/bobtoolz/DVisDrawer.cpp | 126 +- contrib/bobtoolz/DVisDrawer.h | 56 +- contrib/bobtoolz/DWinding.cpp | 462 +- contrib/bobtoolz/DWinding.h | 72 +- contrib/bobtoolz/ScriptParser.cpp | 181 +- contrib/bobtoolz/ScriptParser.h | 72 +- contrib/bobtoolz/StdAfx.cpp | 29 +- contrib/bobtoolz/StdAfx.h | 28 +- contrib/bobtoolz/bobToolz-GTK.cpp | 428 +- contrib/bobtoolz/bobToolz.h | 52 +- contrib/bobtoolz/bsploader.cpp | 254 +- contrib/bobtoolz/bsploader.h | 172 +- contrib/bobtoolz/cportals.cpp | 228 +- contrib/bobtoolz/ctfToolz-GTK.cpp | 88 +- contrib/bobtoolz/ctfresource_gtk.h | 30 +- contrib/bobtoolz/dialogs/AboutDialog.cpp | 51 +- contrib/bobtoolz/dialogs/AboutDialog.h | 58 +- contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp | 52 +- contrib/bobtoolz/dialogs/AutoCaulkDialog.h | 62 +- .../bobtoolz/dialogs/AutoCaulkStartDialog.cpp | 54 +- .../bobtoolz/dialogs/AutoCaulkStartDialog.h | 70 +- contrib/bobtoolz/dialogs/BrushCheckDialog.h | 60 +- contrib/bobtoolz/dialogs/DoorDialog.cpp | 88 +- contrib/bobtoolz/dialogs/DoorDialog.h | 78 +- contrib/bobtoolz/dialogs/IntersectDialog.cpp | 52 +- contrib/bobtoolz/dialogs/IntersectDialog.h | 68 +- .../bobtoolz/dialogs/IntersectInfoDialog.cpp | 48 +- .../bobtoolz/dialogs/IntersectInfoDialog.h | 60 +- contrib/bobtoolz/dialogs/PolygonDialog.cpp | 113 +- contrib/bobtoolz/dialogs/PolygonDialog.h | 78 +- contrib/bobtoolz/dialogs/StairDialog.cpp | 100 +- contrib/bobtoolz/dialogs/StairDialog.h | 76 +- .../bobtoolz/dialogs/TextureResetDialog.cpp | 74 +- contrib/bobtoolz/dialogs/TextureResetDialog.h | 76 +- contrib/bobtoolz/dialogs/brushcheckdialog.cpp | 48 +- contrib/bobtoolz/dialogs/dialogs-gtk.cpp | 2721 ++- contrib/bobtoolz/dialogs/dialogs-gtk.h | 62 +- .../bobtoolz/dialogs/pathplotterdialog.cpp | 77 +- contrib/bobtoolz/dialogs/pathplotterdialog.h | 70 +- contrib/bobtoolz/funchandlers-GTK.cpp | 762 +- contrib/bobtoolz/funchandlers-ctf-GTK.cpp | 213 +- contrib/bobtoolz/funchandlers.cpp | 466 +- contrib/bobtoolz/funchandlers.h | 50 +- contrib/bobtoolz/lists.cpp | 82 +- contrib/bobtoolz/lists.h | 34 +- contrib/bobtoolz/misc.cpp | 432 +- contrib/bobtoolz/misc.h | 58 +- contrib/bobtoolz/resource-gtk.h | 2 +- contrib/bobtoolz/resource.h | 30 +- contrib/bobtoolz/shapes.cpp | 726 +- contrib/bobtoolz/shapes.h | 44 +- contrib/bobtoolz/visfind.cpp | 216 +- contrib/bobtoolz/visfind.h | 2 +- contrib/brushexport/callbacks.cpp | 211 +- contrib/brushexport/callbacks.h | 12 +- contrib/brushexport/export.cpp | 390 +- contrib/brushexport/export.h | 4 +- contrib/brushexport/interface.cpp | 416 +- contrib/brushexport/plugin.cpp | 159 +- contrib/brushexport/plugin.h | 32 +- contrib/brushexport/support.cpp | 48 +- contrib/brushexport/support.h | 6 +- contrib/camera/camera.cpp | 381 +- contrib/camera/camera.h | 158 +- contrib/camera/dialogs.cpp | 1256 +- contrib/camera/dialogs.h | 44 +- contrib/camera/dialogs_common.cpp | 60 +- contrib/camera/funchandlers.cpp | 328 +- contrib/camera/funchandlers.h | 37 +- contrib/camera/listener.cpp | 261 +- contrib/camera/listener.h | 101 +- contrib/camera/misc.cpp | 232 +- contrib/camera/misc.h | 58 +- contrib/camera/renderer.cpp | 142 +- contrib/camera/renderer.h | 66 +- contrib/gtkgensurf/bitmap.cpp | 836 +- contrib/gtkgensurf/dec.cpp | 1027 +- contrib/gtkgensurf/face.cpp | 506 +- contrib/gtkgensurf/font.cpp | 468 +- contrib/gtkgensurf/gendlgs.cpp | 4176 ++-- contrib/gtkgensurf/gendlgs.h | 292 +- contrib/gtkgensurf/genmap.cpp | 3876 ++-- contrib/gtkgensurf/gensurf.cpp | 805 +- contrib/gtkgensurf/gensurf.h | 377 +- contrib/gtkgensurf/heretic.cpp | 247 +- contrib/gtkgensurf/plugin.cpp | 324 +- contrib/gtkgensurf/triangle.c | 19323 ++++++++-------- contrib/gtkgensurf/triangle.h | 50 +- contrib/gtkgensurf/view.cpp | 2122 +- contrib/hydratoolz/plugin.cpp | 820 +- contrib/hydratoolz/plugin.h | 40 +- contrib/prtview/AboutDialog.cpp | 153 +- contrib/prtview/AboutDialog.h | 32 +- contrib/prtview/ConfigDialog.cpp | 833 +- contrib/prtview/ConfigDialog.h | 32 +- contrib/prtview/LoadPortalFileDialog.cpp | 329 +- contrib/prtview/LoadPortalFileDialog.h | 33 +- contrib/prtview/portals.cpp | 528 +- contrib/prtview/portals.h | 156 +- contrib/prtview/prtview.cpp | 417 +- contrib/prtview/prtview.h | 38 +- contrib/shaderplug/shaderplug.cpp | 396 +- contrib/shaderplug/shaderplug.h | 32 +- contrib/sunplug/sunplug.cpp | 636 +- contrib/sunplug/sunplug.h | 30 +- contrib/ufoaiplug/ufoai.cpp | 279 +- contrib/ufoaiplug/ufoai.h | 28 +- contrib/ufoaiplug/ufoai_filters.cpp | 346 +- contrib/ufoaiplug/ufoai_filters.h | 38 +- contrib/ufoaiplug/ufoai_gtk.cpp | 209 +- contrib/ufoaiplug/ufoai_gtk.h | 36 +- contrib/ufoaiplug/ufoai_level.cpp | 290 +- contrib/ufoaiplug/ufoai_level.h | 34 +- include/cullable.cpp | 31 +- include/cullable.h | 72 +- include/editable.cpp | 31 +- include/editable.h | 50 +- include/iarchive.cpp | 31 +- include/iarchive.h | 200 +- include/ibrush.cpp | 31 +- include/ibrush.h | 124 +- include/icamera.cpp | 31 +- include/icamera.h | 56 +- include/idatastream.cpp | 31 +- include/idatastream.h | 76 +- include/ieclass.cpp | 31 +- include/ieclass.h | 76 +- include/ientity.cpp | 31 +- include/ientity.h | 151 +- include/ifilesystem.cpp | 31 +- include/ifilesystem.h | 165 +- include/ifiletypes.cpp | 31 +- include/ifiletypes.h | 71 +- include/ifilter.cpp | 31 +- include/ifilter.h | 93 +- include/igl.cpp | 31 +- include/igl.h | 1699 +- include/iglrender.cpp | 1 - include/iglrender.h | 157 +- include/igtkgl.cpp | 31 +- include/igtkgl.h | 52 +- include/iimage.cpp | 31 +- include/iimage.h | 73 +- include/imap.cpp | 31 +- include/imap.h | 58 +- include/imodel.cpp | 31 +- include/imodel.h | 40 +- include/ipatch.cpp | 31 +- include/ipatch.h | 384 +- include/iplugin.cpp | 31 +- include/iplugin.h | 58 +- include/ireference.cpp | 31 +- include/ireference.h | 69 +- include/irender.cpp | 31 +- include/irender.h | 135 +- include/iscenegraph.cpp | 31 +- include/iscenegraph.h | 329 +- include/iscriplib.cpp | 31 +- include/iscriplib.h | 75 +- include/iselection.cpp | 31 +- include/iselection.h | 169 +- include/ishaders.cpp | 31 +- include/ishaders.h | 210 +- include/itexdef.cpp | 31 +- include/itexdef.h | 55 +- include/itextstream.cpp | 31 +- include/itextstream.h | 115 +- include/itextures.cpp | 31 +- include/itextures.h | 91 +- include/itoolbar.cpp | 31 +- include/itoolbar.h | 68 +- include/iundo.cpp | 31 +- include/iundo.h | 93 +- include/mapfile.cpp | 31 +- include/mapfile.h | 86 +- include/modelskin.cpp | 31 +- include/modelskin.h | 86 +- include/moduleobserver.cpp | 31 +- include/moduleobserver.h | 36 +- include/modulesystem.cpp | 31 +- include/modulesystem.h | 320 +- include/nameable.cpp | 31 +- include/nameable.h | 40 +- include/namespace.cpp | 31 +- include/namespace.h | 51 +- include/preferencesystem.cpp | 271 +- include/preferencesystem.h | 43 +- include/qerplugin.cpp | 31 +- include/qerplugin.h | 169 +- include/renderable.cpp | 31 +- include/renderable.h | 87 +- include/selectable.cpp | 31 +- include/selectable.h | 395 +- include/stream_version.h | 1 - include/warnings.h | 35 +- include/windowobserver.cpp | 31 +- include/windowobserver.h | 86 +- libs/archivelib.cpp | 30 +- libs/archivelib.h | 348 +- libs/bytebool.cpp | 30 +- libs/bytebool.h | 30 +- libs/bytestreamutils.cpp | 30 +- libs/bytestreamutils.h | 127 +- libs/character.cpp | 31 +- libs/character.h | 55 +- libs/cmdlib.h | 53 +- libs/cmdlib/cmdlib.cpp | 199 +- libs/container/array.cpp | 52 +- libs/container/array.h | 285 +- libs/container/cache.cpp | 30 +- libs/container/cache.h | 280 +- libs/container/container.cpp | 31 +- libs/container/container.h | 578 +- libs/container/hashfunc.cpp | 30 +- libs/container/hashfunc.h | 582 +- libs/container/hashtable.cpp | 93 +- libs/container/hashtable.h | 792 +- libs/container/stack.cpp | 31 +- libs/container/stack.h | 360 +- libs/convert.cpp | 31 +- libs/convert.h | 386 +- libs/ddslib.h | 212 +- libs/ddslib/ddslib.c | 794 +- libs/debugging/debugging.cpp | 37 +- libs/debugging/debugging.h | 140 +- libs/dragplanes.cpp | 31 +- libs/dragplanes.h | 437 +- libs/eclasslib.cpp | 30 +- libs/eclasslib.h | 419 +- libs/entitylib.cpp | 30 +- libs/entitylib.h | 1212 +- libs/entityxml.cpp | 30 +- libs/entityxml.h | 138 +- libs/filematch.c | 47 +- libs/filematch.h | 6 +- libs/fs_filesystem.cpp | 30 +- libs/fs_filesystem.h | 291 +- libs/fs_path.cpp | 30 +- libs/fs_path.h | 124 +- libs/generic/arrayrange.cpp | 31 +- libs/generic/arrayrange.h | 78 +- libs/generic/bitfield.cpp | 31 +- libs/generic/bitfield.h | 126 +- libs/generic/callback.cpp | 465 +- libs/generic/callback.h | 674 +- libs/generic/callbackfwd.cpp | 1 - libs/generic/callbackfwd.h | 2 +- libs/generic/constant.cpp | 48 +- libs/generic/constant.h | 55 +- libs/generic/enumeration.cpp | 31 +- libs/generic/enumeration.h | 56 +- libs/generic/functional.cpp | 1 - libs/generic/functional.h | 352 +- libs/generic/object.cpp | 56 +- libs/generic/object.h | 86 +- libs/generic/reference.cpp | 30 +- libs/generic/reference.h | 124 +- libs/generic/referencecounted.cpp | 30 +- libs/generic/referencecounted.h | 271 +- libs/generic/static.cpp | 213 +- libs/generic/static.h | 117 +- libs/generic/vector.cpp | 1 - libs/generic/vector.h | 341 +- libs/gtkutil/accelerator.cpp | 866 +- libs/gtkutil/accelerator.h | 167 +- libs/gtkutil/button.cpp | 180 +- libs/gtkutil/button.h | 46 +- libs/gtkutil/clipboard.cpp | 203 +- libs/gtkutil/clipboard.h | 40 +- libs/gtkutil/closure.cpp | 31 +- libs/gtkutil/closure.h | 95 +- libs/gtkutil/container.cpp | 31 +- libs/gtkutil/container.h | 49 +- libs/gtkutil/cursor.cpp | 111 +- libs/gtkutil/cursor.h | 292 +- libs/gtkutil/dialog.cpp | 375 +- libs/gtkutil/dialog.h | 138 +- libs/gtkutil/entry.cpp | 31 +- libs/gtkutil/entry.h | 70 +- libs/gtkutil/filechooser.cpp | 486 +- libs/gtkutil/filechooser.h | 36 +- libs/gtkutil/frame.cpp | 46 +- libs/gtkutil/frame.h | 34 +- libs/gtkutil/glfont.cpp | 535 +- libs/gtkutil/glfont.h | 49 +- libs/gtkutil/glwidget.cpp | 351 +- libs/gtkutil/glwidget.h | 50 +- libs/gtkutil/idledraw.cpp | 31 +- libs/gtkutil/idledraw.h | 92 +- libs/gtkutil/image.cpp | 124 +- libs/gtkutil/image.h | 42 +- libs/gtkutil/menu.cpp | 411 +- libs/gtkutil/menu.h | 58 +- libs/gtkutil/messagebox.cpp | 363 +- libs/gtkutil/messagebox.h | 34 +- libs/gtkutil/nonmodal.cpp | 31 +- libs/gtkutil/nonmodal.h | 256 +- libs/gtkutil/paned.cpp | 134 +- libs/gtkutil/paned.h | 34 +- libs/gtkutil/pointer.cpp | 31 +- libs/gtkutil/pointer.h | 42 +- libs/gtkutil/toolbar.cpp | 88 +- libs/gtkutil/toolbar.h | 40 +- libs/gtkutil/widget.cpp | 31 +- libs/gtkutil/widget.h | 270 +- libs/gtkutil/window.cpp | 206 +- libs/gtkutil/window.h | 210 +- libs/gtkutil/xorrectangle.cpp | 31 +- libs/gtkutil/xorrectangle.h | 172 +- libs/imagelib.cpp | 31 +- libs/imagelib.h | 200 +- libs/instancelib.cpp | 30 +- libs/instancelib.h | 266 +- libs/l_net/l_net.c | 410 +- libs/l_net/l_net.h | 102 +- libs/l_net/l_net_berkley.c | 592 +- libs/l_net/l_net_wins.c | 656 +- libs/l_net/l_net_wins.h | 72 +- libs/maplib.cpp | 30 +- libs/maplib.h | 428 +- libs/math/aabb.cpp | 31 +- libs/math/aabb.h | 442 +- libs/math/curve.cpp | 31 +- libs/math/curve.h | 323 +- libs/math/expression.cpp | 296 +- libs/math/expression.h | 727 +- libs/math/frustum.cpp | 31 +- libs/math/frustum.h | 984 +- libs/math/line.cpp | 31 +- libs/math/line.h | 185 +- libs/math/matrix.cpp | 31 +- libs/math/matrix.h | 1802 +- libs/math/pi.cpp | 31 +- libs/math/pi.h | 42 +- libs/math/plane.cpp | 31 +- libs/math/plane.h | 193 +- libs/math/quaternion.cpp | 31 +- libs/math/quaternion.h | 460 +- libs/math/vector.cpp | 31 +- libs/math/vector.h | 871 +- libs/mathlib.h | 406 +- libs/mathlib/bbox.c | 690 +- libs/mathlib/line.c | 62 +- libs/mathlib/m4x4.c | 3007 ++- libs/mathlib/mathlib.c | 711 +- libs/mathlib/ray.c | 237 +- libs/md5lib.h | 82 +- libs/md5lib/md5lib.c | 613 +- libs/memory/allocator.cpp | 110 +- libs/memory/allocator.h | 436 +- libs/moduleobservers.cpp | 31 +- libs/moduleobservers.h | 87 +- libs/modulesystem/moduleregistry.cpp | 31 +- libs/modulesystem/moduleregistry.h | 65 +- libs/modulesystem/modulesmap.cpp | 30 +- libs/modulesystem/modulesmap.h | 213 +- libs/modulesystem/singletonmodule.cpp | 54 +- libs/modulesystem/singletonmodule.h | 203 +- libs/os/dir.cpp | 31 +- libs/os/dir.h | 87 +- libs/os/file.cpp | 31 +- libs/os/file.h | 134 +- libs/os/path.cpp | 30 +- libs/os/path.h | 300 +- libs/picomodel.h | 420 +- libs/picomodel/lwo/clip.c | 536 +- libs/picomodel/lwo/envelope.c | 1033 +- libs/picomodel/lwo/list.c | 165 +- libs/picomodel/lwo/lwio.c | 703 +- libs/picomodel/lwo/lwo2.c | 600 +- libs/picomodel/lwo/lwo2.h | 700 +- libs/picomodel/lwo/lwob.c | 1479 +- libs/picomodel/lwo/pntspols.c | 931 +- libs/picomodel/lwo/surface.c | 1914 +- libs/picomodel/lwo/vecmath.c | 41 +- libs/picomodel/lwo/vmap.c | 455 +- libs/picomodel/picointernal.c | 863 +- libs/picomodel/picointernal.h | 230 +- libs/picomodel/picomodel.c | 1848 +- libs/picomodel/picomodules.c | 90 +- libs/picomodel/pm_3ds.c | 561 +- libs/picomodel/pm_ase.c | 963 +- libs/picomodel/pm_fm.c | 524 +- libs/picomodel/pm_fm.h | 504 +- libs/picomodel/pm_lwo.c | 292 +- libs/picomodel/pm_md2.c | 707 +- libs/picomodel/pm_md3.c | 385 +- libs/picomodel/pm_mdc.c | 450 +- libs/picomodel/pm_ms3d.c | 319 +- libs/picomodel/pm_obj.c | 617 +- libs/picomodel/pm_terrain.c | 579 +- libs/pivot.cpp | 31 +- libs/pivot.h | 439 +- libs/profile/file.cpp | 505 +- libs/profile/file.h | 214 +- libs/profile/profile.cpp | 469 +- libs/profile/profile.h | 80 +- libs/render.cpp | 30 +- libs/render.h | 1915 +- libs/scenelib.cpp | 30 +- libs/scenelib.h | 1437 +- libs/script/scripttokeniser.cpp | 31 +- libs/script/scripttokeniser.h | 650 +- libs/script/scripttokenwriter.cpp | 31 +- libs/script/scripttokenwriter.h | 125 +- libs/selectionlib.cpp | 30 +- libs/selectionlib.h | 300 +- libs/shaderlib.cpp | 30 +- libs/shaderlib.h | 101 +- libs/signal/isignal.cpp | 1 - libs/signal/isignal.h | 263 +- libs/signal/signal.cpp | 167 +- libs/signal/signal.h | 592 +- libs/signal/signalfwd.cpp | 1 - libs/signal/signalfwd.h | 30 +- libs/splines/math_angles.cpp | 100 +- libs/splines/math_angles.h | 146 +- libs/splines/math_matrix.cpp | 74 +- libs/splines/math_matrix.h | 170 +- libs/splines/math_quaternion.cpp | 61 +- libs/splines/math_quaternion.h | 88 +- libs/splines/math_vector.cpp | 130 +- libs/splines/math_vector.h | 336 +- libs/splines/q_parse.cpp | 326 +- libs/splines/q_shared.cpp | 732 +- libs/splines/q_shared.h | 685 +- libs/splines/splines.cpp | 1320 +- libs/splines/splines.h | 1743 +- libs/splines/util_list.h | 241 +- libs/splines/util_str.cpp | 822 +- libs/splines/util_str.h | 980 +- libs/str.cpp | 46 +- libs/str.h | 835 +- libs/stream/filestream.cpp | 30 +- libs/stream/filestream.h | 269 +- libs/stream/memstream.cpp | 30 +- libs/stream/memstream.h | 101 +- libs/stream/stringstream.cpp | 30 +- libs/stream/stringstream.h | 259 +- libs/stream/textfilestream.cpp | 30 +- libs/stream/textfilestream.h | 103 +- libs/stream/textstream.cpp | 30 +- libs/stream/textstream.h | 587 +- libs/string/pooledstring.cpp | 28 +- libs/string/pooledstring.h | 145 +- libs/string/string.cpp | 37 +- libs/string/string.h | 661 +- libs/string/stringfwd.cpp | 31 +- libs/string/stringfwd.h | 32 +- libs/stringio.cpp | 30 +- libs/stringio.h | 694 +- libs/texturelib.cpp | 30 +- libs/texturelib.h | 49 +- libs/transformlib.cpp | 30 +- libs/transformlib.h | 229 +- libs/traverselib.cpp | 30 +- libs/traverselib.h | 591 +- libs/typesystem.cpp | 31 +- libs/typesystem.h | 141 +- libs/undolib.cpp | 30 +- libs/undolib.h | 230 +- libs/uniquenames.cpp | 31 +- libs/uniquenames.h | 527 +- libs/versionlib.cpp | 31 +- libs/versionlib.h | 115 +- libs/xml/ixml.cpp | 30 +- libs/xml/ixml.h | 50 +- libs/xml/xmlelement.cpp | 30 +- libs/xml/xmlelement.h | 146 +- libs/xml/xmlparser.cpp | 30 +- libs/xml/xmlparser.h | 341 +- libs/xml/xmltextags.cpp | 1075 +- libs/xml/xmltextags.h | 116 +- libs/xml/xmlwriter.cpp | 30 +- libs/xml/xmlwriter.h | 316 +- plugins/archivepak/archive.cpp | 321 +- plugins/archivepak/archive.h | 32 +- plugins/archivepak/pak.cpp | 31 +- plugins/archivepak/pak.h | 45 +- plugins/archivepak/plugin.cpp | 59 +- plugins/archivepak/plugin.h | 32 +- plugins/archivewad/archive.cpp | 355 +- plugins/archivewad/archive.h | 32 +- plugins/archivewad/plugin.cpp | 59 +- plugins/archivewad/plugin.h | 32 +- plugins/archivewad/wad.cpp | 31 +- plugins/archivewad/wad.h | 100 +- plugins/archivezip/archive.cpp | 563 +- plugins/archivezip/archive.h | 32 +- plugins/archivezip/pkzip.cpp | 31 +- plugins/archivezip/pkzip.h | 381 +- plugins/archivezip/plugin.cpp | 83 +- plugins/archivezip/plugin.h | 32 +- plugins/archivezip/zlibstream.cpp | 31 +- plugins/archivezip/zlibstream.h | 99 +- plugins/entity/angle.cpp | 31 +- plugins/entity/angle.h | 126 +- plugins/entity/angles.cpp | 31 +- plugins/entity/angles.h | 202 +- plugins/entity/colour.cpp | 31 +- plugins/entity/colour.h | 137 +- plugins/entity/curve.cpp | 31 +- plugins/entity/curve.h | 808 +- plugins/entity/doom3group.cpp | 1389 +- plugins/entity/doom3group.h | 36 +- plugins/entity/eclassmodel.cpp | 860 +- plugins/entity/eclassmodel.h | 36 +- plugins/entity/entity.cpp | 568 +- plugins/entity/entity.h | 40 +- plugins/entity/filters.cpp | 88 +- plugins/entity/filters.h | 103 +- plugins/entity/generic.cpp | 776 +- plugins/entity/generic.h | 34 +- plugins/entity/group.cpp | 788 +- plugins/entity/group.h | 34 +- plugins/entity/keyobservers.cpp | 31 +- plugins/entity/keyobservers.h | 69 +- plugins/entity/light.cpp | 3204 ++- plugins/entity/light.h | 44 +- plugins/entity/miscmodel.cpp | 770 +- plugins/entity/miscmodel.h | 34 +- plugins/entity/model.cpp | 31 +- plugins/entity/model.h | 179 +- plugins/entity/modelskinkey.cpp | 31 +- plugins/entity/modelskinkey.h | 146 +- plugins/entity/namedentity.cpp | 31 +- plugins/entity/namedentity.h | 146 +- plugins/entity/namekeys.cpp | 31 +- plugins/entity/namekeys.h | 203 +- plugins/entity/origin.cpp | 31 +- plugins/entity/origin.h | 209 +- plugins/entity/plugin.cpp | 176 +- plugins/entity/plugin.h | 32 +- plugins/entity/rotation.cpp | 31 +- plugins/entity/rotation.h | 304 +- plugins/entity/scale.cpp | 31 +- plugins/entity/scale.h | 185 +- plugins/entity/skincache.cpp | 532 +- plugins/entity/skincache.h | 34 +- plugins/entity/targetable.cpp | 40 +- plugins/entity/targetable.h | 659 +- plugins/image/bmp.cpp | 308 +- plugins/image/bmp.h | 35 +- plugins/image/dds.cpp | 68 +- plugins/image/dds.h | 34 +- plugins/image/image.cpp | 155 +- plugins/image/image.h | 32 +- plugins/image/jpeg.cpp | 479 +- plugins/image/jpeg.h | 63 +- plugins/image/pcx.cpp | 361 +- plugins/image/pcx.h | 34 +- plugins/image/tga.cpp | 563 +- plugins/image/tga.h | 35 +- plugins/imagehl/hlw.cpp | 187 +- plugins/imagehl/hlw.h | 35 +- plugins/imagehl/imagehl.cpp | 107 +- plugins/imagehl/imagehl.h | 32 +- plugins/imagehl/mip.cpp | 329 +- plugins/imagehl/mip.h | 35 +- plugins/imagehl/sprite.cpp | 340 +- plugins/imagehl/sprite.h | 35 +- plugins/imagepng/plugin.cpp | 311 +- plugins/imagepng/plugin.h | 32 +- plugins/imageq2/imageq2.cpp | 107 +- plugins/imageq2/imageq2.h | 32 +- plugins/imageq2/wal.cpp | 215 +- plugins/imageq2/wal.h | 37 +- plugins/imageq2/wal32.cpp | 129 +- plugins/imageq2/wal32.h | 35 +- plugins/mapq3/parse.cpp | 217 +- plugins/mapq3/parse.h | 38 +- plugins/mapq3/plugin.cpp | 977 +- plugins/mapq3/plugin.h | 32 +- plugins/mapq3/write.cpp | 182 +- plugins/mapq3/write.h | 34 +- plugins/mapxml/plugin.cpp | 127 +- plugins/mapxml/plugin.h | 32 +- plugins/mapxml/xmlparse.cpp | 382 +- plugins/mapxml/xmlparse.h | 34 +- plugins/mapxml/xmlwrite.cpp | 120 +- plugins/mapxml/xmlwrite.h | 34 +- plugins/md3model/ident.h | 37 +- plugins/md3model/md2.cpp | 419 +- plugins/md3model/md2.h | 34 +- plugins/md3model/md3.cpp | 435 +- plugins/md3model/md3.h | 34 +- plugins/md3model/md3normals.cpp | 31 +- plugins/md3model/md3normals.h | 50 +- plugins/md3model/md5.cpp | 729 +- plugins/md3model/md5.h | 34 +- plugins/md3model/mdc.cpp | 310 +- plugins/md3model/mdc.h | 34 +- plugins/md3model/mdl.cpp | 392 +- plugins/md3model/mdl.h | 34 +- plugins/md3model/mdlformat.cpp | 31 +- plugins/md3model/mdlformat.h | 110 +- plugins/md3model/mdlimage.cpp | 246 +- plugins/md3model/mdlimage.h | 34 +- plugins/md3model/mdlnormals.cpp | 31 +- plugins/md3model/mdlnormals.h | 356 +- plugins/md3model/model.cpp | 31 +- plugins/md3model/model.h | 1042 +- plugins/md3model/plugin.cpp | 230 +- plugins/md3model/plugin.h | 32 +- plugins/model/model.cpp | 1712 +- plugins/model/model.h | 34 +- plugins/model/plugin.cpp | 211 +- plugins/model/plugin.h | 32 +- plugins/sample/sample.cpp | 114 +- plugins/sample/sample.h | 32 +- plugins/shaders/plugin.cpp | 188 +- plugins/shaders/plugin.h | 32 +- plugins/shaders/shaders.cpp | 3334 ++- plugins/shaders/shaders.h | 66 +- plugins/spritemodel/plugin.cpp | 190 +- plugins/spritemodel/plugin.h | 28 +- plugins/spritemodel/spritemodel.cpp | 239 +- plugins/spritemodel/spritemodel.h | 63 +- plugins/textool/2DView.cpp | 303 +- plugins/textool/2DView.h | 87 +- plugins/textool/ControlPointsManager.cpp | 526 +- plugins/textool/ControlPointsManager.h | 164 +- plugins/textool/StdAfx.cpp | 30 +- plugins/textool/StdAfx.h | 112 +- plugins/textool/TexTool.cpp | 1610 +- plugins/textool/resource.h | 2 +- plugins/vfspk3/archive.cpp | 254 +- plugins/vfspk3/archive.h | 34 +- plugins/vfspk3/vfs.cpp | 1080 +- plugins/vfspk3/vfs.h | 60 +- plugins/vfspk3/vfspk3.cpp | 89 +- plugins/vfspk3/vfspk3.h | 32 +- radiant/autosave.cpp | 311 +- radiant/autosave.h | 32 +- radiant/brush.cpp | 649 +- radiant/brush.h | 6944 +++--- radiant/brush_primit.cpp | 1942 +- radiant/brush_primit.h | 165 +- radiant/brushmanip.cpp | 2204 +- radiant/brushmanip.h | 102 +- radiant/brushmodule.cpp | 552 +- radiant/brushmodule.h | 34 +- radiant/brushnode.cpp | 31 +- radiant/brushnode.h | 267 +- radiant/brushtokens.cpp | 31 +- radiant/brushtokens.h | 1174 +- radiant/brushxml.cpp | 31 +- radiant/brushxml.h | 760 +- radiant/build.cpp | 1729 +- radiant/build.h | 48 +- radiant/camwindow.cpp | 3096 ++- radiant/camwindow.h | 79 +- radiant/clippertool.cpp | 31 +- radiant/clippertool.h | 32 +- radiant/commands.cpp | 842 +- radiant/commands.h | 54 +- radiant/console.cpp | 363 +- radiant/console.h | 38 +- radiant/csg.cpp | 1028 +- radiant/csg.h | 50 +- radiant/dialog.cpp | 833 +- radiant/dialog.h | 249 +- radiant/eclass.cpp | 532 +- radiant/eclass.h | 32 +- radiant/eclass_def.cpp | 532 +- radiant/eclass_def.h | 32 +- radiant/eclass_doom3.cpp | 1528 +- radiant/eclass_doom3.h | 32 +- radiant/eclass_fgd.cpp | 1342 +- radiant/eclass_fgd.h | 32 +- radiant/eclass_xml.cpp | 768 +- radiant/eclass_xml.h | 32 +- radiant/entity.cpp | 1002 +- radiant/entity.h | 42 +- radiant/entityinspector.cpp | 2812 ++- radiant/entityinspector.h | 34 +- radiant/entitylist.cpp | 552 +- radiant/entitylist.h | 34 +- radiant/environment.cpp | 450 +- radiant/environment.h | 34 +- radiant/error.cpp | 181 +- radiant/error.h | 34 +- radiant/feedback.cpp | 521 +- radiant/feedback.h | 245 +- radiant/filetypes.cpp | 202 +- radiant/filetypes.h | 34 +- radiant/filters.cpp | 419 +- radiant/filters.h | 34 +- radiant/findtexturedialog.cpp | 412 +- radiant/findtexturedialog.h | 36 +- radiant/glwidget.cpp | 63 +- radiant/glwidget.h | 32 +- radiant/grid.cpp | 373 +- radiant/grid.h | 36 +- radiant/groupdialog.cpp | 253 +- radiant/groupdialog.h | 45 +- radiant/gtkdlgs.cpp | 1794 +- radiant/gtkdlgs.h | 72 +- radiant/gtkmisc.cpp | 227 +- radiant/gtkmisc.h | 93 +- radiant/help.cpp | 196 +- radiant/help.h | 34 +- radiant/image.cpp | 84 +- radiant/image.h | 34 +- radiant/main.cpp | 1028 +- radiant/main.h | 32 +- radiant/mainframe.cpp | 5019 ++-- radiant/mainframe.h | 268 +- radiant/map.cpp | 3432 ++- radiant/map.h | 150 +- radiant/mru.cpp | 346 +- radiant/mru.h | 36 +- radiant/multimon.cpp | 142 +- radiant/multimon.h | 51 +- radiant/nullmodel.cpp | 305 +- radiant/nullmodel.h | 34 +- radiant/parse.cpp | 58 +- radiant/parse.h | 32 +- radiant/patch.cpp | 5535 +++-- radiant/patch.h | 3371 ++- radiant/patchdialog.cpp | 1995 +- radiant/patchdialog.h | 42 +- radiant/patchmanip.cpp | 1650 +- radiant/patchmanip.h | 54 +- radiant/patchmodule.cpp | 287 +- radiant/patchmodule.h | 32 +- radiant/plugin.cpp | 442 +- radiant/plugin.h | 34 +- radiant/pluginapi.cpp | 89 +- radiant/pluginapi.h | 32 +- radiant/pluginmanager.cpp | 329 +- radiant/pluginmanager.h | 70 +- radiant/pluginmenu.cpp | 283 +- radiant/pluginmenu.h | 32 +- radiant/plugintoolbar.cpp | 207 +- radiant/plugintoolbar.h | 34 +- radiant/points.cpp | 537 +- radiant/points.h | 34 +- radiant/preferencedictionary.cpp | 31 +- radiant/preferencedictionary.h | 476 +- radiant/preferences.cpp | 1520 +- radiant/preferences.h | 618 +- radiant/qe3.cpp | 521 +- radiant/qe3.h | 58 +- radiant/qgl.cpp | 2787 ++- radiant/qgl.h | 38 +- radiant/referencecache.cpp | 1225 +- radiant/referencecache.h | 38 +- radiant/renderer.cpp | 31 +- radiant/renderer.h | 281 +- radiant/renderstate.cpp | 4346 ++-- radiant/renderstate.h | 34 +- radiant/resource.h | 2 +- radiant/scenegraph.cpp | 436 +- radiant/scenegraph.h | 32 +- radiant/select.cpp | 1828 +- radiant/select.h | 69 +- radiant/selection.cpp | 6492 +++--- radiant/selection.h | 44 +- radiant/server.cpp | 401 +- radiant/server.h | 34 +- radiant/shaders.cpp | 112 +- radiant/shaders.h | 34 +- radiant/sockets.cpp | 40 +- radiant/sockets.h | 4 +- radiant/stacktrace.cpp | 480 +- radiant/stacktrace.h | 34 +- radiant/surfacedialog.cpp | 3123 ++- radiant/surfacedialog.h | 61 +- radiant/texmanip.cpp | 691 +- radiant/texmanip.h | 52 +- radiant/textureentry.cpp | 31 +- radiant/textureentry.h | 162 +- radiant/textures.cpp | 1407 +- radiant/textures.h | 34 +- radiant/texwindow.cpp | 4091 ++-- radiant/texwindow.h | 52 +- radiant/timer.cpp | 135 +- radiant/timer.h | 114 +- radiant/treemodel.cpp | 2230 +- radiant/treemodel.h | 40 +- radiant/undo.cpp | 910 +- radiant/undo.h | 32 +- radiant/url.cpp | 73 +- radiant/url.h | 34 +- radiant/view.cpp | 58 +- radiant/view.h | 302 +- radiant/watchbsp.cpp | 1365 +- radiant/watchbsp.h | 64 +- radiant/winding.cpp | 525 +- radiant/winding.h | 417 +- radiant/windowobservers.cpp | 225 +- radiant/windowobservers.h | 88 +- radiant/xmlstuff.cpp | 47 +- radiant/xmlstuff.h | 94 +- radiant/xywindow.cpp | 4353 ++-- radiant/xywindow.h | 449 +- tools/quake2/common/bspfile.c | 981 +- tools/quake2/common/bspfile.h | 157 +- tools/quake2/common/cmdlib.c | 1263 +- tools/quake2/common/cmdlib.h | 156 +- tools/quake2/common/inout.c | 523 +- tools/quake2/common/inout.h | 46 +- tools/quake2/common/l3dslib.c | 251 +- tools/quake2/common/l3dslib.h | 33 +- tools/quake2/common/lbmlib.c | 960 +- tools/quake2/common/lbmlib.h | 52 +- tools/quake2/common/mathlib.c | 168 +- tools/quake2/common/mathlib.h | 86 +- tools/quake2/common/md4.c | 216 +- tools/quake2/common/md4.h | 51 +- tools/quake2/common/path_init.c | 436 +- tools/quake2/common/polylib.c | 819 +- tools/quake2/common/polylib.h | 76 +- tools/quake2/common/q2_threads.h | 44 +- tools/quake2/common/qfiles.h | 616 +- tools/quake2/common/scriplib.c | 293 +- tools/quake2/common/scriplib.h | 54 +- tools/quake2/common/threads.c | 748 +- tools/quake2/common/trilib.c | 158 +- tools/quake2/common/trilib.h | 37 +- tools/quake2/q2map/brushbsp.c | 1422 +- tools/quake2/q2map/csg.c | 701 +- tools/quake2/q2map/faces.c | 1176 +- tools/quake2/q2map/flow.c | 937 +- tools/quake2/q2map/gldraw.c | 262 +- tools/quake2/q2map/glfile.c | 183 +- tools/quake2/q2map/leakfile.c | 260 +- tools/quake2/q2map/lightmap.c | 1429 +- tools/quake2/q2map/main.c | 966 +- tools/quake2/q2map/map.c | 1095 +- tools/quake2/q2map/nodraw.c | 46 +- tools/quake2/q2map/patches.c | 618 +- tools/quake2/q2map/portals.c | 1219 +- tools/quake2/q2map/prtfile.c | 336 +- tools/quake2/q2map/q2map.h | 36 +- tools/quake2/q2map/qbsp.c | 535 +- tools/quake2/q2map/qbsp.h | 422 +- tools/quake2/q2map/qrad.c | 717 +- tools/quake2/q2map/qrad.h | 172 +- tools/quake2/q2map/qvis.c | 733 +- tools/quake2/q2map/qvis.h | 172 +- tools/quake2/q2map/textures.c | 295 +- tools/quake2/q2map/trace.c | 288 +- tools/quake2/q2map/tree.c | 234 +- tools/quake2/q2map/writebsp.c | 586 +- tools/quake2/qdata/anorms.h | 324 +- tools/quake2/qdata/images.c | 888 +- tools/quake2/qdata/models.c | 1205 +- tools/quake2/qdata/qdata.c | 702 +- tools/quake2/qdata/qdata.h | 108 +- tools/quake2/qdata/sprites.c | 275 +- tools/quake2/qdata/tables.c | 199 +- tools/quake2/qdata/video.c | 1313 +- tools/quake2/qdata_heretic2/adpcm.h | 54 +- tools/quake2/qdata_heretic2/animcomp.c | 491 +- tools/quake2/qdata_heretic2/animcomp.h | 49 +- tools/quake2/qdata_heretic2/anorms.h | 355 +- tools/quake2/qdata_heretic2/book.c | 338 +- tools/quake2/qdata_heretic2/common/bspfile.c | 988 +- tools/quake2/qdata_heretic2/common/bspfile.h | 156 +- tools/quake2/qdata_heretic2/common/cmdlib.c | 1264 +- tools/quake2/qdata_heretic2/common/cmdlib.h | 164 +- .../qdata_heretic2/common/her2_threads.h | 44 +- tools/quake2/qdata_heretic2/common/inout.c | 523 +- tools/quake2/qdata_heretic2/common/inout.h | 46 +- tools/quake2/qdata_heretic2/common/l3dslib.c | 444 +- tools/quake2/qdata_heretic2/common/l3dslib.h | 36 +- tools/quake2/qdata_heretic2/common/lbmlib.c | 1141 +- tools/quake2/qdata_heretic2/common/lbmlib.h | 54 +- tools/quake2/qdata_heretic2/common/mathlib.c | 172 +- tools/quake2/qdata_heretic2/common/mathlib.h | 102 +- tools/quake2/qdata_heretic2/common/md4.c | 216 +- tools/quake2/qdata_heretic2/common/md4.h | 51 +- .../quake2/qdata_heretic2/common/path_init.c | 438 +- tools/quake2/qdata_heretic2/common/polylib.c | 839 +- tools/quake2/qdata_heretic2/common/polylib.h | 76 +- tools/quake2/qdata_heretic2/common/qfiles.c | 90 +- tools/quake2/qdata_heretic2/common/qfiles.h | 636 +- tools/quake2/qdata_heretic2/common/scriplib.c | 293 +- tools/quake2/qdata_heretic2/common/scriplib.h | 54 +- tools/quake2/qdata_heretic2/common/threads.c | 747 +- tools/quake2/qdata_heretic2/common/token.c | 393 +- tools/quake2/qdata_heretic2/common/token.h | 90 +- tools/quake2/qdata_heretic2/common/trilib.c | 1286 +- tools/quake2/qdata_heretic2/common/trilib.h | 52 +- tools/quake2/qdata_heretic2/fmodels.c | 3533 ++- tools/quake2/qdata_heretic2/images.c | 1580 +- tools/quake2/qdata_heretic2/jointed.c | 450 +- tools/quake2/qdata_heretic2/jointed.h | 36 +- tools/quake2/qdata_heretic2/joints.h | 104 +- tools/quake2/qdata_heretic2/models.c | 2031 +- tools/quake2/qdata_heretic2/pics.c | 246 +- tools/quake2/qdata_heretic2/qcommon/angles.h | 111 +- .../qdata_heretic2/qcommon/arrayedlist.h | 58 +- tools/quake2/qdata_heretic2/qcommon/flex.h | 40 +- tools/quake2/qdata_heretic2/qcommon/fmodel.h | 168 +- .../quake2/qdata_heretic2/qcommon/h2common.h | 31 +- .../quake2/qdata_heretic2/qcommon/placement.h | 32 +- .../quake2/qdata_heretic2/qcommon/q_typedef.h | 42 +- tools/quake2/qdata_heretic2/qcommon/qfiles.h | 601 +- .../quake2/qdata_heretic2/qcommon/reference.c | 78 +- .../quake2/qdata_heretic2/qcommon/reference.h | 102 +- .../qdata_heretic2/qcommon/resourcemanager.c | 101 +- .../qdata_heretic2/qcommon/resourcemanager.h | 42 +- .../quake2/qdata_heretic2/qcommon/skeletons.c | 155 +- .../quake2/qdata_heretic2/qcommon/skeletons.h | 48 +- tools/quake2/qdata_heretic2/qd_fmodel.h | 64 +- tools/quake2/qdata_heretic2/qd_skeletons.c | 956 +- tools/quake2/qdata_heretic2/qd_skeletons.h | 44 +- tools/quake2/qdata_heretic2/qdata.c | 968 +- tools/quake2/qdata_heretic2/qdata.h | 220 +- tools/quake2/qdata_heretic2/resource.h | 2 +- tools/quake2/qdata_heretic2/sprites.c | 396 +- tools/quake2/qdata_heretic2/svdcmp.c | 711 +- tools/quake2/qdata_heretic2/tables.c | 199 +- tools/quake2/qdata_heretic2/tmix.c | 747 +- tools/quake2/qdata_heretic2/video.c | 1085 +- tools/quake3/common/aselib.c | 521 +- tools/quake3/common/aselib.h | 38 +- tools/quake3/common/bspfile.c | 713 +- tools/quake3/common/bspfile.h | 149 +- tools/quake3/common/cmdlib.c | 1182 +- tools/quake3/common/cmdlib.h | 140 +- tools/quake3/common/imagelib.c | 1414 +- tools/quake3/common/imagelib.h | 61 +- tools/quake3/common/inout.c | 531 +- tools/quake3/common/inout.h | 44 +- tools/quake3/common/jpeg.c | 496 +- tools/quake3/common/l3dslib.c | 253 +- tools/quake3/common/l3dslib.h | 33 +- tools/quake3/common/md4.c | 216 +- tools/quake3/common/md4.h | 51 +- tools/quake3/common/mutex.c | 178 +- tools/quake3/common/mutex.h | 36 +- tools/quake3/common/polylib.c | 1278 +- tools/quake3/common/polylib.h | 96 +- tools/quake3/common/polyset.h | 40 +- tools/quake3/common/qfiles.h | 522 +- tools/quake3/common/qthreads.h | 45 +- tools/quake3/common/scriplib.c | 417 +- tools/quake3/common/scriplib.h | 64 +- tools/quake3/common/surfaceflags.h | 166 +- tools/quake3/common/threads.c | 786 +- tools/quake3/common/trilib.c | 195 +- tools/quake3/common/trilib.h | 31 +- tools/quake3/common/unzip.c | 5630 ++--- tools/quake3/common/unzip.h | 316 +- tools/quake3/common/vfs.c | 684 +- tools/quake3/common/vfs.h | 72 +- tools/quake3/q3data/3dslib.c | 306 +- tools/quake3/q3data/3dslib.h | 136 +- tools/quake3/q3data/compress.c | 776 +- tools/quake3/q3data/images.c | 571 +- tools/quake3/q3data/md3lib.c | 101 +- tools/quake3/q3data/md3lib.h | 30 +- tools/quake3/q3data/models.c | 1344 +- tools/quake3/q3data/oldstuff.c | 152 +- tools/quake3/q3data/p3dlib.c | 159 +- tools/quake3/q3data/p3dlib.h | 34 +- tools/quake3/q3data/polyset.c | 104 +- tools/quake3/q3data/q3data.c | 632 +- tools/quake3/q3data/q3data.h | 118 +- tools/quake3/q3data/stripper.c | 148 +- tools/quake3/q3data/video.c | 724 +- tools/quake3/q3map2/brush.c | 1133 +- tools/quake3/q3map2/brush_primit.c | 84 +- tools/quake3/q3map2/bsp.c | 895 +- tools/quake3/q3map2/bspfile_abstract.c | 821 +- tools/quake3/q3map2/bspfile_ibsp.c | 475 +- tools/quake3/q3map2/bspfile_rbsp.c | 320 +- tools/quake3/q3map2/convert_ase.c | 374 +- tools/quake3/q3map2/convert_map.c | 811 +- tools/quake3/q3map2/convert_obj.c | 301 +- tools/quake3/q3map2/decals.c | 785 +- tools/quake3/q3map2/facebsp.c | 452 +- tools/quake3/q3map2/fog.c | 626 +- tools/quake3/q3map2/game__null.h | 123 +- tools/quake3/q3map2/game_darkplaces.h | 215 +- tools/quake3/q3map2/game_dq.h | 215 +- tools/quake3/q3map2/game_ef.h | 317 +- tools/quake3/q3map2/game_etut.h | 449 +- tools/quake3/q3map2/game_ja.h | 304 +- tools/quake3/q3map2/game_jk2.h | 296 +- tools/quake3/q3map2/game_nexuiz.h | 223 +- tools/quake3/q3map2/game_prophecy.h | 215 +- tools/quake3/q3map2/game_qfusion.h | 321 +- tools/quake3/q3map2/game_quake3.h | 309 +- tools/quake3/q3map2/game_quakelive.h | 221 +- tools/quake3/q3map2/game_reaction.h | 288 +- tools/quake3/q3map2/game_sof2.h | 442 +- tools/quake3/q3map2/game_t.h | 43 +- tools/quake3/q3map2/game_tenebrae.h | 311 +- tools/quake3/q3map2/game_tremulous.h | 241 +- tools/quake3/q3map2/game_wolf.h | 397 +- tools/quake3/q3map2/game_wolfet.h | 275 +- tools/quake3/q3map2/game_xonotic.h | 77 +- tools/quake3/q3map2/image.c | 390 +- tools/quake3/q3map2/leakfile.c | 137 +- tools/quake3/q3map2/light.c | 2448 +- tools/quake3/q3map2/light_bounce.c | 859 +- tools/quake3/q3map2/light_shadows.c | 120 +- tools/quake3/q3map2/light_trace.c | 1725 +- tools/quake3/q3map2/light_ydnar.c | 3934 ++-- tools/quake3/q3map2/lightmaps.c | 110 +- tools/quake3/q3map2/lightmaps_ydnar.c | 3034 +-- tools/quake3/q3map2/main.c | 1583 +- tools/quake3/q3map2/map.c | 1591 +- tools/quake3/q3map2/mesh.c | 669 +- tools/quake3/q3map2/model.c | 811 +- tools/quake3/q3map2/patch.c | 450 +- tools/quake3/q3map2/path_init.c | 563 +- tools/quake3/q3map2/portals.c | 1036 +- tools/quake3/q3map2/prtfile.c | 416 +- tools/quake3/q3map2/q3map2.h | 3092 +-- tools/quake3/q3map2/shaders.c | 1983 +- tools/quake3/q3map2/surface.c | 3575 +-- tools/quake3/q3map2/surface_extra.c | 418 +- tools/quake3/q3map2/surface_foliage.c | 356 +- tools/quake3/q3map2/surface_fur.c | 117 +- tools/quake3/q3map2/surface_meta.c | 1755 +- tools/quake3/q3map2/tjunction.c | 482 +- tools/quake3/q3map2/tree.c | 166 +- tools/quake3/q3map2/vis.c | 1290 +- tools/quake3/q3map2/visflow.c | 1660 +- tools/quake3/q3map2/writebsp.c | 548 +- 1056 files changed, 202237 insertions(+), 213598 deletions(-) diff --git a/conftest.cpp b/conftest.cpp index 76529358..10b7a620 100644 --- a/conftest.cpp +++ b/conftest.cpp @@ -1,7 +1,6 @@ #include /* jpeglib.h needs it */ #include CONFTEST_HEADER -int main() -{ +int main(){ (void) CONFTEST_SYMBOL; return 0; } diff --git a/contrib/bkgrnd2d/bkgrnd2d.cpp b/contrib/bkgrnd2d/bkgrnd2d.cpp index 36cf45e2..b1159525 100644 --- a/contrib/bkgrnd2d/bkgrnd2d.cpp +++ b/contrib/bkgrnd2d/bkgrnd2d.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // bkgrnd2d Plugin @@ -30,25 +30,21 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA CBackgroundRender render; -CBackgroundImage backgroundXY(XY),backgroundXZ(XZ),backgroundYZ(YZ); +CBackgroundImage backgroundXY( XY ),backgroundXZ( XZ ),backgroundYZ( YZ ); -CBackgroundRender::CBackgroundRender() -{ +CBackgroundRender::CBackgroundRender(){ refCount = 1; } -CBackgroundRender::~CBackgroundRender() -{ +CBackgroundRender::~CBackgroundRender(){ } -void CBackgroundRender::Register() -{ +void CBackgroundRender::Register(){ g_QglTable.m_pfnHookGL2DWindow( this ); } -void CBackgroundRender::Draw2D( VIEWTYPE vt ) -{ - switch(vt) +void CBackgroundRender::Draw2D( VIEWTYPE vt ){ + switch ( vt ) { case XY: backgroundXY.Render(); @@ -63,8 +59,7 @@ void CBackgroundRender::Draw2D( VIEWTYPE vt ) } -CBackgroundImage::CBackgroundImage(VIEWTYPE vt) -{ +CBackgroundImage::CBackgroundImage( VIEWTYPE vt ){ m_tex = NULL; m_alpha = 0.5; @@ -76,159 +71,154 @@ CBackgroundImage::CBackgroundImage(VIEWTYPE vt) m_vt = vt; - switch(m_vt) + switch ( m_vt ) { - case XY: - m_ix = 0; - m_iy = 1; - break; - case XZ: - m_ix = 0; - m_iy = 2; - break; - case YZ: - m_ix = 1; - m_iy = 2; - break; + case XY: + m_ix = 0; + m_iy = 1; + break; + case XZ: + m_ix = 0; + m_iy = 2; + break; + case YZ: + m_ix = 1; + m_iy = 2; + break; } } /* - * should cleanup, but I don't think we can be sure it happens before our + * should cleanup, but I don't think we can be sure it happens before our * interfaces are gone -CBackgroundImage::~CBackgroundImage() -{ -} -*/ - -void CBackgroundImage::Cleanup() -{ - if(m_tex) { - g_QglTable.m_pfn_qglDeleteTextures(1,&m_tex->texture_number); - g_free(m_tex); + CBackgroundImage::~CBackgroundImage() + { + } + */ + +void CBackgroundImage::Cleanup(){ + if ( m_tex ) { + g_QglTable.m_pfn_qglDeleteTextures( 1,&m_tex->texture_number ); + g_free( m_tex ); m_tex = NULL; } } -void CBackgroundImage::Render() -{ - if (!m_bActive || !Valid()) +void CBackgroundImage::Render(){ + if ( !m_bActive || !Valid() ) { return; - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); + } + g_QglTable.m_pfn_qglPushAttrib( GL_ALL_ATTRIB_BITS ); - g_QglTable.m_pfn_qglEnable(GL_TEXTURE_2D); - g_QglTable.m_pfn_qglEnable(GL_BLEND); - g_QglTable.m_pfn_qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - g_QglTable.m_pfn_qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - g_QglTable.m_pfn_qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - g_QglTable.m_pfn_qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); + g_QglTable.m_pfn_qglEnable( GL_TEXTURE_2D ); + g_QglTable.m_pfn_qglEnable( GL_BLEND ); + g_QglTable.m_pfn_qglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + g_QglTable.m_pfn_qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + g_QglTable.m_pfn_qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ); + g_QglTable.m_pfn_qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP ); - g_QglTable.m_pfn_qglPolygonMode(GL_FRONT,GL_FILL); + g_QglTable.m_pfn_qglPolygonMode( GL_FRONT,GL_FILL ); // TODO, just so we can tell if we end up going the wrong way // g_QglTable.m_pfn_qglPolygonMode(GL_BACK,GL_LINE); // TODO any other state we should not assume ? - g_QglTable.m_pfn_qglBindTexture(GL_TEXTURE_2D, m_tex->texture_number); - g_QglTable.m_pfn_qglBegin(GL_QUADS); + g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, m_tex->texture_number ); + g_QglTable.m_pfn_qglBegin( GL_QUADS ); - g_QglTable.m_pfn_qglColor4f(1.0,1.0,1.0,m_alpha); - g_QglTable.m_pfn_qglTexCoord2f(0.0,1.0); - g_QglTable.m_pfn_qglVertex2f(m_xmin,m_ymin); + g_QglTable.m_pfn_qglColor4f( 1.0,1.0,1.0,m_alpha ); + g_QglTable.m_pfn_qglTexCoord2f( 0.0,1.0 ); + g_QglTable.m_pfn_qglVertex2f( m_xmin,m_ymin ); - g_QglTable.m_pfn_qglTexCoord2f(1.0,1.0); - g_QglTable.m_pfn_qglVertex2f(m_xmax,m_ymin); + g_QglTable.m_pfn_qglTexCoord2f( 1.0,1.0 ); + g_QglTable.m_pfn_qglVertex2f( m_xmax,m_ymin ); - g_QglTable.m_pfn_qglTexCoord2f(1.0,0.0); - g_QglTable.m_pfn_qglVertex2f(m_xmax,m_ymax); + g_QglTable.m_pfn_qglTexCoord2f( 1.0,0.0 ); + g_QglTable.m_pfn_qglVertex2f( m_xmax,m_ymax ); - g_QglTable.m_pfn_qglTexCoord2f(0.0,0.0); - g_QglTable.m_pfn_qglVertex2f(m_xmin,m_ymax); + g_QglTable.m_pfn_qglTexCoord2f( 0.0,0.0 ); + g_QglTable.m_pfn_qglVertex2f( m_xmin,m_ymax ); g_QglTable.m_pfn_qglEnd(); - g_QglTable.m_pfn_qglBindTexture(GL_TEXTURE_2D, 0); + g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, 0 ); g_QglTable.m_pfn_qglPopAttrib(); } -bool CBackgroundImage::Load(const char *filename) -{ +bool CBackgroundImage::Load( const char *filename ){ qtexture_t *newtex; - + unsigned char *image = NULL; // gets allocated with what ? g_malloc int width = 0, height = 0; - g_FuncTable.m_pfnLoadImage(filename,&image,&width,&height); + g_FuncTable.m_pfnLoadImage( filename,&image,&width,&height ); - if(!image) { - Syn_Printf(MSG_WARN "load %s failed\n",filename); + if ( !image ) { + Syn_Printf( MSG_WARN "load %s failed\n",filename ); return false; } // just in case we want to build for an old version // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=900 #ifdef BKGRND2D_JPG_WORKAROUND - if ( strlen(filename) > 4 && !strcmp(".jpg",filename + strlen(filename) - 4)) { - Syn_Printf(MSG_PREFIX ".jpg workaround, clearing alpha channel\n"); - int size = width*height*4; + if ( strlen( filename ) > 4 && !strcmp( ".jpg",filename + strlen( filename ) - 4 ) ) { + Syn_Printf( MSG_PREFIX ".jpg workaround, clearing alpha channel\n" ); + int size = width * height * 4; int i; - for (i = 3; i < size; i+=4) { + for ( i = 3; i < size; i += 4 ) { image[i] = 255; } } #endif - + //TODO bug for stored texture size //TODO whose gl context are we in, anyway ? - newtex = g_FuncTable.m_pfnLoadTextureRGBA(image,width,height); + newtex = g_FuncTable.m_pfnLoadTextureRGBA( image,width,height ); - g_free(image); + g_free( image ); - if(!newtex) { - Syn_Printf(MSG_WARN "image to texture failed\n"); + if ( !newtex ) { + Syn_Printf( MSG_WARN "image to texture failed\n" ); return false; } Cleanup(); m_tex = newtex; - g_FuncTable.m_pfnSysUpdateWindows(W_XY); + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); return true; } -bool CBackgroundImage::SetExtentsMM() -{ +bool CBackgroundImage::SetExtentsMM(){ entity_s *worldentity; const char *val; int xmin = 0, ymin = 0, xmax = 0, ymax = 0; - worldentity = (entity_s *)g_FuncTable.m_pfnGetEntityHandle(0); - if(!worldentity) { - Syn_Printf(MSG_WARN "SetExtentsMM worldspawn not found\n"); + worldentity = (entity_s *)g_FuncTable.m_pfnGetEntityHandle( 0 ); + if ( !worldentity ) { + Syn_Printf( MSG_WARN "SetExtentsMM worldspawn not found\n" ); return false; } //TODO val is not NULL even if key does not exist - val = g_EntityTable.m_pfnValueForKey(worldentity,"mapcoordsmins"); - if(!val || !val[0]) { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmins not found\n"); + val = g_EntityTable.m_pfnValueForKey( worldentity,"mapcoordsmins" ); + if ( !val || !val[0] ) { + Syn_Printf( MSG_WARN "SetExtentsMM mapcoordsmins not found\n" ); return false; } // we could be more robust // note contortions due to splashs strange idea of min and max - if(sscanf(val, "%d %d",&xmin,&ymax) != 2) - { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmins malformed\n"); + if ( sscanf( val, "%d %d",&xmin,&ymax ) != 2 ) { + Syn_Printf( MSG_WARN "SetExtentsMM mapcoordsmins malformed\n" ); return false; } - val = g_EntityTable.m_pfnValueForKey(worldentity,"mapcoordsmaxs"); - if(!val || !val[0]) { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmaxs not found\n"); + val = g_EntityTable.m_pfnValueForKey( worldentity,"mapcoordsmaxs" ); + if ( !val || !val[0] ) { + Syn_Printf( MSG_WARN "SetExtentsMM mapcoordsmaxs not found\n" ); return false; } - if(sscanf(val, "%d %d",&xmax,&ymin) != 2) - { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmaxs malformed\n"); + if ( sscanf( val, "%d %d",&xmax,&ymin ) != 2 ) { + Syn_Printf( MSG_WARN "SetExtentsMM mapcoordsmaxs malformed\n" ); return false; } //might do sanity check before we commit @@ -237,72 +227,74 @@ bool CBackgroundImage::SetExtentsMM() m_xmax = (float)xmax; m_ymax = (float)ymax; - g_FuncTable.m_pfnSysUpdateWindows(W_XY); + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); return true; } // TODO, this should just be exported from core // ripped directly from radiant/select.cpp:Select_GetBounds // -static bool get_selection_bounds (vec3_t mins, vec3_t maxs) -{ - brush_t *b; - int i; +static bool get_selection_bounds( vec3_t mins, vec3_t maxs ){ + brush_t *b; + int i; brush_t *selected_brushes = g_DataTable.m_pfnSelectedBrushes(); //TODO should never happen - if(!selected_brushes) { - Sys_Printf (MSG_PREFIX "selected_brushes = NULL\n"); - return false; + if ( !selected_brushes ) { + Sys_Printf( MSG_PREFIX "selected_brushes = NULL\n" ); + return false; } // this should mean no selection - if(selected_brushes == selected_brushes->next) { - Sys_Printf (MSG_PREFIX "nothing selected\n"); + if ( selected_brushes == selected_brushes->next ) { + Sys_Printf( MSG_PREFIX "nothing selected\n" ); - return false; + return false; } - for (i=0 ; i<3 ; i++) + for ( i = 0 ; i < 3 ; i++ ) { mins[i] = 99999; maxs[i] = -99999; } - for (b=selected_brushes->next ; b != selected_brushes ; b=b->next) + for ( b = selected_brushes->next ; b != selected_brushes ; b = b->next ) { - if (b->owner->eclass->fixedsize) - { - for (i=0 ; i<3 ; i++) + if ( b->owner->eclass->fixedsize ) { + for ( i = 0 ; i < 3 ; i++ ) { - if (b->owner->origin[i] < mins[i]) + if ( b->owner->origin[i] < mins[i] ) { mins[i] = b->owner->origin[i]; - if (b->owner->origin[i] > maxs[i]) + } + if ( b->owner->origin[i] > maxs[i] ) { maxs[i] = b->owner->origin[i]; + } } } else { - for (i=0 ; i<3 ; i++) + for ( i = 0 ; i < 3 ; i++ ) { - if (b->mins[i] < mins[i]) + if ( b->mins[i] < mins[i] ) { mins[i] = b->mins[i]; - if (b->maxs[i] > maxs[i]) + } + if ( b->maxs[i] > maxs[i] ) { maxs[i] = b->maxs[i]; + } } } } - return true; + return true; } -bool CBackgroundImage::SetExtentsSel() -{ +bool CBackgroundImage::SetExtentsSel(){ vec3_t mins,maxs; - if(!get_selection_bounds(mins,maxs)) + if ( !get_selection_bounds( mins,maxs ) ) { return false; + } - if(((int)mins[m_ix] == (int)maxs[m_ix]) || - ((int)mins[m_iy] == (int)maxs[m_iy])) { - Syn_Printf(MSG_PREFIX "tiny selection\n"); + if ( ( (int)mins[m_ix] == (int)maxs[m_ix] ) || + ( (int)mins[m_iy] == (int)maxs[m_iy] ) ) { + Syn_Printf( MSG_PREFIX "tiny selection\n" ); return false; } @@ -311,8 +303,7 @@ bool CBackgroundImage::SetExtentsSel() m_xmax = maxs[m_ix]; m_ymax = maxs[m_iy]; - g_FuncTable.m_pfnSysUpdateWindows(W_XY); + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); - return true; + return true; } - diff --git a/contrib/bkgrnd2d/bkgrnd2d.h b/contrib/bkgrnd2d/bkgrnd2d.h index 3874cb19..41ee2713 100644 --- a/contrib/bkgrnd2d/bkgrnd2d.h +++ b/contrib/bkgrnd2d/bkgrnd2d.h @@ -1,22 +1,22 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // bkgrnd2d Plugin @@ -30,53 +30,56 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class CBackgroundImage { private: - qtexture_t *m_tex; - VIEWTYPE m_vt; - +qtexture_t *m_tex; +VIEWTYPE m_vt; + // which components of a vec3_t correspond to x and y in the image - unsigned m_ix,m_iy; +unsigned m_ix,m_iy; public: - CBackgroundImage(VIEWTYPE vt); +CBackgroundImage( VIEWTYPE vt ); // ~CBackgroundImage(); - float m_alpha; // vertex alpha - bool m_bActive; - +float m_alpha; // vertex alpha +bool m_bActive; + // x and y axis are in relation to the screen, not world, making rendering -// the same for each view type. Whoever sets them is responsible for +// the same for each view type. Whoever sets them is responsible for // shuffling. // units are world units. // TODO should be private - float m_xmin,m_ymin,m_xmax,m_ymax; +float m_xmin,m_ymin,m_xmax,m_ymax; // load file, create new tex, cleanup old tex, set new tex - bool Load(const char *filename); - void Cleanup(); // free texture, free tex, set make tex NULL - bool SetExtentsMM(); // set extents by ET mapcoordsmaxs/mapcoordsmins - bool SetExtentsSel(); // set extents by selection - void Render(); - bool Valid() { return (m_tex && (m_xmin != m_xmax) && (m_ymin != m_ymax)); } +bool Load( const char *filename ); +void Cleanup(); // free texture, free tex, set make tex NULL +bool SetExtentsMM(); // set extents by ET mapcoordsmaxs/mapcoordsmins +bool SetExtentsSel(); // set extents by selection +void Render(); +bool Valid() { return ( m_tex && ( m_xmin != m_xmax ) && ( m_ymin != m_ymax ) ); } }; class CBackgroundRender : public IGL2DWindow { public: - CBackgroundRender(); - virtual ~CBackgroundRender(); +CBackgroundRender(); +virtual ~CBackgroundRender(); protected: - int refCount; +int refCount; public: - // IGL2DWindow IGL3DWindow interface - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } - void Draw2D( VIEWTYPE vt ); - void Register(); +// IGL2DWindow IGL3DWindow interface +void IncRef() { refCount++; } +void DecRef() { + refCount--; if ( refCount <= 0 ) { + delete this; + } +} +void Draw2D( VIEWTYPE vt ); +void Register(); }; extern CBackgroundImage backgroundXY,backgroundXZ,backgroundYZ; extern CBackgroundRender render; - diff --git a/contrib/bkgrnd2d/dialog.cpp b/contrib/bkgrnd2d/dialog.cpp index 8d9a8455..6d63bc3f 100644 --- a/contrib/bkgrnd2d/dialog.cpp +++ b/contrib/bkgrnd2d/dialog.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // bkgrnd2d Plugin dialog @@ -41,142 +41,137 @@ static GtkTooltips *pTooltips; class CBackgroundDialogPage { private: - GtkWidget *m_pWidget; - GtkWidget *m_pTabLabel; - GtkWidget *m_pFileLabel; - GtkWidget *m_pPosLabel; - VIEWTYPE m_vt; - bool m_bValidFile; +GtkWidget *m_pWidget; +GtkWidget *m_pTabLabel; +GtkWidget *m_pFileLabel; +GtkWidget *m_pPosLabel; +VIEWTYPE m_vt; +bool m_bValidFile; public: - CBackgroundImage *m_pImage; - CBackgroundDialogPage( VIEWTYPE vt ); - void Append(GtkWidget *notebook); - void Browse(); - void Reload(); - void SetPosLabel(); +CBackgroundImage *m_pImage; +CBackgroundDialogPage( VIEWTYPE vt ); +void Append( GtkWidget *notebook ); +void Browse(); +void Reload(); +void SetPosLabel(); // ~BackgroundDialogPage(); }; // dialog page callbacks -static void browse_callback( GtkWidget *widget, gpointer data ) -{ - ((CBackgroundDialogPage *)data)->Browse(); +static void browse_callback( GtkWidget *widget, gpointer data ){ + ( (CBackgroundDialogPage *)data )->Browse(); } -static void reload_callback( GtkWidget *widget, gpointer data ) -{ - ((CBackgroundDialogPage *)data)->Reload(); +static void reload_callback( GtkWidget *widget, gpointer data ){ + ( (CBackgroundDialogPage *)data )->Reload(); } -static void size_sel_callback( GtkWidget *widget, gpointer data ) -{ +static void size_sel_callback( GtkWidget *widget, gpointer data ){ CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - if (pPage->m_pImage->SetExtentsSel()) + if ( pPage->m_pImage->SetExtentsSel() ) { pPage->SetPosLabel(); + } } -static void size_mm_callback( GtkWidget *widget, gpointer data ) -{ +static void size_mm_callback( GtkWidget *widget, gpointer data ){ CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - if(pPage->m_pImage->SetExtentsMM()) + if ( pPage->m_pImage->SetExtentsMM() ) { pPage->SetPosLabel(); + } } -static void alpha_adjust_callback( GtkWidget *widget, gpointer data ) -{ +static void alpha_adjust_callback( GtkWidget *widget, gpointer data ){ CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - pPage->m_pImage->m_alpha = (float)gtk_range_get_value (GTK_RANGE(widget)); - g_FuncTable.m_pfnSysUpdateWindows(W_XY); + pPage->m_pImage->m_alpha = (float)gtk_range_get_value( GTK_RANGE( widget ) ); + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); } -void CBackgroundDialogPage::Reload() -{ - if(m_bValidFile) - m_pImage->Load(gtk_label_get_text(GTK_LABEL(m_pFileLabel))); +void CBackgroundDialogPage::Reload(){ + if ( m_bValidFile ) { + m_pImage->Load( gtk_label_get_text( GTK_LABEL( m_pFileLabel ) ) ); + } } -void CBackgroundDialogPage::Browse() -{ +void CBackgroundDialogPage::Browse(){ char browsedir[PATH_MAX]; const char *ct; const char *newfile; char *t; - + //TODO GetMapName saves the map. eeep! //also with no map, returns unnamed.map, otherwise returns full path // Syn_Printf(MSG_PREFIX "GetMapName() %s\n", // g_FuncTable.m_pfnGetMapName()); - - ct = g_FuncTable.m_pfnReadProjectKey("basepath"); + + ct = g_FuncTable.m_pfnReadProjectKey( "basepath" ); // TODO shouldn't need this stuff - if(!ct || !strlen(ct)) { - Syn_Printf(MSG_PREFIX "basepath = NULL or empty\n"); + if ( !ct || !strlen( ct ) ) { + Syn_Printf( MSG_PREFIX "basepath = NULL or empty\n" ); return; } - Syn_Printf(MSG_PREFIX "basepath: %s\n",ct); - if(strlen(ct) >= PATH_MAX) { - Syn_Printf(MSG_PREFIX "base game dir too long\n"); + Syn_Printf( MSG_PREFIX "basepath: %s\n",ct ); + if ( strlen( ct ) >= PATH_MAX ) { + Syn_Printf( MSG_PREFIX "base game dir too long\n" ); return; } - strcpy(browsedir,ct); - // make sure we have a trailing / - if(browsedir[strlen(browsedir) - 1] != '/') - strcat(browsedir,"/"); + strcpy( browsedir,ct ); + // make sure we have a trailing / + if ( browsedir[strlen( browsedir ) - 1] != '/' ) { + strcat( browsedir,"/" ); + } //if we dont have a file yet, don't try to use it for default dir - if(m_bValidFile) { - // filename should always be a nice clean unix style relative path - ct = gtk_label_get_text(GTK_LABEL(m_pFileLabel)); - strcat(browsedir,ct); - Syn_Printf(MSG_PREFIX "full path: %s\n",browsedir); + if ( m_bValidFile ) { + // filename should always be a nice clean unix style relative path + ct = gtk_label_get_text( GTK_LABEL( m_pFileLabel ) ); + strcat( browsedir,ct ); + Syn_Printf( MSG_PREFIX "full path: %s\n",browsedir ); // lop off the file part - t = browsedir + strlen(browsedir) - 1; - while (t != browsedir && *t != '/') + t = browsedir + strlen( browsedir ) - 1; + while ( t != browsedir && *t != '/' ) t--; *t = 0; } - Syn_Printf(MSG_PREFIX "browse directory %s\n",browsedir); - + Syn_Printf( MSG_PREFIX "browse directory %s\n",browsedir ); + //does NOT need freeing contrary to include/qerplugin.h comments //TODO bug/patch for comments //TODO patern gets fucked up sometimes if empty //http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=915 - newfile = g_FuncTable.m_pfnFileDialog(pDialogWnd,TRUE, - "Load Background Image",browsedir,FILETYPE_KEY); - if(!newfile) { - Syn_Printf(MSG_PREFIX "newfile = NULL\n"); + newfile = g_FuncTable.m_pfnFileDialog( pDialogWnd,TRUE, + "Load Background Image",browsedir,FILETYPE_KEY ); + if ( !newfile ) { + Syn_Printf( MSG_PREFIX "newfile = NULL\n" ); return; } - Syn_Printf(MSG_PREFIX "newfile: %s\n",newfile); - newfile = g_FileSystemTable.m_pfnExtractRelativePath(newfile); + Syn_Printf( MSG_PREFIX "newfile: %s\n",newfile ); + newfile = g_FileSystemTable.m_pfnExtractRelativePath( newfile ); - if(!newfile) { - Syn_Printf(MSG_PREFIX "newfile = NULL\n"); + if ( !newfile ) { + Syn_Printf( MSG_PREFIX "newfile = NULL\n" ); return; } - Syn_Printf(MSG_PREFIX "newfile: %s\n",newfile); + Syn_Printf( MSG_PREFIX "newfile: %s\n",newfile ); - if(m_pImage->Load(newfile)) { + if ( m_pImage->Load( newfile ) ) { m_bValidFile = true; - gtk_label_set_text(GTK_LABEL(m_pFileLabel),newfile); + gtk_label_set_text( GTK_LABEL( m_pFileLabel ),newfile ); } } -void CBackgroundDialogPage::SetPosLabel() -{ +void CBackgroundDialogPage::SetPosLabel(){ char s[64]; // TODO no snprintf ? - sprintf(s, "Size/Position (%d,%d) (%d,%d)",(int)(m_pImage->m_xmin), - (int)(m_pImage->m_ymin),(int)(m_pImage->m_xmax),(int)(m_pImage->m_ymax)); - gtk_label_set_text(GTK_LABEL(m_pPosLabel),s); + sprintf( s, "Size/Position (%d,%d) (%d,%d)",(int)( m_pImage->m_xmin ), + (int)( m_pImage->m_ymin ),(int)( m_pImage->m_xmax ),(int)( m_pImage->m_ymax ) ); + gtk_label_set_text( GTK_LABEL( m_pPosLabel ),s ); } -CBackgroundDialogPage::CBackgroundDialogPage(VIEWTYPE vt ) -{ +CBackgroundDialogPage::CBackgroundDialogPage( VIEWTYPE vt ){ GtkWidget *frame; GtkWidget *hbox; GtkWidget *w; @@ -185,180 +180,174 @@ CBackgroundDialogPage::CBackgroundDialogPage(VIEWTYPE vt ) m_bValidFile = false; - switch(m_vt) + switch ( m_vt ) { - case XY: - m_pTabLabel = gtk_label_new("X/Y"); - m_pImage = &backgroundXY; - break; - case XZ: - m_pTabLabel = gtk_label_new("X/Z"); - m_pImage = &backgroundXZ; - break; - case YZ: - m_pTabLabel = gtk_label_new("Y/Z"); - m_pImage = &backgroundYZ; - break; + case XY: + m_pTabLabel = gtk_label_new( "X/Y" ); + m_pImage = &backgroundXY; + break; + case XZ: + m_pTabLabel = gtk_label_new( "X/Z" ); + m_pImage = &backgroundXZ; + break; + case YZ: + m_pTabLabel = gtk_label_new( "Y/Z" ); + m_pImage = &backgroundYZ; + break; } // A vbox to hold everything - m_pWidget = gtk_vbox_new(FALSE,0); + m_pWidget = gtk_vbox_new( FALSE,0 ); // Frame for file row - frame = gtk_frame_new("File"); - gtk_box_pack_start (GTK_BOX (m_pWidget),frame, FALSE, FALSE, 2); + frame = gtk_frame_new( "File" ); + gtk_box_pack_start( GTK_BOX( m_pWidget ),frame, FALSE, FALSE, 2 ); // hbox for first row - hbox = gtk_hbox_new(FALSE,5); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - gtk_container_add (GTK_CONTAINER (frame), hbox); + hbox = gtk_hbox_new( FALSE,5 ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ),4 ); + gtk_container_add( GTK_CONTAINER( frame ), hbox ); // label to display filename - m_pFileLabel = gtk_label_new(NO_FILE_MSG); - gtk_label_set_selectable(GTK_LABEL(m_pFileLabel),TRUE); + m_pFileLabel = gtk_label_new( NO_FILE_MSG ); + gtk_label_set_selectable( GTK_LABEL( m_pFileLabel ),TRUE ); //TODO set min size ? done with spaces right now - gtk_box_pack_start (GTK_BOX (hbox),m_pFileLabel, TRUE, TRUE, 5); - - gtk_widget_show (m_pFileLabel); - - w = gtk_button_new_with_label ("Browse..."); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (browse_callback), - (gpointer)this); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_tooltips_set_tip (pTooltips, w, "Select a file", NULL); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Reload"); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (reload_callback), - (gpointer)this); + gtk_box_pack_start( GTK_BOX( hbox ),m_pFileLabel, TRUE, TRUE, 5 ); + + gtk_widget_show( m_pFileLabel ); + + w = gtk_button_new_with_label( "Browse..." ); + g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( browse_callback ), + ( gpointer ) this ); + gtk_box_pack_start( GTK_BOX( hbox ),w, FALSE, FALSE, 5 ); + gtk_tooltips_set_tip( pTooltips, w, "Select a file", NULL ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Reload" ); + g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( reload_callback ), + ( gpointer ) this ); // TODO disable until we have file // gtk_widget_set_sensitive(w,FALSE); - gtk_tooltips_set_tip (pTooltips, w, "Reload current file", NULL); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_widget_show (w); + gtk_tooltips_set_tip( pTooltips, w, "Reload current file", NULL ); + gtk_box_pack_start( GTK_BOX( hbox ),w, FALSE, FALSE, 5 ); + gtk_widget_show( w ); - gtk_widget_show (hbox); - gtk_widget_show (frame); + gtk_widget_show( hbox ); + gtk_widget_show( frame ); // second row (rendering options) - frame = gtk_frame_new("Rendering"); - gtk_box_pack_start (GTK_BOX (m_pWidget),frame, FALSE, FALSE, 2); - - hbox = gtk_hbox_new(FALSE,5); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - gtk_container_add (GTK_CONTAINER (frame), hbox); - - w = gtk_label_new("Vertex alpha:"); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_widget_show (w); - - w = gtk_hscale_new_with_range(0.0,1.0,0.01); - gtk_range_set_value(GTK_RANGE(w),0.5); - gtk_scale_set_value_pos(GTK_SCALE(w),GTK_POS_LEFT); - g_signal_connect (G_OBJECT (w), "value-changed", - G_CALLBACK (alpha_adjust_callback), (gpointer)this); - gtk_box_pack_start (GTK_BOX (hbox),w, TRUE, TRUE, 5); - gtk_tooltips_set_tip (pTooltips, w, "Set image transparancy", NULL); - gtk_widget_show (w); - - gtk_widget_show (hbox); - gtk_widget_show (frame); + frame = gtk_frame_new( "Rendering" ); + gtk_box_pack_start( GTK_BOX( m_pWidget ),frame, FALSE, FALSE, 2 ); + + hbox = gtk_hbox_new( FALSE,5 ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ),4 ); + gtk_container_add( GTK_CONTAINER( frame ), hbox ); + + w = gtk_label_new( "Vertex alpha:" ); + gtk_box_pack_start( GTK_BOX( hbox ),w, FALSE, FALSE, 5 ); + gtk_widget_show( w ); + + w = gtk_hscale_new_with_range( 0.0,1.0,0.01 ); + gtk_range_set_value( GTK_RANGE( w ),0.5 ); + gtk_scale_set_value_pos( GTK_SCALE( w ),GTK_POS_LEFT ); + g_signal_connect( G_OBJECT( w ), "value-changed", + G_CALLBACK( alpha_adjust_callback ), ( gpointer ) this ); + gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, TRUE, 5 ); + gtk_tooltips_set_tip( pTooltips, w, "Set image transparancy", NULL ); + gtk_widget_show( w ); + + gtk_widget_show( hbox ); + gtk_widget_show( frame ); // Third row (size and position) - frame = gtk_frame_new("Size/Position (undefined)"); - m_pPosLabel = gtk_frame_get_label_widget (GTK_FRAME(frame)); - gtk_box_pack_start ( GTK_BOX (m_pWidget), frame, FALSE, FALSE, 2); - - hbox = gtk_hbox_new(FALSE,5); - gtk_container_add (GTK_CONTAINER (frame), hbox); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - - w = gtk_button_new_with_label ("from selection"); - gtk_box_pack_start (GTK_BOX (hbox),w, TRUE, FALSE, 5); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (size_sel_callback), - (gpointer)this); - gtk_tooltips_set_tip (pTooltips, w, "Set the size of the image to the bounding rectangle of all selected brushes and entities", NULL); - gtk_widget_show (w); - - if(m_vt == XY) { - w = gtk_button_new_with_label ("from map mins/maxs"); - gtk_box_pack_start ( GTK_BOX (hbox),w, TRUE, FALSE, 2); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (size_mm_callback), - (gpointer)this); - gtk_tooltips_set_tip (pTooltips, w, "Set the size of the image using the mapcoordsmins and mapcoordsmaxs keys of the worldspawn entity", NULL); - gtk_widget_show (w); + frame = gtk_frame_new( "Size/Position (undefined)" ); + m_pPosLabel = gtk_frame_get_label_widget( GTK_FRAME( frame ) ); + gtk_box_pack_start( GTK_BOX( m_pWidget ), frame, FALSE, FALSE, 2 ); + + hbox = gtk_hbox_new( FALSE,5 ); + gtk_container_add( GTK_CONTAINER( frame ), hbox ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ),4 ); + + w = gtk_button_new_with_label( "from selection" ); + gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, FALSE, 5 ); + g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( size_sel_callback ), + ( gpointer ) this ); + gtk_tooltips_set_tip( pTooltips, w, "Set the size of the image to the bounding rectangle of all selected brushes and entities", NULL ); + gtk_widget_show( w ); + + if ( m_vt == XY ) { + w = gtk_button_new_with_label( "from map mins/maxs" ); + gtk_box_pack_start( GTK_BOX( hbox ),w, TRUE, FALSE, 2 ); + g_signal_connect( G_OBJECT( w ), "clicked", G_CALLBACK( size_mm_callback ), + ( gpointer ) this ); + gtk_tooltips_set_tip( pTooltips, w, "Set the size of the image using the mapcoordsmins and mapcoordsmaxs keys of the worldspawn entity", NULL ); + gtk_widget_show( w ); } - gtk_widget_show (hbox); - gtk_widget_show (frame); + gtk_widget_show( hbox ); + gtk_widget_show( frame ); - gtk_widget_show ( m_pWidget ); + gtk_widget_show( m_pWidget ); } -void CBackgroundDialogPage::Append(GtkWidget *notebook) -{ - gtk_notebook_append_page( GTK_NOTEBOOK(notebook), m_pWidget, m_pTabLabel); +void CBackgroundDialogPage::Append( GtkWidget *notebook ){ + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), m_pWidget, m_pTabLabel ); } // dialog global callbacks /* -static gint expose_callback( GtkWidget *widget, gpointer data ) -{ - return FALSE; -} -*/ - -static void response_callback( GtkWidget *widget, gint response, gpointer data ) -{ - if( response == GTK_RESPONSE_CLOSE ) - gtk_widget_hide( pDialogWnd ); + static gint expose_callback( GtkWidget *widget, gpointer data ) + { + return FALSE; + } + */ + +static void response_callback( GtkWidget *widget, gint response, gpointer data ){ + if ( response == GTK_RESPONSE_CLOSE ) { + gtk_widget_hide( pDialogWnd ); + } } -static gint close_callback( GtkWidget *widget, gpointer data ) -{ - gtk_widget_hide( pDialogWnd ); +static gint close_callback( GtkWidget *widget, gpointer data ){ + gtk_widget_hide( pDialogWnd ); return TRUE; } -void InitBackgroundDialog() -{ +void InitBackgroundDialog(){ CBackgroundDialogPage *pPage; - pDialogWnd = gtk_dialog_new_with_buttons ("Background Images", - GTK_WINDOW(g_pMainWidget), - (GtkDialogFlags)(GTK_DIALOG_DESTROY_WITH_PARENT), - // TODO dialog with no buttons - // GTK_STOCK_CLOSE, - // GTK_RESPONSE_CLOSE, - NULL); - gtk_signal_connect( GTK_OBJECT (pDialogWnd), "delete_event", - GTK_SIGNAL_FUNC( close_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (pDialogWnd), "response", - GTK_SIGNAL_FUNC( response_callback ), NULL ); -// gtk_signal_connect( GTK_OBJECT (pDialogWnd), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); + pDialogWnd = gtk_dialog_new_with_buttons( "Background Images", + GTK_WINDOW( g_pMainWidget ), + (GtkDialogFlags)( GTK_DIALOG_DESTROY_WITH_PARENT ), + // TODO dialog with no buttons + // GTK_STOCK_CLOSE, + // GTK_RESPONSE_CLOSE, + NULL ); + gtk_signal_connect( GTK_OBJECT( pDialogWnd ), "delete_event", + GTK_SIGNAL_FUNC( close_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( pDialogWnd ), "response", + GTK_SIGNAL_FUNC( response_callback ), NULL ); +// gtk_signal_connect( GTK_OBJECT (pDialogWnd), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); pTooltips = gtk_tooltips_new(); pNotebook = gtk_notebook_new(); - pPage = new CBackgroundDialogPage(XY); - pPage->Append(pNotebook); - pPage = new CBackgroundDialogPage(XZ); - pPage->Append(pNotebook); - pPage = new CBackgroundDialogPage(YZ); - pPage->Append(pNotebook); + pPage = new CBackgroundDialogPage( XY ); + pPage->Append( pNotebook ); + pPage = new CBackgroundDialogPage( XZ ); + pPage->Append( pNotebook ); + pPage = new CBackgroundDialogPage( YZ ); + pPage->Append( pNotebook ); + + gtk_box_pack_start( GTK_BOX( GTK_DIALOG( pDialogWnd )->vbox ), pNotebook, TRUE, TRUE, 0 ); - gtk_box_pack_start (GTK_BOX (GTK_DIALOG(pDialogWnd)->vbox), pNotebook, TRUE, TRUE, 0); + gtk_widget_show( pNotebook ); - gtk_widget_show ( pNotebook ); - gtk_widget_realize( pDialogWnd ); } -void ShowBackgroundDialog() -{ - gtk_window_present( GTK_WINDOW(pDialogWnd) ); +void ShowBackgroundDialog(){ + gtk_window_present( GTK_WINDOW( pDialogWnd ) ); } -void ShowBackgroundDialogPG(int page) -{ - gtk_notebook_set_current_page(GTK_NOTEBOOK(pNotebook),page); +void ShowBackgroundDialogPG( int page ){ + gtk_notebook_set_current_page( GTK_NOTEBOOK( pNotebook ),page ); ShowBackgroundDialog(); } - diff --git a/contrib/bkgrnd2d/dialog.h b/contrib/bkgrnd2d/dialog.h index 03af2078..29a511d6 100644 --- a/contrib/bkgrnd2d/dialog.h +++ b/contrib/bkgrnd2d/dialog.h @@ -1,22 +1,22 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // bkgrnd2d Plugin dialog box @@ -30,6 +30,6 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA void InitBackgroundDialog(); void ShowBackgroundDialog(); -void ShowBackgroundDialogPG(int page); +void ShowBackgroundDialogPG( int page ); #endif // _BKGRND2D_DIALOG_H_ diff --git a/contrib/bkgrnd2d/plugin.cpp b/contrib/bkgrnd2d/plugin.cpp index a37882c5..44705711 100644 --- a/contrib/bkgrnd2d/plugin.cpp +++ b/contrib/bkgrnd2d/plugin.cpp @@ -1,44 +1,44 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // 2d background Plugin // // Code by reyalP aka Reed Mideke // -// Based on +// Based on // /* Overview ======== - This little plugin allows you to display an image in the background of the - gtkradiant XY window. + This little plugin allows you to display an image in the background of the + gtkradiant XY window. Version History =============== v0.1 - Initial version. - v0.2 - - three views, dialog box, toolbar + v0.2 + - three views, dialog box, toolbar v0.25 - tooltips, follow gtkradiant coding conventions @@ -50,14 +50,14 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA How ? ----- - textures 'n widgets 'n stuff. -*/ + */ //#include "plugin.h" //TODO we just poke the objects directly #include "bkgrnd2d.h" #include "dialog.h" -#define CMD_SEP "-" +#define CMD_SEP "-" #define CMD_CONFIG "Configure..." #define CMD_ABOUT "About..." // ============================================================================= @@ -79,13 +79,13 @@ void *g_pMainWidget; static const char *PLUGIN_NAME = "2d window background plugin"; //backwards for some reason -static const char *PLUGIN_COMMANDS = CMD_ABOUT ";" - CMD_SEP ";" - CMD_CONFIG - ; +static const char *PLUGIN_COMMANDS = CMD_ABOUT ";" + CMD_SEP ";" + CMD_CONFIG +; static const char *PLUGIN_ABOUT = "2d window background v0.25\n\n" - "By reyalP (hellsownpuppy@yahoo.com)"; + "By reyalP (hellsownpuppy@yahoo.com)"; @@ -100,37 +100,37 @@ struct toolbar_button_info_s const char *image; const char *text; const char *tip; - void (*func)(); + void ( *func )(); IToolbarButton::EType type; }; -struct toolbar_button_info_s toolbar_buttons[NUM_TOOLBAR_BUTTONS] = +struct toolbar_button_info_s toolbar_buttons[NUM_TOOLBAR_BUTTONS] = { { "bkgrnd2d_xy_toggle.bmp", "xy background", - "Toggle xy background image", + "Toggle xy background image", DoBkgrndToggleXY, IToolbarButton::eToggleButton }, { "bkgrnd2d_xz_toggle.bmp", "xz background", - "Toggle xz background image", + "Toggle xz background image", DoBkgrndToggleXZ, IToolbarButton::eToggleButton }, { "bkgrnd2d_yz_toggle.bmp", "yz background", - "Toggle yz background image", + "Toggle yz background image", DoBkgrndToggleYZ, IToolbarButton::eToggleButton }, { "bkgrnd2d_conf.bmp", "Configure", - "Configure background images", + "Configure background images", ShowBackgroundDialog, IToolbarButton::eButton }, @@ -139,112 +139,104 @@ struct toolbar_button_info_s toolbar_buttons[NUM_TOOLBAR_BUTTONS] = class Bkgrnd2dButton : public IToolbarButton { public: - const toolbar_button_info_s *bi; - virtual const char* getImage() const - { - return bi->image; - } - virtual const char* getText() const - { - return bi->text; - } - virtual const char* getTooltip() const - { - return bi->tip; - } - virtual void activate() const - { - bi->func(); - return ; - } - virtual EType getType() const - { - return bi->type; - } +const toolbar_button_info_s *bi; +virtual const char* getImage() const { + return bi->image; +} +virtual const char* getText() const { + return bi->text; +} +virtual const char* getTooltip() const { + return bi->tip; +} +virtual void activate() const { + bi->func(); + return ; +} +virtual EType getType() const { + return bi->type; +} }; Bkgrnd2dButton g_bkgrnd2dbuttons[NUM_TOOLBAR_BUTTONS]; -unsigned int ToolbarButtonCount() -{ - return NUM_TOOLBAR_BUTTONS; +unsigned int ToolbarButtonCount(){ + return NUM_TOOLBAR_BUTTONS; } -const IToolbarButton* GetToolbarButton(unsigned int index) -{ - g_bkgrnd2dbuttons[index].bi = &toolbar_buttons[index]; - return &g_bkgrnd2dbuttons[index]; +const IToolbarButton* GetToolbarButton( unsigned int index ){ + g_bkgrnd2dbuttons[index].bi = &toolbar_buttons[index]; + return &g_bkgrnd2dbuttons[index]; } -extern "C" const char* QERPlug_Init (void *hApp, void* pMainWidget) -{ - g_pMainWidget = pMainWidget; +extern "C" const char* QERPlug_Init( void *hApp, void* pMainWidget ){ + g_pMainWidget = pMainWidget; - InitBackgroundDialog(); - render.Register(); + InitBackgroundDialog(); + render.Register(); //TODO is it right ? is it wrong ? it works //TODO figure out supported image types - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("all files", "*.*")); - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("jpeg files", "*.jpg")); - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("targa files", "*.tga")); - return (char *) PLUGIN_NAME; + GetFileTypeRegistry()->addType( FILETYPE_KEY, filetype_t( "all files", "*.*" ) ); + GetFileTypeRegistry()->addType( FILETYPE_KEY, filetype_t( "jpeg files", "*.jpg" ) ); + GetFileTypeRegistry()->addType( FILETYPE_KEY, filetype_t( "targa files", "*.tga" ) ); + return (char *) PLUGIN_NAME; } -extern "C" const char* QERPlug_GetName () -{ - return (char *) PLUGIN_NAME; +extern "C" const char* QERPlug_GetName(){ + return (char *) PLUGIN_NAME; } -extern "C" const char* QERPlug_GetCommandList () -{ - return (char *) PLUGIN_COMMANDS; +extern "C" const char* QERPlug_GetCommandList(){ + return (char *) PLUGIN_COMMANDS; } -extern "C" void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - Sys_Printf (MSG_PREFIX "Command \"%s\"\n",p); - if(!strcmp(p, CMD_ABOUT)) { - g_FuncTable.m_pfnMessageBox(NULL, PLUGIN_ABOUT, "About", MB_OK, NULL); - } - else if(!strcmp(p,CMD_CONFIG)) { - ShowBackgroundDialog(); - } +extern "C" void QERPlug_Dispatch( const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ){ + Sys_Printf( MSG_PREFIX "Command \"%s\"\n",p ); + if ( !strcmp( p, CMD_ABOUT ) ) { + g_FuncTable.m_pfnMessageBox( NULL, PLUGIN_ABOUT, "About", MB_OK, NULL ); + } + else if ( !strcmp( p,CMD_CONFIG ) ) { + ShowBackgroundDialog(); + } } //TODO these three suck -void DoBkgrndToggleXY() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleXY\n"); - // always toggle, since the buttons do - backgroundXY.m_bActive = (backgroundXY.m_bActive) ? false:true; - // if we don't have image or extents, and we activated, - // bring up the dialog with the corresponding page - // would be better to hide or grey out button, but we can't - if(backgroundXY.m_bActive && !backgroundXY.Valid()) - ShowBackgroundDialogPG(0); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); +void DoBkgrndToggleXY(){ + Sys_Printf( MSG_PREFIX "DoBkgrndToggleXY\n" ); + // always toggle, since the buttons do + backgroundXY.m_bActive = ( backgroundXY.m_bActive ) ? false : true; + // if we don't have image or extents, and we activated, + // bring up the dialog with the corresponding page + // would be better to hide or grey out button, but we can't + if ( backgroundXY.m_bActive && !backgroundXY.Valid() ) { + ShowBackgroundDialogPG( 0 ); + } + else{ + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); + } } -void DoBkgrndToggleXZ() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleXZ\n"); - backgroundXZ.m_bActive = (backgroundXZ.m_bActive) ? false:true; - if(backgroundXZ.m_bActive && !backgroundXZ.Valid()) - ShowBackgroundDialogPG(1); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); +void DoBkgrndToggleXZ(){ + Sys_Printf( MSG_PREFIX "DoBkgrndToggleXZ\n" ); + backgroundXZ.m_bActive = ( backgroundXZ.m_bActive ) ? false : true; + if ( backgroundXZ.m_bActive && !backgroundXZ.Valid() ) { + ShowBackgroundDialogPG( 1 ); + } + else{ + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); + } } -void DoBkgrndToggleYZ() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleYZ\n"); - backgroundYZ.m_bActive = (backgroundYZ.m_bActive) ? false:true; - if(backgroundYZ.m_bActive && !backgroundYZ.Valid()) - ShowBackgroundDialogPG(2); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); +void DoBkgrndToggleYZ(){ + Sys_Printf( MSG_PREFIX "DoBkgrndToggleYZ\n" ); + backgroundYZ.m_bActive = ( backgroundYZ.m_bActive ) ? false : true; + if ( backgroundYZ.m_bActive && !backgroundYZ.Valid() ) { + ShowBackgroundDialogPG( 2 ); + } + else{ + g_FuncTable.m_pfnSysUpdateWindows( W_XY ); + } } // ============================================================================= @@ -252,68 +244,60 @@ void DoBkgrndToggleYZ() CSynapseServer* g_pSynapseServer = NULL; CSynapseClientBkgrnd2d g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(TOOLBAR_MAJOR, BKGRND2D_MINOR, sizeof(_QERPlugToolbarTable)); - g_SynapseClient.AddAPI(PLUGIN_MAJOR, BKGRND2D_MINOR, sizeof( _QERPluginTable ) ); - - g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( g_FuncTable ), SYN_REQUIRE, &g_FuncTable ); - g_SynapseClient.AddAPI( QGL_MAJOR, NULL, sizeof( g_QglTable ), SYN_REQUIRE, &g_QglTable ); + +extern "C" CSynapseClient * SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces( const char *version, CSynapseServer *pServer ){ + if ( strcmp( version, SYNAPSE_VERSION ) ) { + Syn_Printf( "ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version ); + return NULL; + } + g_pSynapseServer = pServer; + g_pSynapseServer->IncRef(); + Set_Syn_Printf( g_pSynapseServer->Get_Syn_Printf() ); + + g_SynapseClient.AddAPI( TOOLBAR_MAJOR, BKGRND2D_MINOR, sizeof( _QERPlugToolbarTable ) ); + g_SynapseClient.AddAPI( PLUGIN_MAJOR, BKGRND2D_MINOR, sizeof( _QERPluginTable ) ); + + g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( g_FuncTable ), SYN_REQUIRE, &g_FuncTable ); + g_SynapseClient.AddAPI( QGL_MAJOR, NULL, sizeof( g_QglTable ), SYN_REQUIRE, &g_QglTable ); // TODO is this the right way to ask for 'whichever VFS we have loaded' ? Seems to work // for misc filename functions - g_SynapseClient.AddAPI( VFS_MAJOR, "*", sizeof( g_FileSystemTable ), SYN_REQUIRE, &g_FileSystemTable ); + g_SynapseClient.AddAPI( VFS_MAJOR, "*", sizeof( g_FileSystemTable ), SYN_REQUIRE, &g_FileSystemTable ); // get worldspawn - g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( g_EntityTable ), SYN_REQUIRE, &g_EntityTable ); + g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( g_EntityTable ), SYN_REQUIRE, &g_EntityTable ); // selected brushes - g_SynapseClient.AddAPI( DATA_MAJOR, NULL, sizeof( g_DataTable ), SYN_REQUIRE, &g_DataTable ); + g_SynapseClient.AddAPI( DATA_MAJOR, NULL, sizeof( g_DataTable ), SYN_REQUIRE, &g_DataTable ); - return &g_SynapseClient; + return &g_SynapseClient; } -bool CSynapseClientBkgrnd2d::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - if (!strcmp(pAPI->major_name, TOOLBAR_MAJOR)) - { - _QERPlugToolbarTable* pTable= static_cast<_QERPlugToolbarTable*>(pAPI->mpTable); - - pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; - pTable->m_pfnGetToolbarButton = &GetToolbarButton; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; +bool CSynapseClientBkgrnd2d::RequestAPI( APIDescriptor_t *pAPI ){ + if ( !strcmp( pAPI->major_name, PLUGIN_MAJOR ) ) { + _QERPluginTable* pTable = static_cast<_QERPluginTable*>( pAPI->mpTable ); + + pTable->m_pfnQERPlug_Init = QERPlug_Init; + pTable->m_pfnQERPlug_GetName = QERPlug_GetName; + pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + return true; + } + if ( !strcmp( pAPI->major_name, TOOLBAR_MAJOR ) ) { + _QERPlugToolbarTable* pTable = static_cast<_QERPlugToolbarTable*>( pAPI->mpTable ); + + pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; + pTable->m_pfnGetToolbarButton = &GetToolbarButton; + return true; + } + + Syn_Printf( "ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo() ); + return false; } #include "version.h" -const char* CSynapseClientBkgrnd2d::GetInfo() -{ - return "2d Background plugin built " __DATE__ " " RADIANT_VERSION; +const char* CSynapseClientBkgrnd2d::GetInfo(){ + return "2d Background plugin built " __DATE__ " " RADIANT_VERSION; } -const char* CSynapseClientBkgrnd2d::GetName() -{ - return "bkgrnd2d"; +const char* CSynapseClientBkgrnd2d::GetName(){ + return "bkgrnd2d"; } - diff --git a/contrib/bkgrnd2d/plugin.h b/contrib/bkgrnd2d/plugin.h index 30b0ca7d..13ca7378 100644 --- a/contrib/bkgrnd2d/plugin.h +++ b/contrib/bkgrnd2d/plugin.h @@ -1,22 +1,22 @@ /* -Copyright (C) 2003 Reed Mideke. + Copyright (C) 2003 Reed Mideke. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // bkgrnd2d Plugin @@ -30,9 +30,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #define _PLUGIN_H_ /*! -\todo need general notice about lib purpose etc. -and the external dependencies (such as GLib, STL, mathlib etc.) -*/ + \todo need general notice about lib purpose etc. + and the external dependencies (such as GLib, STL, mathlib etc.) + */ #include // for CPtrArray for idata.h @@ -63,13 +63,13 @@ extern CSynapseServer* g_pSynapseServer; class CSynapseClientBkgrnd2d : public CSynapseClient { public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - const char* GetName(); +// CSynapseClient API +bool RequestAPI( APIDescriptor_t *pAPI ); +const char* GetInfo(); +const char* GetName(); - CSynapseClientBkgrnd2d() { } - virtual ~CSynapseClientBkgrnd2d() { } +CSynapseClientBkgrnd2d() { } +virtual ~CSynapseClientBkgrnd2d() { } }; #define MSG_PREFIX "bkgrnd2d: " #define MSG_WARN "bkgrnd2d WARNING: " diff --git a/contrib/bobtoolz/CPortals.h b/contrib/bobtoolz/CPortals.h index 71f399b7..fc555531 100644 --- a/contrib/bobtoolz/CPortals.h +++ b/contrib/bobtoolz/CPortals.h @@ -1,47 +1,47 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ class CBspPoint { public: - float p[3]; +float p[3]; }; class CBspPortal { public: - CBspPortal(); - ~CBspPortal(); +CBspPortal(); +~CBspPortal(); - unsigned point_count; - CBspPoint *point; - bool Build(char *def, unsigned int pointCnt, bool bInverse); +unsigned point_count; +CBspPoint *point; +bool Build( char *def, unsigned int pointCnt, bool bInverse ); }; class CBspNode { public: - CBspPortal *portal; - unsigned int portal_count; +CBspPortal *portal; +unsigned int portal_count; - bool AddPortal(char* def, unsigned int pointCnt, bool bInverse); - unsigned int portal_next; - CBspNode(); - ~CBspNode(); +bool AddPortal( char* def, unsigned int pointCnt, bool bInverse ); +unsigned int portal_next; +CBspNode(); +~CBspNode(); }; @@ -50,14 +50,14 @@ public: class CPortals { public: - CPortals(); - ~CPortals(); +CPortals(); +~CPortals(); - void Load(); // use filename in fn - void Purge(); +void Load(); // use filename in fn +void Purge(); - char fn[NAME_MAX]; - CBspNode *node; +char fn[NAME_MAX]; +CBspNode *node; - unsigned int node_count; +unsigned int node_count; }; diff --git a/contrib/bobtoolz/DBobView.cpp b/contrib/bobtoolz/DBobView.cpp index aef76088..55dd8e4d 100644 --- a/contrib/bobtoolz/DBobView.cpp +++ b/contrib/bobtoolz/DBobView.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // BobView.cpp: implementation of the DBobView class. // @@ -41,25 +41,24 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DBobView::DBobView() -{ +DBobView::DBobView(){ nPathCount = 0; - + path = NULL; boundingShow = BOUNDS_APEX; - constructShaders(); - GlobalShaderCache().attachRenderable(*this); + constructShaders(); + GlobalShaderCache().attachRenderable( *this ); } -DBobView::~DBobView() -{ - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); +DBobView::~DBobView(){ + GlobalShaderCache().detachRenderable( *this ); + destroyShaders(); - if(path) + if ( path ) { delete[] path; + } g_PathView = NULL; } @@ -68,12 +67,11 @@ DBobView::~DBobView() // Implementation ////////////////////////////////////////////////////////////////////// -void DBobView::render(RenderStateFlags state) const -{ - glBegin(GL_LINE_STRIP); +void DBobView::render( RenderStateFlags state ) const { + glBegin( GL_LINE_STRIP ); - for(int i = 0; i < nPathCount; i++) - glVertex3fv(path[i]); + for ( int i = 0; i < nPathCount; i++ ) + glVertex3fv( path[i] ); glEnd(); } @@ -81,107 +79,101 @@ void DBobView::render(RenderStateFlags state) const const char* DBobView_state_line = "$bobtoolz/bobview/line"; const char* DBobView_state_box = "$bobtoolz/bobview/box"; -void DBobView::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND|RENDER_LINESMOOTH; - state.m_sort = OpenGLState::eSortOpaque; - state.m_linewidth = 1; - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - GlobalOpenGLStateLibrary().insert(DBobView_state_line, state); - - state.m_colour[0] = 0.25f; - state.m_colour[1] = 0.75f; - state.m_colour[2] = 0.75f; - state.m_colour[3] = 1; - GlobalOpenGLStateLibrary().insert(DBobView_state_box, state); - - m_shader_line = GlobalShaderCache().capture(DBobView_state_line); - m_shader_box = GlobalShaderCache().capture(DBobView_state_box); +void DBobView::constructShaders(){ + OpenGLState state; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_BLEND | RENDER_LINESMOOTH; + state.m_sort = OpenGLState::eSortOpaque; + state.m_linewidth = 1; + state.m_colour[0] = 1; + state.m_colour[1] = 0; + state.m_colour[2] = 0; + state.m_colour[3] = 1; + GlobalOpenGLStateLibrary().insert( DBobView_state_line, state ); + + state.m_colour[0] = 0.25f; + state.m_colour[1] = 0.75f; + state.m_colour[2] = 0.75f; + state.m_colour[3] = 1; + GlobalOpenGLStateLibrary().insert( DBobView_state_box, state ); + + m_shader_line = GlobalShaderCache().capture( DBobView_state_line ); + m_shader_box = GlobalShaderCache().capture( DBobView_state_box ); } -void DBobView::destroyShaders() -{ - GlobalOpenGLStateLibrary().erase(DBobView_state_line); - GlobalOpenGLStateLibrary().erase(DBobView_state_box); - GlobalShaderCache().release(DBobView_state_line); - GlobalShaderCache().release(DBobView_state_box); +void DBobView::destroyShaders(){ + GlobalOpenGLStateLibrary().erase( DBobView_state_line ); + GlobalOpenGLStateLibrary().erase( DBobView_state_box ); + GlobalShaderCache().release( DBobView_state_line ); + GlobalShaderCache().release( DBobView_state_box ); } -Matrix4 g_transform_box1 = matrix4_translation_for_vec3(Vector3(16.0f, 16.0f, 28.0f)); -Matrix4 g_transform_box2 = matrix4_translation_for_vec3(Vector3(-16.0f, 16.0f, 28.0f)); -Matrix4 g_transform_box3 = matrix4_translation_for_vec3(Vector3(16.0f, -16.0f, -28.0f)); -Matrix4 g_transform_box4 = matrix4_translation_for_vec3(Vector3(-16.0f, -16.0f, -28.0f)); +Matrix4 g_transform_box1 = matrix4_translation_for_vec3( Vector3( 16.0f, 16.0f, 28.0f ) ); +Matrix4 g_transform_box2 = matrix4_translation_for_vec3( Vector3( -16.0f, 16.0f, 28.0f ) ); +Matrix4 g_transform_box3 = matrix4_translation_for_vec3( Vector3( 16.0f, -16.0f, -28.0f ) ); +Matrix4 g_transform_box4 = matrix4_translation_for_vec3( Vector3( -16.0f, -16.0f, -28.0f ) ); -void DBobView::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!path) +void DBobView::renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if ( !path ) { return; + } - renderer.SetState(m_shader_line, Renderer::eWireframeOnly); - renderer.SetState(m_shader_line, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_matrix4_identity); - - if(m_bShowExtra) - { - renderer.SetState(m_shader_box, Renderer::eWireframeOnly); - renderer.SetState(m_shader_box, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_transform_box1); - renderer.addRenderable(*this, g_transform_box2); - renderer.addRenderable(*this, g_transform_box3); - renderer.addRenderable(*this, g_transform_box4); - } + renderer.SetState( m_shader_line, Renderer::eWireframeOnly ); + renderer.SetState( m_shader_line, Renderer::eFullMaterials ); + renderer.addRenderable( *this, g_matrix4_identity ); + + if ( m_bShowExtra ) { + renderer.SetState( m_shader_box, Renderer::eWireframeOnly ); + renderer.SetState( m_shader_box, Renderer::eFullMaterials ); + renderer.addRenderable( *this, g_transform_box1 ); + renderer.addRenderable( *this, g_transform_box2 ); + renderer.addRenderable( *this, g_transform_box3 ); + renderer.addRenderable( *this, g_transform_box4 ); + } } -void DBobView::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - renderSolid(renderer, volume); +void DBobView::renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); } -void DBobView::SetPath(vec3_t *pPath) -{ - if(path) +void DBobView::SetPath( vec3_t *pPath ){ + if ( path ) { delete[] path; + } path = pPath; } #define LOCAL_GRAVITY -800.0f -bool DBobView::CalculateTrajectory(vec3_t start, vec3_t apex, float multiplier, int points, float varGravity) -{ - if(apex[2] <= start[2]) - { - SetPath(NULL); +bool DBobView::CalculateTrajectory( vec3_t start, vec3_t apex, float multiplier, int points, float varGravity ){ + if ( apex[2] <= start[2] ) { + SetPath( NULL ); return false; } // ----think q3a actually would allow these //scrub that, coz the plugin wont :] vec3_t dist, speed; - VectorSubtract(apex, start, dist); + VectorSubtract( apex, start, dist ); - vec_t speed_z = (float)sqrt(-2*LOCAL_GRAVITY*dist[2]); - float flight_time = -speed_z/LOCAL_GRAVITY; + vec_t speed_z = (float)sqrt( -2 * LOCAL_GRAVITY * dist[2] ); + float flight_time = -speed_z / LOCAL_GRAVITY; - VectorScale(dist, 1/flight_time, speed); + VectorScale( dist, 1 / flight_time, speed ); speed[2] = speed_z; // Sys_Printf("Speed: (%.4f %.4f %.4f)\n", speed[0], speed[1], speed[2]); vec3_t* pPath = new vec3_t[points]; - float interval = multiplier*flight_time/points; - for(int i = 0; i < points; i++) + float interval = multiplier * flight_time / points; + for ( int i = 0; i < points; i++ ) { - float ltime = interval*i; + float ltime = interval * i; - VectorScale(speed, ltime, pPath[i]); - VectorAdd(pPath[i], start, pPath[i]); + VectorScale( speed, ltime, pPath[i] ); + VectorAdd( pPath[i], start, pPath[i] ); // could do this all with vectors // vGrav = {0, 0, -800.0f} @@ -190,92 +182,86 @@ bool DBobView::CalculateTrajectory(vec3_t start, vec3_t apex, float multiplier, // _VectorAdd(pPath[i], start, pPath[i]) // _VectorAdd(pPath[i], vAdd, pPath[i]) - pPath[i][2] = start[2] + (speed_z*ltime) + (varGravity*0.5f*ltime*ltime); + pPath[i][2] = start[2] + ( speed_z * ltime ) + ( varGravity * 0.5f * ltime * ltime ); } - SetPath(pPath); + SetPath( pPath ); return true; } -void DBobView::Begin(const char* trigger, const char *target, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra) -{ - strcpy(entTrigger, trigger); - strcpy(entTarget, target); +void DBobView::Begin( const char* trigger, const char *target, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra ){ + strcpy( entTrigger, trigger ); + strcpy( entTarget, target ); fMultiplier = multiplier; fVarGravity = varGravity; nPathCount = points; m_bShowExtra = bShowExtra; - if(!UpdatePath()) - { + if ( !UpdatePath() ) { globalErrorStream() << "Initialization Failure in DBobView::Begin"; delete this; } globalOutputStream() << "Initialization of Path Plotter succeeded."; } -bool DBobView::UpdatePath() -{ +bool DBobView::UpdatePath(){ vec3_t start, apex; - if(GetEntityCentre(entTrigger, start)) - { - if(GetEntityCentre(entTarget, apex)) - { - CalculateTrajectory(start, apex, fMultiplier, nPathCount, fVarGravity); + if ( GetEntityCentre( entTrigger, start ) ) { + if ( GetEntityCentre( entTarget, apex ) ) { + CalculateTrajectory( start, apex, fMultiplier, nPathCount, fVarGravity ); return true; } } return false; } -void DBobView_setEntity(Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra) -{ +void DBobView_setEntity( Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra ){ DEntity trigger; - trigger.LoadEPairList(&entity); + trigger.LoadEPairList( &entity ); - DEPair* trigger_ep = trigger.FindEPairByKey("targetname"); + DEPair* trigger_ep = trigger.FindEPairByKey( "targetname" ); - if(trigger_ep) - { - if(!strcmp(trigger.m_Classname, "trigger_push")) - { - DEPair* target_ep = trigger.FindEPairByKey("target"); - if(target_ep) - { - const scene::Path* entTarget = FindEntityFromTargetname(target_ep->value); - if(entTarget) - { - if(g_PathView) + if ( trigger_ep ) { + if ( !strcmp( trigger.m_Classname, "trigger_push" ) ) { + DEPair* target_ep = trigger.FindEPairByKey( "target" ); + if ( target_ep ) { + const scene::Path* entTarget = FindEntityFromTargetname( target_ep->value ); + if ( entTarget ) { + if ( g_PathView ) { delete g_PathView; + } g_PathView = new DBobView; - Entity* target = Node_getEntity(entTarget->top()); - if(target != 0) - { - if(!bNoUpdate) - { + Entity* target = Node_getEntity( entTarget->top() ); + if ( target != 0 ) { + if ( !bNoUpdate ) { g_PathView->trigger = &entity; - entity.attach(*g_PathView); + entity.attach( *g_PathView ); g_PathView->target = target; - target->attach(*g_PathView); + target->attach( *g_PathView ); } - g_PathView->Begin(trigger_ep->value, target_ep->value, multiplier, points, varGravity, bNoUpdate, bShowExtra); + g_PathView->Begin( trigger_ep->value, target_ep->value, multiplier, points, varGravity, bNoUpdate, bShowExtra ); } - else + else{ globalErrorStream() << "bobToolz PathPlotter: trigger_push ARGH\n"; + } } - else + else{ globalErrorStream() << "bobToolz PathPlotter: trigger_push target could not be found..\n"; + } } - else + else{ globalErrorStream() << "bobToolz PathPlotter: trigger_push has no target..\n"; + } } - else + else{ globalErrorStream() << "bobToolz PathPlotter: You must select a 'trigger_push' entity..\n"; - } - else + } + } + else{ globalErrorStream() << "bobToolz PathPlotter: Entity must have a targetname.\n"; + } return; } \ No newline at end of file diff --git a/contrib/bobtoolz/DBobView.h b/contrib/bobtoolz/DBobView.h index 6869e6bd..05c8ad29 100644 --- a/contrib/bobtoolz/DBobView.h +++ b/contrib/bobtoolz/DBobView.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DBobView.h: interface for the DBobView class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ #include "ientity.h" @@ -32,8 +32,8 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class DListener; class Shader; -#define BOUNDS_ALL 0 -#define BOUNDS_APEX 1 +#define BOUNDS_ALL 0 +#define BOUNDS_APEX 1 #if _MSC_VER > 1000 #pragma once @@ -41,66 +41,61 @@ class Shader; class DBobView : public Renderable, public OpenGLRenderable, public Entity::Observer { - Shader* m_shader_line; - Shader* m_shader_box; +Shader* m_shader_line; +Shader* m_shader_box; public: - DBobView(); - virtual ~DBobView(); +DBobView(); +virtual ~DBobView(); protected: - vec3_t* path; +vec3_t* path; public: - bool m_bShowExtra; - int boundingShow; - DListener* eyes; - float fVarGravity; - float fMultiplier; - int nPathCount; - - Entity* trigger; - Entity* target; - - bool UpdatePath(); - char entTarget[256]; - char entTrigger[256]; - void Begin(const char*, const char*, float, int, float, bool, bool); - bool CalculateTrajectory(vec3_t, vec3_t, float, int, float); - - void SetPath(vec3_t* pPath); - - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; - - void constructShaders(); - void destroyShaders(); - - void valueChanged(const char* value) - { - UpdatePath(); - } - typedef MemberCaller1 ValueChangedCaller; - void insert(const char* key, EntityKeyValue& value) - { - value.attach(ValueChangedCaller(*this)); - } - void erase(const char* key, EntityKeyValue& value) - { - value.detach(ValueChangedCaller(*this)); - } - void clear() - { - if(trigger != 0) - { - trigger->detach(*this); - target->detach(*this); - trigger = 0; - target = 0; - } - } +bool m_bShowExtra; +int boundingShow; +DListener* eyes; +float fVarGravity; +float fMultiplier; +int nPathCount; + +Entity* trigger; +Entity* target; + +bool UpdatePath(); +char entTarget[256]; +char entTrigger[256]; +void Begin( const char*, const char*, float, int, float, bool, bool ); +bool CalculateTrajectory( vec3_t, vec3_t, float, int, float ); + +void SetPath( vec3_t* pPath ); + +void render( RenderStateFlags state ) const; +void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; +void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + +void constructShaders(); +void destroyShaders(); + +void valueChanged( const char* value ){ + UpdatePath(); +} +typedef MemberCaller1 ValueChangedCaller; +void insert( const char* key, EntityKeyValue& value ){ + value.attach( ValueChangedCaller( *this ) ); +} +void erase( const char* key, EntityKeyValue& value ){ + value.detach( ValueChangedCaller( *this ) ); +} +void clear(){ + if ( trigger != 0 ) { + trigger->detach( *this ); + target->detach( *this ); + trigger = 0; + target = 0; + } +} }; class Entity; -void DBobView_setEntity(Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra); +void DBobView_setEntity( Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra ); #endif // !defined(AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/DBrush.cpp b/contrib/bobtoolz/DBrush.cpp index 96c884d2..7c24cd0f 100644 --- a/contrib/bobtoolz/DBrush.cpp +++ b/contrib/bobtoolz/DBrush.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DBrush.cpp: implementation of the DBrush class. // @@ -51,16 +51,14 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DBrush::DBrush(int ID) -{ +DBrush::DBrush( int ID ){ m_nBrushID = ID; bBoundsBuilt = false; QER_entity = NULL; QER_brush = NULL; } -DBrush::~DBrush() -{ +DBrush::~DBrush(){ ClearFaces(); ClearPoints(); } @@ -69,55 +67,52 @@ DBrush::~DBrush() // Implementation ////////////////////////////////////////////////////////////////////// -DPlane* DBrush::AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData) -{ +DPlane* DBrush::AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ){ #ifdef _DEBUG // Sys_Printf("(%f %f %f) (%f %f %f) (%f %f %f)\n", va[0], va[1], va[2], vb[0], vb[1], vb[2], vc[0], vc[1], vc[2]); #endif bBoundsBuilt = false; - DPlane* newFace = new DPlane(va, vb, vc, texData); - faceList.push_back(newFace); - + DPlane* newFace = new DPlane( va, vb, vc, texData ); + faceList.push_back( newFace ); + return newFace; } -int DBrush::BuildPoints() -{ +int DBrush::BuildPoints(){ ClearPoints(); - - if(faceList.size() <= 3) // if less than 3 faces, there can be no points - return 0; // with only 3 faces u can't have a bounded soild - for(std::list::const_iterator p1=faceList.begin(); p1!=faceList.end(); p1++) + if ( faceList.size() <= 3 ) { // if less than 3 faces, there can be no points + return 0; // with only 3 faces u can't have a bounded soild + + } + for ( std::list::const_iterator p1 = faceList.begin(); p1 != faceList.end(); p1++ ) { - std::list::const_iterator p2=p1; - for(p2++; p2!=faceList.end(); p2++) + std::list::const_iterator p2 = p1; + for ( p2++; p2 != faceList.end(); p2++ ) { - std::list::const_iterator p3=p2; - for(p3++; p3!=faceList.end(); p3++) + std::list::const_iterator p3 = p2; + for ( p3++; p3 != faceList.end(); p3++ ) { vec3_t pnt; - if((*p1)->PlaneIntersection(*p2, *p3, pnt)) - { - int pos = PointPosition(pnt); + if ( ( *p1 )->PlaneIntersection( *p2, *p3, pnt ) ) { + int pos = PointPosition( pnt ); - if(pos == POINT_IN_BRUSH) - { // ???? shouldn't happen here + if ( pos == POINT_IN_BRUSH ) { // ???? shouldn't happen here globalErrorStream() << "ERROR:: Build Brush Points: Point IN brush!!!\n"; } - else if(pos == POINT_ON_BRUSH) - { // normal point - if(!HasPoint(pnt)) - AddPoint(pnt); + else if ( pos == POINT_ON_BRUSH ) { // normal point + if ( !HasPoint( pnt ) ) { + AddPoint( pnt ); + } /* else - Sys_Printf("Duplicate Point Found, pyramids ahoy!!!!!\n");*/ + Sys_Printf("Duplicate Point Found, pyramids ahoy!!!!!\n");*/ // point lies on more that 3 planes } - + // otherwise point is removed due to another plane.. - // Sys_Printf("(%f, %f, %f)\n", pnt[0], pnt[1], pnt[2]); - } + // Sys_Printf("(%f, %f, %f)\n", pnt[0], pnt[1], pnt[2]); + } } } } @@ -126,111 +121,103 @@ int DBrush::BuildPoints() // Sys_Printf("%i points on brush\n", pointList.size()); #endif - return static_cast(pointList.size()); + return static_cast( pointList.size() ); } -void DBrush_addFace(DBrush& brush, const _QERFaceData& faceData) -{ - brush.AddFace(vector3_to_array(faceData.m_p0), vector3_to_array(faceData.m_p1), vector3_to_array(faceData.m_p2), 0); +void DBrush_addFace( DBrush& brush, const _QERFaceData& faceData ){ + brush.AddFace( vector3_to_array( faceData.m_p0 ), vector3_to_array( faceData.m_p1 ), vector3_to_array( faceData.m_p2 ), 0 ); } typedef ReferenceCaller1 DBrushAddFaceCaller; -void DBrush_addFaceTextured(DBrush& brush, const _QERFaceData& faceData) -{ - brush.AddFace(vector3_to_array(faceData.m_p0), vector3_to_array(faceData.m_p1), vector3_to_array(faceData.m_p2), &faceData); +void DBrush_addFaceTextured( DBrush& brush, const _QERFaceData& faceData ){ + brush.AddFace( vector3_to_array( faceData.m_p0 ), vector3_to_array( faceData.m_p1 ), vector3_to_array( faceData.m_p2 ), &faceData ); } typedef ReferenceCaller1 DBrushAddFaceTexturedCaller; -void DBrush::LoadFromBrush(scene::Instance& brush, bool textured) -{ +void DBrush::LoadFromBrush( scene::Instance& brush, bool textured ){ ClearFaces(); ClearPoints(); - GlobalBrushCreator().Brush_forEachFace(brush.path().top(), textured ? BrushFaceDataCallback(DBrushAddFaceTexturedCaller(*this)) : BrushFaceDataCallback(DBrushAddFaceCaller(*this))); + GlobalBrushCreator().Brush_forEachFace( brush.path().top(), textured ? BrushFaceDataCallback( DBrushAddFaceTexturedCaller( *this ) ) : BrushFaceDataCallback( DBrushAddFaceCaller( *this ) ) ); - QER_entity = brush.path().parent().get_pointer(); + QER_entity = brush.path().parent().get_pointer(); QER_brush = brush.path().top().get_pointer(); } -int DBrush::PointPosition(vec3_t pnt) -{ - int state = POINT_IN_BRUSH; // if nothing happens point is inside brush +int DBrush::PointPosition( vec3_t pnt ){ + int state = POINT_IN_BRUSH; // if nothing happens point is inside brush - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) + for ( std::list::const_iterator chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - float dist = (*chkPlane)->DistanceToPoint(pnt); + float dist = ( *chkPlane )->DistanceToPoint( pnt ); - if(dist > MAX_ROUND_ERROR) - return POINT_OUT_BRUSH; // if point is in front of plane, it CANT be in the brush - else if(fabs(dist) < MAX_ROUND_ERROR) - state = POINT_ON_BRUSH; // if point is ON plane point is either ON the brush - // or outside it, it can no longer be in it + if ( dist > MAX_ROUND_ERROR ) { + return POINT_OUT_BRUSH; // if point is in front of plane, it CANT be in the brush + } + else if ( fabs( dist ) < MAX_ROUND_ERROR ) { + state = POINT_ON_BRUSH; // if point is ON plane point is either ON the brush + } + // or outside it, it can no longer be in it } return state; } -void DBrush::ClearPoints() -{ - for(std::list::const_iterator deadPoint=pointList.begin(); deadPoint!=pointList.end(); deadPoint++) { +void DBrush::ClearPoints(){ + for ( std::list::const_iterator deadPoint = pointList.begin(); deadPoint != pointList.end(); deadPoint++ ) { delete *deadPoint; } pointList.clear(); } -void DBrush::ClearFaces() -{ +void DBrush::ClearFaces(){ bBoundsBuilt = false; - for(std::list::const_iterator deadPlane=faceList.begin(); deadPlane!=faceList.end(); deadPlane++) + for ( std::list::const_iterator deadPlane = faceList.begin(); deadPlane != faceList.end(); deadPlane++ ) { delete *deadPlane; } faceList.clear(); } -void DBrush::AddPoint(vec3_t pnt) -{ +void DBrush::AddPoint( vec3_t pnt ){ DPoint* newPoint = new DPoint; - VectorCopy(pnt, newPoint->_pnt); - pointList.push_back(newPoint); + VectorCopy( pnt, newPoint->_pnt ); + pointList.push_back( newPoint ); } -bool DBrush::HasPoint(vec3_t pnt) -{ - for(std::list::const_iterator chkPoint=pointList.begin(); chkPoint!=pointList.end(); chkPoint++) +bool DBrush::HasPoint( vec3_t pnt ){ + for ( std::list::const_iterator chkPoint = pointList.begin(); chkPoint != pointList.end(); chkPoint++ ) { - if(**chkPoint == pnt) + if ( **chkPoint == pnt ) { return true; + } } return false; } -int DBrush::RemoveRedundantPlanes() -{ +int DBrush::RemoveRedundantPlanes(){ int cnt = 0; std::list::iterator chkPlane; // find duplicate planes - std::list::iterator p1=faceList.begin(); + std::list::iterator p1 = faceList.begin(); - while( p1!=faceList.end() ) + while ( p1 != faceList.end() ) { std::list::iterator p2 = p1; - for(p2++; p2!=faceList.end(); p2++) + for ( p2++; p2 != faceList.end(); p2++ ) { - if(**p1 == **p2) - { - if(!strcmp((*p1)->m_shader.c_str(), "textures/common/caulk")) - { + if ( **p1 == **p2 ) { + if ( !strcmp( ( *p1 )->m_shader.c_str(), "textures/common/caulk" ) ) { delete *p1; - p1 = faceList.erase(p1); // duplicate plane + p1 = faceList.erase( p1 ); // duplicate plane } else { delete *p2; - p2 = faceList.erase(p2); // duplicate plane + p2 = faceList.erase( p2 ); // duplicate plane } cnt++; @@ -238,188 +225,197 @@ int DBrush::RemoveRedundantPlanes() } } - if( p2 == faceList.end() ) + if ( p2 == faceList.end() ) { p1++; + } } - + //+djbob kill planes with bad normal, they are more of a nuisance than losing a brush - chkPlane=faceList.begin(); - while( chkPlane!=faceList.end() ) + chkPlane = faceList.begin(); + while ( chkPlane != faceList.end() ) { - if(VectorLength((*chkPlane)->normal) == 0) // plane has bad normal - { + if ( VectorLength( ( *chkPlane )->normal ) == 0 ) { // plane has bad normal delete *chkPlane; - chkPlane = faceList.erase(chkPlane); + chkPlane = faceList.erase( chkPlane ); cnt++; - } else { + } + else { chkPlane++; } } //-djbob - - if(pointList.size() == 0) // if points may not have been built, build them + + if ( pointList.size() == 0 ) { // if points may not have been built, build them /* if(BuildPoints() == 0) // just let the planes die if they are all bad - return cnt;*/ - BuildPoints(); + return cnt;*/ + BuildPoints(); + } - chkPlane=faceList.begin(); - while(chkPlane != faceList.end()) + chkPlane = faceList.begin(); + while ( chkPlane != faceList.end() ) { - if((*chkPlane)->IsRedundant(pointList)) // checks that plane "0wnz" :), 3 or more points - { + if ( ( *chkPlane )->IsRedundant( pointList ) ) { // checks that plane "0wnz" :), 3 or more points delete *chkPlane; - chkPlane = faceList.erase(chkPlane); + chkPlane = faceList.erase( chkPlane ); cnt++; - } - else + } + else{ chkPlane++; + } } return cnt; } -bool DBrush::GetBounds(vec3_t min, vec3_t max) -{ +bool DBrush::GetBounds( vec3_t min, vec3_t max ){ BuildBounds(); - if(!bBoundsBuilt) + if ( !bBoundsBuilt ) { return false; + } - VectorCopy(bbox_min, min); - VectorCopy(bbox_max, max); + VectorCopy( bbox_min, min ); + VectorCopy( bbox_max, max ); return true; } -bool DBrush::BBoxCollision(DBrush* chkBrush) -{ +bool DBrush::BBoxCollision( DBrush* chkBrush ){ vec3_t min1, min2; vec3_t max1, max2; - GetBounds(min1, max1); - chkBrush->GetBounds(min2, max2); + GetBounds( min1, max1 ); + chkBrush->GetBounds( min2, max2 ); - if(min1[0] >= max2[0]) + if ( min1[0] >= max2[0] ) { return false; - if(min1[1] >= max2[1]) + } + if ( min1[1] >= max2[1] ) { return false; - if(min1[2] >= max2[2]) + } + if ( min1[2] >= max2[2] ) { return false; + } - if(max1[0] <= min2[0]) + if ( max1[0] <= min2[0] ) { return false; - if(max1[1] <= min2[1]) + } + if ( max1[1] <= min2[1] ) { return false; - if(max1[2] <= min2[2]) + } + if ( max1[2] <= min2[2] ) { return false; + } return true; } -DPlane* DBrush::HasPlane(DPlane* chkPlane) -{ - for(std::list::const_iterator brushPlane=faceList.begin(); brushPlane!=faceList.end(); brushPlane++) +DPlane* DBrush::HasPlane( DPlane* chkPlane ){ + for ( std::list::const_iterator brushPlane = faceList.begin(); brushPlane != faceList.end(); brushPlane++ ) { - if(**brushPlane == *chkPlane) + if ( **brushPlane == *chkPlane ) { return *brushPlane; + } } return NULL; } -bool DBrush::IsCutByPlane(DPlane *cuttingPlane) -{ +bool DBrush::IsCutByPlane( DPlane *cuttingPlane ){ bool isInFront; - if(pointList.size() == 0) - if(BuildPoints() == 0) + if ( pointList.size() == 0 ) { + if ( BuildPoints() == 0 ) { return false; + } + } std::list::const_iterator chkPnt = pointList.begin(); - if(chkPnt == pointList.end()) + if ( chkPnt == pointList.end() ) { return false; + } - float dist = cuttingPlane->DistanceToPoint((*chkPnt)->_pnt); + float dist = cuttingPlane->DistanceToPoint( ( *chkPnt )->_pnt ); - if(dist > MAX_ROUND_ERROR) + if ( dist > MAX_ROUND_ERROR ) { isInFront = false; - else if(dist < MAX_ROUND_ERROR) + } + else if ( dist < MAX_ROUND_ERROR ) { isInFront = true; - else + } + else{ return true; + } - for(chkPnt++=pointList.begin(); chkPnt!=pointList.end(); chkPnt++) + for ( chkPnt++ = pointList.begin(); chkPnt != pointList.end(); chkPnt++ ) { - dist = cuttingPlane->DistanceToPoint((*chkPnt)->_pnt); + dist = cuttingPlane->DistanceToPoint( ( *chkPnt )->_pnt ); - if(dist > MAX_ROUND_ERROR) - { - if(isInFront) + if ( dist > MAX_ROUND_ERROR ) { + if ( isInFront ) { return true; + } } - else if(dist < MAX_ROUND_ERROR) - { - if(!isInFront) + else if ( dist < MAX_ROUND_ERROR ) { + if ( !isInFront ) { return true; + } } - else + else{ return true; + } } return false; } -scene::Node* DBrush::BuildInRadiant(bool allowDestruction, int* changeCnt, scene::Node* entity) -{ - if(allowDestruction) - { +scene::Node* DBrush::BuildInRadiant( bool allowDestruction, int* changeCnt, scene::Node* entity ){ + if ( allowDestruction ) { bool kill = true; - - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) + + for ( std::list::const_iterator chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - if((*chkPlane)->m_bChkOk) - { + if ( ( *chkPlane )->m_bChkOk ) { kill = false; break; } } - if(kill) + if ( kill ) { return NULL; + } } //+djbob: fixed bug when brush had no faces "phantom brush" in radiant. - if(faceList.size() < 4) - { + if ( faceList.size() < 4 ) { globalErrorStream() << "Possible Phantom Brush Found, will not rebuild\n"; return NULL; } //-djbob - NodeSmartReference node(GlobalBrushCreator().createBrush()); + NodeSmartReference node( GlobalBrushCreator().createBrush() ); - for(std::list::const_iterator buildPlane=faceList.begin(); buildPlane!=faceList.end(); buildPlane++) { - if((*buildPlane)->AddToBrush(node) && changeCnt) { - (*changeCnt)++; + for ( std::list::const_iterator buildPlane = faceList.begin(); buildPlane != faceList.end(); buildPlane++ ) { + if ( ( *buildPlane )->AddToBrush( node ) && changeCnt ) { + ( *changeCnt )++; } } - if(entity) { - Node_getTraversable(*entity)->insert(node); - } else { - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(node); + if ( entity ) { + Node_getTraversable( *entity )->insert( node ); + } + else { + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( node ); } - QER_entity = entity; - QER_brush = node.get_pointer(); + QER_entity = entity; + QER_brush = node.get_pointer(); return node.get_pointer(); } -void DBrush::CutByPlane(DPlane *cutPlane, DBrush **newBrush1, DBrush **newBrush2) -{ - if(!IsCutByPlane(cutPlane)) - { +void DBrush::CutByPlane( DPlane *cutPlane, DBrush **newBrush1, DBrush **newBrush2 ){ + if ( !IsCutByPlane( cutPlane ) ) { *newBrush1 = NULL; *newBrush2 = NULL; return; @@ -427,15 +423,15 @@ void DBrush::CutByPlane(DPlane *cutPlane, DBrush **newBrush1, DBrush **newBrush2 DBrush* b1 = new DBrush; DBrush* b2 = new DBrush; - - for(std::list::const_iterator parsePlane=faceList.begin(); parsePlane!=faceList.end(); parsePlane++) + + for ( std::list::const_iterator parsePlane = faceList.begin(); parsePlane != faceList.end(); parsePlane++ ) { - b1->AddFace((*parsePlane)->points[0], (*parsePlane)->points[1], (*parsePlane)->points[2], NULL); - b2->AddFace((*parsePlane)->points[0], (*parsePlane)->points[1], (*parsePlane)->points[2], NULL); + b1->AddFace( ( *parsePlane )->points[0], ( *parsePlane )->points[1], ( *parsePlane )->points[2], NULL ); + b2->AddFace( ( *parsePlane )->points[0], ( *parsePlane )->points[1], ( *parsePlane )->points[2], NULL ); } - b1->AddFace(cutPlane->points[0], cutPlane->points[1], cutPlane->points[2], NULL); - b2->AddFace(cutPlane->points[2], cutPlane->points[1], cutPlane->points[0], NULL); + b1->AddFace( cutPlane->points[0], cutPlane->points[1], cutPlane->points[2], NULL ); + b2->AddFace( cutPlane->points[2], cutPlane->points[1], cutPlane->points[0], NULL ); b1->RemoveRedundantPlanes(); b2->RemoveRedundantPlanes(); @@ -444,68 +440,72 @@ void DBrush::CutByPlane(DPlane *cutPlane, DBrush **newBrush1, DBrush **newBrush2 *newBrush2 = b2; } -bool DBrush::IntersectsWith(DBrush *chkBrush) -{ - if(pointList.size() == 0) - if(BuildPoints() == 0) - return false; // invalid brush!!!! +bool DBrush::IntersectsWith( DBrush *chkBrush ){ + if ( pointList.size() == 0 ) { + if ( BuildPoints() == 0 ) { + return false; // invalid brush!!!! - if(chkBrush->pointList.size() == 0) - if(chkBrush->BuildPoints() == 0) - return false; // invalid brush!!!! - - if(!BBoxCollision(chkBrush)) + } + } + if ( chkBrush->pointList.size() == 0 ) { + if ( chkBrush->BuildPoints() == 0 ) { + return false; // invalid brush!!!! + + } + } + if ( !BBoxCollision( chkBrush ) ) { return false; + } std::list::const_iterator iplPlane; - for( iplPlane=faceList.begin(); iplPlane!=faceList.end(); iplPlane++) + for ( iplPlane = faceList.begin(); iplPlane != faceList.end(); iplPlane++ ) { bool allInFront = true; - for(std::list::const_iterator iPoint=chkBrush->pointList.begin(); iPoint!=chkBrush->pointList.end(); iPoint++) + for ( std::list::const_iterator iPoint = chkBrush->pointList.begin(); iPoint != chkBrush->pointList.end(); iPoint++ ) { - if((*iplPlane)->DistanceToPoint((*iPoint)->_pnt) < -MAX_ROUND_ERROR) - { + if ( ( *iplPlane )->DistanceToPoint( ( *iPoint )->_pnt ) < -MAX_ROUND_ERROR ) { allInFront = false; break; } } - if(allInFront) + if ( allInFront ) { return false; + } } - for( iplPlane=chkBrush->faceList.begin(); iplPlane!=chkBrush->faceList.end(); iplPlane++) + for ( iplPlane = chkBrush->faceList.begin(); iplPlane != chkBrush->faceList.end(); iplPlane++ ) { bool allInFront = true; - for(std::list::const_iterator iPoint=pointList.begin(); iPoint!=pointList.end(); iPoint++) + for ( std::list::const_iterator iPoint = pointList.begin(); iPoint != pointList.end(); iPoint++ ) { - if((*iplPlane)->DistanceToPoint((*iPoint)->_pnt) < -MAX_ROUND_ERROR) - { + if ( ( *iplPlane )->DistanceToPoint( ( *iPoint )->_pnt ) < -MAX_ROUND_ERROR ) { allInFront = false; break; } } - if(allInFront) + if ( allInFront ) { return false; + } } return true; } -bool DBrush::IntersectsWith(DPlane* p1, DPlane* p2, vec3_t v) { +bool DBrush::IntersectsWith( DPlane* p1, DPlane* p2, vec3_t v ) { vec3_t vDown = { 0, 0, -1 }; std::list::const_iterator iplPlane; - for( iplPlane = faceList.begin(); iplPlane != faceList.end(); iplPlane++) { - DPlane* p = (*iplPlane); - + for ( iplPlane = faceList.begin(); iplPlane != faceList.end(); iplPlane++ ) { + DPlane* p = ( *iplPlane ); + vec_t d = DotProduct( p->normal, vDown ); - if( d >= 0 ) { + if ( d >= 0 ) { continue; } - if(p->PlaneIntersection(p1, p2, v)) { - if(PointPosition( v ) != POINT_OUT_BRUSH) { + if ( p->PlaneIntersection( p1, p2, v ) ) { + if ( PointPosition( v ) != POINT_OUT_BRUSH ) { return true; } } @@ -514,149 +514,161 @@ bool DBrush::IntersectsWith(DPlane* p1, DPlane* p2, vec3_t v) { return false; } -void DBrush::BuildBounds() -{ - if(!bBoundsBuilt) - { - if(pointList.size() == 0) // if points may not have been built, build them - if(BuildPoints() == 0) +void DBrush::BuildBounds(){ + if ( !bBoundsBuilt ) { + if ( pointList.size() == 0 ) { // if points may not have been built, build them + if ( BuildPoints() == 0 ) { return; - + } + } + std::list::const_iterator first = pointList.begin(); - VectorCopy((*first)->_pnt, bbox_min); - VectorCopy((*first)->_pnt, bbox_max); + VectorCopy( ( *first )->_pnt, bbox_min ); + VectorCopy( ( *first )->_pnt, bbox_max ); - std::list::const_iterator point=pointList.begin(); - for( point++; point!=pointList.end(); point++) + std::list::const_iterator point = pointList.begin(); + for ( point++; point != pointList.end(); point++ ) { - if((*point)->_pnt[0] > bbox_max[0]) - bbox_max[0] = (*point)->_pnt[0]; - if((*point)->_pnt[1] > bbox_max[1]) - bbox_max[1] = (*point)->_pnt[1]; - if((*point)->_pnt[2] > bbox_max[2]) - bbox_max[2] = (*point)->_pnt[2]; + if ( ( *point )->_pnt[0] > bbox_max[0] ) { + bbox_max[0] = ( *point )->_pnt[0]; + } + if ( ( *point )->_pnt[1] > bbox_max[1] ) { + bbox_max[1] = ( *point )->_pnt[1]; + } + if ( ( *point )->_pnt[2] > bbox_max[2] ) { + bbox_max[2] = ( *point )->_pnt[2]; + } - if((*point)->_pnt[0] < bbox_min[0]) - bbox_min[0] = (*point)->_pnt[0]; - if((*point)->_pnt[1] < bbox_min[1]) - bbox_min[1] = (*point)->_pnt[1]; - if((*point)->_pnt[2] < bbox_min[2]) - bbox_min[2] = (*point)->_pnt[2]; + if ( ( *point )->_pnt[0] < bbox_min[0] ) { + bbox_min[0] = ( *point )->_pnt[0]; + } + if ( ( *point )->_pnt[1] < bbox_min[1] ) { + bbox_min[1] = ( *point )->_pnt[1]; + } + if ( ( *point )->_pnt[2] < bbox_min[2] ) { + bbox_min[2] = ( *point )->_pnt[2]; + } } bBoundsBuilt = true; } } -bool DBrush::BBoxTouch(DBrush *chkBrush) -{ +bool DBrush::BBoxTouch( DBrush *chkBrush ){ vec3_t min1, min2; vec3_t max1, max2; - GetBounds(min1, max1); - chkBrush->GetBounds(min2, max2); + GetBounds( min1, max1 ); + chkBrush->GetBounds( min2, max2 ); - if((min1[0] - max2[0]) > MAX_ROUND_ERROR) + if ( ( min1[0] - max2[0] ) > MAX_ROUND_ERROR ) { return false; - if((min1[1] - max2[1]) > MAX_ROUND_ERROR) + } + if ( ( min1[1] - max2[1] ) > MAX_ROUND_ERROR ) { return false; - if((min1[2] - max2[2]) > MAX_ROUND_ERROR) + } + if ( ( min1[2] - max2[2] ) > MAX_ROUND_ERROR ) { return false; + } - if((min2[0] - max1[0]) > MAX_ROUND_ERROR) + if ( ( min2[0] - max1[0] ) > MAX_ROUND_ERROR ) { return false; - if((min2[1] - max1[1]) > MAX_ROUND_ERROR) + } + if ( ( min2[1] - max1[1] ) > MAX_ROUND_ERROR ) { return false; - if((min2[2] - max1[2]) > MAX_ROUND_ERROR) + } + if ( ( min2[2] - max1[2] ) > MAX_ROUND_ERROR ) { return false; + } int cnt = 0; - if((min2[0] - max1[0]) == 0) + if ( ( min2[0] - max1[0] ) == 0 ) { cnt++; + } - if((min2[1] - max1[1]) == 0) + if ( ( min2[1] - max1[1] ) == 0 ) { cnt++; + } - if((min2[2] - max1[2]) == 0) + if ( ( min2[2] - max1[2] ) == 0 ) { cnt++; + } - if((min1[0] - max2[0]) == 0) + if ( ( min1[0] - max2[0] ) == 0 ) { cnt++; + } - if((min1[1] - max2[1]) == 0) + if ( ( min1[1] - max2[1] ) == 0 ) { cnt++; + } - if((min1[2] - max2[2]) == 0) + if ( ( min1[2] - max2[2] ) == 0 ) { cnt++; + } - if(cnt > 1) + if ( cnt > 1 ) { return false; + } return true; } -void DBrush::ResetChecks(std::list* exclusionList) -{ - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) +void DBrush::ResetChecks( std::list* exclusionList ){ + for ( std::list::const_iterator resetPlane = faceList.begin(); resetPlane != faceList.end(); resetPlane++ ) { bool set = false; - if(exclusionList) - { - for(std::list::iterator eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++) + if ( exclusionList ) { + for ( std::list::iterator eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++ ) { - if(strstr((*resetPlane)->m_shader.c_str(), eTexture->GetBuffer())) - { + if ( strstr( ( *resetPlane )->m_shader.c_str(), eTexture->GetBuffer() ) ) { set = true; break; } } } - (*resetPlane)->m_bChkOk = set; + ( *resetPlane )->m_bChkOk = set; } } -DPlane* DBrush::HasPlaneInverted(DPlane *chkPlane) -{ - for(std::list::const_iterator brushPlane=faceList.begin(); brushPlane!=faceList.end(); brushPlane++) +DPlane* DBrush::HasPlaneInverted( DPlane *chkPlane ){ + for ( std::list::const_iterator brushPlane = faceList.begin(); brushPlane != faceList.end(); brushPlane++ ) { - if(**brushPlane != *chkPlane) - { - if(fabs((*brushPlane)->_d + chkPlane->_d) < 0.1) - return (*brushPlane); + if ( **brushPlane != *chkPlane ) { + if ( fabs( ( *brushPlane )->_d + chkPlane->_d ) < 0.1 ) { + return ( *brushPlane ); + } } } return NULL; } -bool DBrush::HasTexture(const char *textureName) -{ - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) +bool DBrush::HasTexture( const char *textureName ){ + for ( std::list::const_iterator chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - if(strstr((*chkPlane)->m_shader.c_str(), textureName)) + if ( strstr( ( *chkPlane )->m_shader.c_str(), textureName ) ) { return true; + } } return false; } -bool DBrush::IsDetail() -{ - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) +bool DBrush::IsDetail(){ + for ( std::list::const_iterator chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - if((*chkPlane)->texInfo.contents & FACE_DETAIL) + if ( ( *chkPlane )->texInfo.contents & FACE_DETAIL ) { return true; + } } return false; } -void DBrush::BuildFromWinding(DWinding *w) -{ - if(w->numpoints < 3) - { +void DBrush::BuildFromWinding( DWinding *w ){ + if ( w->numpoints < 3 ) { globalErrorStream() << "Winding has invalid number of points"; return; } @@ -666,89 +678,89 @@ void DBrush::BuildFromWinding(DWinding *w) DWinding* w2; w2 = w->CopyWinding(); int i; - for(i = 0; i < w2->numpoints; i++) - VectorAdd(w2->p[i], wPlane->normal, w2->p[i]); + for ( i = 0; i < w2->numpoints; i++ ) + VectorAdd( w2->p[i], wPlane->normal, w2->p[i] ); - AddFace(w2->p[0], w2->p[1], w2->p[2], NULL); - AddFace(w->p[2], w->p[1], w->p[0], NULL); + AddFace( w2->p[0], w2->p[1], w2->p[2], NULL ); + AddFace( w->p[2], w->p[1], w->p[0], NULL ); - for(i = 0; i < w->numpoints-1; i++) - AddFace(w2->p[i], w->p[i], w->p[i+1], NULL); - AddFace(w2->p[w->numpoints-1], w->p[w->numpoints-1], w->p[0], NULL); + for ( i = 0; i < w->numpoints - 1; i++ ) + AddFace( w2->p[i], w->p[i], w->p[i + 1], NULL ); + AddFace( w2->p[w->numpoints - 1], w->p[w->numpoints - 1], w->p[0], NULL ); delete wPlane; delete w2; } -void DBrush::SaveToFile(FILE *pFile) -{ - fprintf(pFile, "{\n"); +void DBrush::SaveToFile( FILE *pFile ){ + fprintf( pFile, "{\n" ); - for(std::list::const_iterator pp=faceList.begin(); pp!=faceList.end(); pp++) + for ( std::list::const_iterator pp = faceList.begin(); pp != faceList.end(); pp++ ) { char buffer[512]; - sprintf(buffer, "( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) %s %.0f %.0f %f %f %.0f 0 0 0\n", - (*pp)->points[0][0], (*pp)->points[0][1], (*pp)->points[0][2], - (*pp)->points[1][0], (*pp)->points[1][1], (*pp)->points[1][2], - (*pp)->points[2][0], (*pp)->points[2][1], (*pp)->points[2][2], - (*pp)->m_shader.c_str(), - (*pp)->texInfo.m_texdef.shift[0], (*pp)->texInfo.m_texdef.shift[1], - (*pp)->texInfo.m_texdef.scale[0], (*pp)->texInfo.m_texdef.scale[0], - (*pp)->texInfo.m_texdef.rotate); + sprintf( buffer, "( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) %s %.0f %.0f %f %f %.0f 0 0 0\n", + ( *pp )->points[0][0], ( *pp )->points[0][1], ( *pp )->points[0][2], + ( *pp )->points[1][0], ( *pp )->points[1][1], ( *pp )->points[1][2], + ( *pp )->points[2][0], ( *pp )->points[2][1], ( *pp )->points[2][2], + ( *pp )->m_shader.c_str(), + ( *pp )->texInfo.m_texdef.shift[0], ( *pp )->texInfo.m_texdef.shift[1], + ( *pp )->texInfo.m_texdef.scale[0], ( *pp )->texInfo.m_texdef.scale[0], + ( *pp )->texInfo.m_texdef.rotate ); - fprintf(pFile, buffer); + fprintf( pFile, buffer ); } - fprintf(pFile, "}\n"); + fprintf( pFile, "}\n" ); } -void DBrush::Rotate(vec3_t vOrigin, vec3_t vRotation) -{ - for(std::list::const_iterator rotPlane=faceList.begin(); rotPlane!=faceList.end(); rotPlane++) +void DBrush::Rotate( vec3_t vOrigin, vec3_t vRotation ){ + for ( std::list::const_iterator rotPlane = faceList.begin(); rotPlane != faceList.end(); rotPlane++ ) { - for(int i = 0; i < 3; i++) - VectorRotate((*rotPlane)->points[i], vRotation, vOrigin); + for ( int i = 0; i < 3; i++ ) + VectorRotate( ( *rotPlane )->points[i], vRotation, vOrigin ); - (*rotPlane)->Rebuild(); + ( *rotPlane )->Rebuild(); } } -void DBrush::RotateAboutCentre(vec3_t vRotation) -{ +void DBrush::RotateAboutCentre( vec3_t vRotation ){ vec3_t min, max, centre; - GetBounds(min, max); - VectorAdd(min, max, centre); - VectorScale(centre, 0.5f, centre); + GetBounds( min, max ); + VectorAdd( min, max, centre ); + VectorScale( centre, 0.5f, centre ); - Rotate(centre, vRotation); + Rotate( centre, vRotation ); } -bool DBrush::ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation) -{ - if(textureName) - { +bool DBrush::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ + if ( textureName ) { bool changed = false; - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) + for ( std::list::const_iterator resetPlane = faceList.begin(); resetPlane != faceList.end(); resetPlane++ ) { - if(!strcmp((*resetPlane)->m_shader.c_str(), textureName)) - { - if(bResetTextureName) - (*resetPlane)->m_shader = newTextureName; + if ( !strcmp( ( *resetPlane )->m_shader.c_str(), textureName ) ) { + if ( bResetTextureName ) { + ( *resetPlane )->m_shader = newTextureName; + } - if(bResetScale[0]) - (*resetPlane)->texInfo.m_texdef.scale[0] = fScale[0]; - if(bResetScale[1]) - (*resetPlane)->texInfo.m_texdef.scale[1] = fScale[1]; + if ( bResetScale[0] ) { + ( *resetPlane )->texInfo.m_texdef.scale[0] = fScale[0]; + } + if ( bResetScale[1] ) { + ( *resetPlane )->texInfo.m_texdef.scale[1] = fScale[1]; + } - if(bResetShift[0]) - (*resetPlane)->texInfo.m_texdef.shift[0] = fShift[0]; - if(bResetShift[1]) - (*resetPlane)->texInfo.m_texdef.shift[1] = fShift[1]; + if ( bResetShift[0] ) { + ( *resetPlane )->texInfo.m_texdef.shift[0] = fShift[0]; + } + if ( bResetShift[1] ) { + ( *resetPlane )->texInfo.m_texdef.shift[1] = fShift[1]; + } - if(bResetRotation) - (*resetPlane)->texInfo.m_texdef.rotate = (float)rotation; + if ( bResetRotation ) { + ( *resetPlane )->texInfo.m_texdef.rotate = (float)rotation; + } changed = true; } @@ -757,53 +769,59 @@ bool DBrush::ResetTextures(const char* textureName, float fScale[2], float fS } else { - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) + for ( std::list::const_iterator resetPlane = faceList.begin(); resetPlane != faceList.end(); resetPlane++ ) { - if(bResetTextureName) - (*resetPlane)->m_shader = newTextureName; + if ( bResetTextureName ) { + ( *resetPlane )->m_shader = newTextureName; + } - if(bResetScale[0]) - (*resetPlane)->texInfo.m_texdef.scale[0] = fScale[0]; - if(bResetScale[1]) - (*resetPlane)->texInfo.m_texdef.scale[1] = fScale[1]; + if ( bResetScale[0] ) { + ( *resetPlane )->texInfo.m_texdef.scale[0] = fScale[0]; + } + if ( bResetScale[1] ) { + ( *resetPlane )->texInfo.m_texdef.scale[1] = fScale[1]; + } - if(bResetShift[0]) - (*resetPlane)->texInfo.m_texdef.shift[0] = fShift[0]; - if(bResetShift[1]) - (*resetPlane)->texInfo.m_texdef.shift[1] = fShift[1]; + if ( bResetShift[0] ) { + ( *resetPlane )->texInfo.m_texdef.shift[0] = fShift[0]; + } + if ( bResetShift[1] ) { + ( *resetPlane )->texInfo.m_texdef.shift[1] = fShift[1]; + } - if(bResetRotation) - (*resetPlane)->texInfo.m_texdef.rotate = (float)rotation; + if ( bResetRotation ) { + ( *resetPlane )->texInfo.m_texdef.rotate = (float)rotation; + } } return true; } } -bool DBrush::operator ==(DBrush* other) -{ +bool DBrush::operator ==( DBrush* other ){ std::list::const_iterator chkPlane; - - for(chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) + + for ( chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - if(!other->HasPlane((*chkPlane))) + if ( !other->HasPlane( ( *chkPlane ) ) ) { return false; + } } - for(chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) + for ( chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - if(!HasPlane((*chkPlane))) + if ( !HasPlane( ( *chkPlane ) ) ) { return false; + } } return true; } -DPlane* DBrush::AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const char *textureName, bool bDetail) -{ +DPlane* DBrush::AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const char *textureName, bool bDetail ){ bBoundsBuilt = false; - DPlane* newFace = new DPlane(va, vb, vc, textureName, bDetail); - faceList.push_back(newFace); - + DPlane* newFace = new DPlane( va, vb, vc, textureName, bDetail ); + faceList.push_back( newFace ); + return newFace; } @@ -811,11 +829,11 @@ DPlane* DBrush::FindPlaneWithClosestNormal( vec_t* normal ) { vec_t bestDot = -2; DPlane* bestDotPlane = NULL; std::list::const_iterator chkPlane; - for( chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - DPlane* pPlane = (*chkPlane); + for ( chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { + DPlane* pPlane = ( *chkPlane ); vec_t dot = DotProduct( pPlane->normal, normal ); - if( dot > bestDot ) { + if ( dot > bestDot ) { bestDot = dot; bestDotPlane = pPlane; } @@ -827,20 +845,20 @@ DPlane* DBrush::FindPlaneWithClosestNormal( vec_t* normal ) { int DBrush::FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ) { int numpnts = 0; - if(!maxpnts) { + if ( !maxpnts ) { return 0; } BuildPoints(); - for( std::list::const_iterator points = pointList.begin(); points != pointList.end(); points++ ) { - DPoint* point = (*points); + for ( std::list::const_iterator points = pointList.begin(); points != pointList.end(); points++ ) { + DPoint* point = ( *points ); - if( fabs(plane->DistanceToPoint( point->_pnt )) < MAX_ROUND_ERROR ) { + if ( fabs( plane->DistanceToPoint( point->_pnt ) ) < MAX_ROUND_ERROR ) { pnts[numpnts] = point; numpnts++; - if(numpnts >= maxpnts) { + if ( numpnts >= maxpnts ) { return numpnts; } @@ -852,8 +870,8 @@ int DBrush::FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ) { void DBrush::RemovePlane( DPlane* plane ) { bBoundsBuilt = false; - for( std::list::const_iterator deadPlane = faceList.begin(); deadPlane != faceList.end(); deadPlane++ ) { - if(*deadPlane == plane) { + for ( std::list::const_iterator deadPlane = faceList.begin(); deadPlane != faceList.end(); deadPlane++ ) { + if ( *deadPlane == plane ) { delete *deadPlane; faceList.remove( plane ); } diff --git a/contrib/bobtoolz/DBrush.h b/contrib/bobtoolz/DBrush.h index 112f2294..b5e343eb 100644 --- a/contrib/bobtoolz/DBrush.h +++ b/contrib/bobtoolz/DBrush.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DBrush.h: interface for the DBrush class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -40,74 +40,74 @@ class _QERFaceData; namespace scene { - class Node; - class Instance; +class Node; +class Instance; } -#define POINT_IN_BRUSH 0 -#define POINT_ON_BRUSH 1 -#define POINT_OUT_BRUSH 2 +#define POINT_IN_BRUSH 0 +#define POINT_ON_BRUSH 1 +#define POINT_OUT_BRUSH 2 -class DBrush +class DBrush { public: - DPlane* AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail); - void SaveToFile(FILE* pFile); +DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); +void SaveToFile( FILE* pFile ); - void Rotate(vec3_t vOrigin, vec3_t vRotation); - void RotateAboutCentre(vec3_t vRotation); +void Rotate( vec3_t vOrigin, vec3_t vRotation ); +void RotateAboutCentre( vec3_t vRotation ); - DPlane* HasPlaneInverted(DPlane* chkPlane); - DPlane* HasPlane(DPlane* chkPlane); - DPlane* AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData); +DPlane* HasPlaneInverted( DPlane* chkPlane ); +DPlane* HasPlane( DPlane* chkPlane ); +DPlane* AddFace( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); - bool ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation); - bool IsDetail(); - bool HasTexture(const char* textureName); - bool IntersectsWith(DBrush *chkBrush); - bool IntersectsWith(DPlane* p1, DPlane* p2, vec3_t v); - bool IsCutByPlane(DPlane* cuttingPlane); - bool GetBounds(vec3_t min, vec3_t max); - bool HasPoint(vec3_t pnt); - bool BBoxCollision(DBrush* chkBrush); - bool BBoxTouch(DBrush* chkBrush); +bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); +bool IsDetail(); +bool HasTexture( const char* textureName ); +bool IntersectsWith( DBrush *chkBrush ); +bool IntersectsWith( DPlane* p1, DPlane* p2, vec3_t v ); +bool IsCutByPlane( DPlane* cuttingPlane ); +bool GetBounds( vec3_t min, vec3_t max ); +bool HasPoint( vec3_t pnt ); +bool BBoxCollision( DBrush* chkBrush ); +bool BBoxTouch( DBrush* chkBrush ); - int BuildPoints(); - void BuildBounds(); - void BuildFromWinding(DWinding* w); - scene::Node* BuildInRadiant(bool allowDestruction, int* changeCnt, scene::Node* entity = NULL); +int BuildPoints(); +void BuildBounds(); +void BuildFromWinding( DWinding* w ); +scene::Node* BuildInRadiant( bool allowDestruction, int* changeCnt, scene::Node* entity = NULL ); - void ResetChecks(std::list* exclusionList); +void ResetChecks( std::list* exclusionList ); - void ClearFaces(); - void ClearPoints(); - - int RemoveRedundantPlanes( void ); - void RemovePlane( DPlane* plane ); - int PointPosition(vec3_t pnt); +void ClearFaces(); +void ClearPoints(); - - void CutByPlane(DPlane* cutPlane, DBrush** newBrush1, DBrush** newBrush2); +int RemoveRedundantPlanes( void ); +void RemovePlane( DPlane* plane ); +int PointPosition( vec3_t pnt ); - void LoadFromBrush(scene::Instance& brush, bool textured); - void AddPoint(vec3_t pnt); - DPlane* FindPlaneWithClosestNormal( vec_t* normal ); - int FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ); +void CutByPlane( DPlane* cutPlane, DBrush** newBrush1, DBrush** newBrush2 ); - DBrush(int ID = -1); - virtual ~DBrush(); +void LoadFromBrush( scene::Instance& brush, bool textured ); +void AddPoint( vec3_t pnt ); - bool operator== (DBrush* other); +DPlane* FindPlaneWithClosestNormal( vec_t* normal ); +int FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ); + +DBrush( int ID = -1 ); +virtual ~DBrush(); + +bool operator==( DBrush* other ); // members - scene::Node* QER_entity; - scene::Node* QER_brush; - std::list faceList; - std::list pointList; - int m_nBrushID; - vec3_t bbox_min, bbox_max; - bool bBoundsBuilt; +scene::Node* QER_entity; +scene::Node* QER_brush; +std::list faceList; +std::list pointList; +int m_nBrushID; +vec3_t bbox_min, bbox_max; +bool bBoundsBuilt; }; //typedef CList DBrushList; diff --git a/contrib/bobtoolz/DEPair.cpp b/contrib/bobtoolz/DEPair.cpp index 72dda4b3..c75a8751 100644 --- a/contrib/bobtoolz/DEPair.cpp +++ b/contrib/bobtoolz/DEPair.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DEPair.cpp: implementation of the DEPair class. // @@ -27,13 +27,11 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DEPair::DEPair() -{ +DEPair::DEPair(){ } -DEPair::~DEPair() -{ +DEPair::~DEPair(){ } @@ -41,8 +39,7 @@ DEPair::~DEPair() // Implementation ////////////////////////////////////////////////////////////////////// -void DEPair::Build(const char *pKey, const char *pValue) -{ - key = pKey; - value = pValue; +void DEPair::Build( const char *pKey, const char *pValue ){ + key = pKey; + value = pValue; } diff --git a/contrib/bobtoolz/DEPair.h b/contrib/bobtoolz/DEPair.h index fac4c334..3b5ca3ae 100644 --- a/contrib/bobtoolz/DEPair.h +++ b/contrib/bobtoolz/DEPair.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DEPair.h: interface for the DEPair class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -30,16 +30,16 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "str.h" -class DEPair +class DEPair { public: - DEPair(); - virtual ~DEPair(); +DEPair(); +virtual ~DEPair(); - void Build(const char* pKey, const char* pValue); +void Build( const char* pKey, const char* pValue ); - Str key; - Str value; +Str key; +Str value; }; //typedef CList DEPairList; diff --git a/contrib/bobtoolz/DEntity.cpp b/contrib/bobtoolz/DEntity.cpp index f03b489e..38ab47f4 100644 --- a/contrib/bobtoolz/DEntity.cpp +++ b/contrib/bobtoolz/DEntity.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DEntity.cpp: implementation of the DEntity class. // @@ -78,15 +78,13 @@ const char* brushEntityList[] = { // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DEntity::DEntity(const char *classname, int ID) -{ - SetClassname(classname); +DEntity::DEntity( const char *classname, int ID ){ + SetClassname( classname ); m_nID = ID; QER_Entity = NULL; } -DEntity::~DEntity() -{ +DEntity::~DEntity(){ ClearPatches(); ClearBrushes(); ClearEPairs(); @@ -96,132 +94,127 @@ DEntity::~DEntity() // Implementation ////////////////////////////////////////////////////////////////////// -void DEntity::ClearBrushes() -{ - for(std::list::const_iterator deadBrush=brushList.begin(); deadBrush!=brushList.end(); deadBrush++) +void DEntity::ClearBrushes(){ + for ( std::list::const_iterator deadBrush = brushList.begin(); deadBrush != brushList.end(); deadBrush++ ) { delete *deadBrush; } brushList.clear(); } -void DEntity::ClearPatches() -{ - for(std::list::const_iterator deadPatch=patchList.begin(); deadPatch!=patchList.end(); deadPatch++) +void DEntity::ClearPatches(){ + for ( std::list::const_iterator deadPatch = patchList.begin(); deadPatch != patchList.end(); deadPatch++ ) { delete *deadPatch; } patchList.clear(); } -DPatch* DEntity::NewPatch() -{ +DPatch* DEntity::NewPatch(){ DPatch* newPatch = new DPatch; - patchList.push_back(newPatch); + patchList.push_back( newPatch ); return newPatch; } -DBrush* DEntity::NewBrush(int ID) -{ - DBrush* newBrush = new DBrush(ID); +DBrush* DEntity::NewBrush( int ID ){ + DBrush* newBrush = new DBrush( ID ); - brushList.push_back(newBrush); + brushList.push_back( newBrush ); return newBrush; } -char* getNextBracket(char* s) -{ +char* getNextBracket( char* s ){ char* p = s; - while(*p) + while ( *p ) { p++; - if(*p == '(') + if ( *p == '(' ) { break; + } } return p; } -bool DEntity::LoadFromPrt(char *filename) -{ +bool DEntity::LoadFromPrt( char *filename ){ CPortals portals; - strcpy(portals.fn, filename); + strcpy( portals.fn, filename ); portals.Load(); - if(portals.node_count == 0) + if ( portals.node_count == 0 ) { return false; + } ClearBrushes(); ClearEPairs(); - - bool build = false; - for(unsigned int i = 0; i < portals.node_count; i++) + + bool build = false; + for ( unsigned int i = 0; i < portals.node_count; i++ ) { - build = false; + build = false; DBrush* brush = NewBrush(); - for(unsigned int j = 0; j < portals.node[i].portal_count; j++) + for ( unsigned int j = 0; j < portals.node[i].portal_count; j++ ) { - for(unsigned int k = 0; k < portals.node[i].portal[j].point_count-2; k++) - { - vec3_t v1, v2, normal, n; - VectorSubtract(portals.node[i].portal[j].point[k+2].p, portals.node[i].portal[j].point[k+1].p, v1); - VectorSubtract(portals.node[i].portal[j].point[k].p, portals.node[i].portal[j].point[k+1].p, v2); - CrossProduct(v1, v2, n); - VectorNormalize(n, v2); - - if(k == 0) - { - VectorCopy(v2, normal); - } - else - { - VectorSubtract(v2, normal, v1); - if(VectorLength(v1) > 0.01) - { - build = true; - break; - } - } - } - - if(!build) - brush->AddFace(portals.node[i].portal[j].point[2].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[0].p, "textures/common/caulk", false); - else - brush->AddFace(portals.node[i].portal[j].point[0].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[2].p, "textures/common/caulk", false); + for ( unsigned int k = 0; k < portals.node[i].portal[j].point_count - 2; k++ ) + { + vec3_t v1, v2, normal, n; + VectorSubtract( portals.node[i].portal[j].point[k + 2].p, portals.node[i].portal[j].point[k + 1].p, v1 ); + VectorSubtract( portals.node[i].portal[j].point[k].p, portals.node[i].portal[j].point[k + 1].p, v2 ); + CrossProduct( v1, v2, n ); + VectorNormalize( n, v2 ); + + if ( k == 0 ) { + VectorCopy( v2, normal ); + } + else + { + VectorSubtract( v2, normal, v1 ); + if ( VectorLength( v1 ) > 0.01 ) { + build = true; + break; + } + } + } + + if ( !build ) { + brush->AddFace( portals.node[i].portal[j].point[2].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[0].p, "textures/common/caulk", false ); + } + else{ + brush->AddFace( portals.node[i].portal[j].point[0].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[2].p, "textures/common/caulk", false ); + } + } + if ( build ) { + brush->BuildInRadiant( false, NULL ); } - if(build) - brush->BuildInRadiant(false, NULL); } return true; } -DPlane* DEntity::AddFaceToBrush(vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID) -{ - DBrush* buildBrush = GetBrushForID(ID); - return buildBrush->AddFace(va, vb, vc, faceData); +DPlane* DEntity::AddFaceToBrush( vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID ){ + DBrush* buildBrush = GetBrushForID( ID ); + return buildBrush->AddFace( va, vb, vc, faceData ); // slow, dont use much } -DBrush* DEntity::GetBrushForID(int ID) -{ +DBrush* DEntity::GetBrushForID( int ID ){ DBrush* buildBrush = NULL; - for(std::list::const_iterator chkBrush=brushList.begin(); chkBrush!=brushList.end(); chkBrush++) + for ( std::list::const_iterator chkBrush = brushList.begin(); chkBrush != brushList.end(); chkBrush++ ) { - if((*chkBrush)->m_nBrushID == ID) - { - buildBrush = (*chkBrush); + if ( ( *chkBrush )->m_nBrushID == ID ) { + buildBrush = ( *chkBrush ); break; } } - if(!buildBrush) - buildBrush = NewBrush(ID); + if ( !buildBrush ) { + buildBrush = NewBrush( ID ); + } return buildBrush; } @@ -229,99 +222,86 @@ DBrush* DEntity::GetBrushForID(int ID) template class BrushSelectedVisitor : public SelectionSystem::Visitor { - const Functor& m_functor; +const Functor& m_functor; public: - BrushSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - if(Node_isBrush(instance.path().top())) - { - m_functor(instance); - } - } +BrushSelectedVisitor( const Functor& functor ) : m_functor( functor ){ +} +void visit( scene::Instance& instance ) const { + if ( Node_isBrush( instance.path().top() ) ) { + m_functor( instance ); + } +} }; template -inline const Functor& Scene_forEachSelectedBrush(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor(functor)); - return functor; +inline const Functor& Scene_forEachSelectedBrush( const Functor& functor ){ + GlobalSelectionSystem().foreachSelected( BrushSelectedVisitor( functor ) ); + return functor; } -void DEntity_loadBrush(DEntity& entity, scene::Instance& brush) -{ - DBrush* loadBrush = entity.NewBrush(static_cast(entity.brushList.size())); - loadBrush->LoadFromBrush(brush, true); +void DEntity_loadBrush( DEntity& entity, scene::Instance& brush ){ + DBrush* loadBrush = entity.NewBrush( static_cast( entity.brushList.size() ) ); + loadBrush->LoadFromBrush( brush, true ); } typedef ReferenceCaller1 DEntityLoadBrushCaller; -void DEntity::LoadSelectedBrushes() -{ +void DEntity::LoadSelectedBrushes(){ ClearBrushes(); ClearEPairs(); - Scene_forEachSelectedBrush(DEntityLoadBrushCaller(*this)); + Scene_forEachSelectedBrush( DEntityLoadBrushCaller( *this ) ); } template class PatchSelectedVisitor : public SelectionSystem::Visitor { - const Functor& m_functor; +const Functor& m_functor; public: - PatchSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - if(Node_isPatch(instance.path().top())) - { - m_functor(instance); - } - } +PatchSelectedVisitor( const Functor& functor ) : m_functor( functor ){ +} +void visit( scene::Instance& instance ) const { + if ( Node_isPatch( instance.path().top() ) ) { + m_functor( instance ); + } +} }; template -inline const Functor& Scene_forEachSelectedPatch(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(PatchSelectedVisitor(functor)); - return functor; +inline const Functor& Scene_forEachSelectedPatch( const Functor& functor ){ + GlobalSelectionSystem().foreachSelected( PatchSelectedVisitor( functor ) ); + return functor; } -void DEntity_loadPatch(DEntity& entity, scene::Instance& patch) -{ - DPatch* loadPatch = entity.NewPatch(); - loadPatch->LoadFromPatch(patch); +void DEntity_loadPatch( DEntity& entity, scene::Instance& patch ){ + DPatch* loadPatch = entity.NewPatch(); + loadPatch->LoadFromPatch( patch ); } typedef ReferenceCaller1 DEntityLoadPatchCaller; -void DEntity::LoadSelectedPatches() -{ +void DEntity::LoadSelectedPatches(){ ClearPatches(); ClearEPairs(); - Scene_forEachSelectedPatch(DEntityLoadPatchCaller(*this)); + Scene_forEachSelectedPatch( DEntityLoadPatchCaller( *this ) ); } -bool* DEntity::BuildIntersectList() -{ +bool* DEntity::BuildIntersectList(){ int max = GetIDMax(); - if(max == 0) + if ( max == 0 ) { return NULL; + } bool* pbIntList = new bool[max]; - memset(pbIntList, 0, sizeof(bool)*(max)); + memset( pbIntList, 0, sizeof( bool ) * ( max ) ); - for(std::list::const_iterator pB1=brushList.begin(); pB1!=brushList.end(); pB1++) + for ( std::list::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++ ) { - std::list::const_iterator pB2=pB1; - for(pB2++; pB2!=brushList.end(); pB2++) + std::list::const_iterator pB2 = pB1; + for ( pB2++; pB2 != brushList.end(); pB2++ ) { - if((*pB1)->IntersectsWith((*pB2))) - { - pbIntList[(*pB1)->m_nBrushID] = true; - pbIntList[(*pB2)->m_nBrushID] = true; + if ( ( *pB1 )->IntersectsWith( ( *pB2 ) ) ) { + pbIntList[( *pB1 )->m_nBrushID] = true; + pbIntList[( *pB2 )->m_nBrushID] = true; } } } @@ -329,24 +309,23 @@ bool* DEntity::BuildIntersectList() return pbIntList; } -bool* DEntity::BuildDuplicateList() -{ +bool* DEntity::BuildDuplicateList(){ int max = GetIDMax(); - if(max == 0) + if ( max == 0 ) { return NULL; + } bool* pbDupList = new bool[max]; - memset(pbDupList, 0, sizeof(bool)*(max)); + memset( pbDupList, 0, sizeof( bool ) * ( max ) ); - for(std::list::const_iterator pB1=brushList.begin(); pB1!=brushList.end(); pB1++) + for ( std::list::const_iterator pB1 = brushList.begin(); pB1 != brushList.end(); pB1++ ) { - std::list::const_iterator pB2=pB1; - for(pB2++; pB2!=brushList.end(); pB2++) + std::list::const_iterator pB2 = pB1; + for ( pB2++; pB2 != brushList.end(); pB2++ ) { - if(**pB1 == *pB2) - { - pbDupList[(*pB1)->m_nBrushID] = true; - pbDupList[(*pB2)->m_nBrushID] = true; + if ( **pB1 == *pB2 ) { + pbDupList[( *pB1 )->m_nBrushID] = true; + pbDupList[( *pB2 )->m_nBrushID] = true; } } } @@ -354,172 +333,159 @@ bool* DEntity::BuildDuplicateList() return pbDupList; } -void DEntity::SelectBrushes(bool *selectList) -{ - if(selectList == NULL) +void DEntity::SelectBrushes( bool *selectList ){ + if ( selectList == NULL ) { return; + } - GlobalSelectionSystem().setSelectedAll(false); + GlobalSelectionSystem().setSelectedAll( false ); - scene::Path path(NodeReference(GlobalSceneGraph().root())); - path.push(NodeReference(*QER_Entity)); + scene::Path path( NodeReference( GlobalSceneGraph().root() ) ); + path.push( NodeReference( *QER_Entity ) ); - for(std::list::const_iterator pBrush=brushList.begin(); pBrush!=brushList.end(); pBrush++) + for ( std::list::const_iterator pBrush = brushList.begin(); pBrush != brushList.end(); pBrush++ ) { - if(selectList[(*pBrush)->m_nBrushID]) - { - path.push(NodeReference(*(*pBrush)->QER_brush)); - Instance_getSelectable(*GlobalSceneGraph().find(path))->setSelected(true); - path.pop(); - } + if ( selectList[( *pBrush )->m_nBrushID] ) { + path.push( NodeReference( *( *pBrush )->QER_brush ) ); + Instance_getSelectable( *GlobalSceneGraph().find( path ) )->setSelected( true ); + path.pop(); + } } } -bool DEntity::LoadFromEntity(scene::Node& ent, bool bLoadPatches) { +bool DEntity::LoadFromEntity( scene::Node& ent, bool bLoadPatches ) { ClearPatches(); ClearBrushes(); ClearEPairs(); QER_Entity = &ent; - LoadEPairList(Node_getEntity(ent)); + LoadEPairList( Node_getEntity( ent ) ); bool keep = false; int i; - for(i = 0; brushEntityList[i]; i++) + for ( i = 0; brushEntityList[i]; i++ ) { - if(string_equal_nocase(brushEntityList[i], m_Classname)) - { + if ( string_equal_nocase( brushEntityList[i], m_Classname ) ) { keep = true; break; } } - if(!keep) + if ( !keep ) { return false; + } + + if ( Node_getTraversable( ent ) ) { + class load_brushes_t : public scene::Traversable::Walker + { + DEntity* m_entity; + mutable int m_count; +public: + load_brushes_t( DEntity* entity ) + : m_entity( entity ), m_count( 0 ){ + } + bool pre( scene::Node& node ) const { + scene::Path path( NodeReference( GlobalSceneGraph().root() ) ); + path.push( NodeReference( *m_entity->QER_Entity ) ); + path.push( NodeReference( node ) ); + scene::Instance* instance = GlobalSceneGraph().find( path ); + ASSERT_MESSAGE( instance != 0, "" ); + + if ( Node_isPatch( node ) ) { + DPatch* loadPatch = m_entity->NewPatch(); + loadPatch->LoadFromPatch( *instance ); + } + else if ( Node_isBrush( node ) ) { + DBrush* loadBrush = m_entity->NewBrush( m_count++ ); + loadBrush->LoadFromBrush( *instance, true ); + } + return false; + } + } load_brushes( this ); - if(Node_getTraversable(ent)) - { - class load_brushes_t : public scene::Traversable::Walker - { - DEntity* m_entity; - mutable int m_count; - public: - load_brushes_t(DEntity* entity) - : m_entity(entity), m_count(0) - { - } - bool pre(scene::Node& node) const - { - scene::Path path(NodeReference(GlobalSceneGraph().root())); - path.push(NodeReference(*m_entity->QER_Entity)); - path.push(NodeReference(node)); - scene::Instance* instance = GlobalSceneGraph().find(path); - ASSERT_MESSAGE(instance != 0, ""); - - if(Node_isPatch(node)) - { - DPatch* loadPatch = m_entity->NewPatch(); - loadPatch->LoadFromPatch(*instance); - } - else if(Node_isBrush(node)) - { - DBrush* loadBrush = m_entity->NewBrush(m_count++); - loadBrush->LoadFromBrush(*instance, true); - } - return false; - } - } load_brushes(this); - - Node_getTraversable(ent)->traverse(load_brushes); - } + Node_getTraversable( ent )->traverse( load_brushes ); + } return true; } -void DEntity::RemoveNonCheckBrushes(std::list* exclusionList, bool useDetail) -{ - std::list::iterator chkBrush=brushList.begin(); +void DEntity::RemoveNonCheckBrushes( std::list* exclusionList, bool useDetail ){ + std::list::iterator chkBrush = brushList.begin(); - while( chkBrush!=brushList.end() ) + while ( chkBrush != brushList.end() ) { - if(!useDetail) - { - if((*chkBrush)->IsDetail()) - { + if ( !useDetail ) { + if ( ( *chkBrush )->IsDetail() ) { delete *chkBrush; - chkBrush = brushList.erase(chkBrush); + chkBrush = brushList.erase( chkBrush ); continue; } } std::list::iterator eTexture; - for( eTexture=exclusionList->begin(); eTexture!=exclusionList->end(); eTexture++ ) + for ( eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++ ) { - if((*chkBrush)->HasTexture((*eTexture).GetBuffer())) - { + if ( ( *chkBrush )->HasTexture( ( *eTexture ).GetBuffer() ) ) { delete *chkBrush; - chkBrush = brushList.erase(chkBrush); + chkBrush = brushList.erase( chkBrush ); break; } } - if( eTexture == exclusionList->end() ) + if ( eTexture == exclusionList->end() ) { chkBrush++; + } } } -void DEntity::ResetChecks(std::list* exclusionList) -{ - for(std::list::const_iterator resetBrush=brushList.begin(); resetBrush!=brushList.end(); resetBrush++) +void DEntity::ResetChecks( std::list* exclusionList ){ + for ( std::list::const_iterator resetBrush = brushList.begin(); resetBrush != brushList.end(); resetBrush++ ) { - (*resetBrush)->ResetChecks(exclusionList); + ( *resetBrush )->ResetChecks( exclusionList ); } } -int DEntity::FixBrushes() -{ +int DEntity::FixBrushes(){ int count = 0; - for(std::list::const_iterator fixBrush=brushList.begin(); fixBrush!=brushList.end(); fixBrush++) + for ( std::list::const_iterator fixBrush = brushList.begin(); fixBrush != brushList.end(); fixBrush++ ) { - count += (*fixBrush)->RemoveRedundantPlanes(); + count += ( *fixBrush )->RemoveRedundantPlanes(); } return count; } -void DEntity::BuildInRadiant(bool allowDestruction) -{ - bool makeEntity = strcmp(m_Classname, "worldspawn") ? true : false; +void DEntity::BuildInRadiant( bool allowDestruction ){ + bool makeEntity = strcmp( m_Classname, "worldspawn" ) ? true : false; - if(makeEntity) - { - NodeSmartReference node(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert(m_Classname.GetBuffer(), !brushList.empty() || !patchList.empty()))); + if ( makeEntity ) { + NodeSmartReference node( GlobalEntityCreator().createEntity( GlobalEntityClassManager().findOrInsert( m_Classname.GetBuffer(), !brushList.empty() || !patchList.empty() ) ) ); - for(std::list::const_iterator buildEPair=epairList.begin(); buildEPair!=epairList.end(); buildEPair++) + for ( std::list::const_iterator buildEPair = epairList.begin(); buildEPair != epairList.end(); buildEPair++ ) { - Node_getEntity(node)->setKeyValue((*buildEPair)->key, (*buildEPair)->value); + Node_getEntity( node )->setKeyValue( ( *buildEPair )->key, ( *buildEPair )->value ); } - Node_getTraversable(GlobalSceneGraph().root())->insert(node); + Node_getTraversable( GlobalSceneGraph().root() )->insert( node ); - for(std::list::const_iterator buildBrush=brushList.begin(); buildBrush!=brushList.end(); buildBrush++) - (*buildBrush)->BuildInRadiant(allowDestruction, NULL, node.get_pointer()); + for ( std::list::const_iterator buildBrush = brushList.begin(); buildBrush != brushList.end(); buildBrush++ ) + ( *buildBrush )->BuildInRadiant( allowDestruction, NULL, node.get_pointer() ); - for(std::list::const_iterator buildPatch=patchList.begin(); buildPatch!=patchList.end(); buildPatch++) - (*buildPatch)->BuildInRadiant(node.get_pointer()); + for ( std::list::const_iterator buildPatch = patchList.begin(); buildPatch != patchList.end(); buildPatch++ ) + ( *buildPatch )->BuildInRadiant( node.get_pointer() ); QER_Entity = node.get_pointer(); } else { - for(std::list::const_iterator buildBrush=brushList.begin(); buildBrush!=brushList.end(); buildBrush++) - (*buildBrush)->BuildInRadiant(allowDestruction, NULL); + for ( std::list::const_iterator buildBrush = brushList.begin(); buildBrush != brushList.end(); buildBrush++ ) + ( *buildBrush )->BuildInRadiant( allowDestruction, NULL ); - for(std::list::const_iterator buildPatch=patchList.begin(); buildPatch!=patchList.end(); buildPatch++) - (*buildPatch)->BuildInRadiant(); + for ( std::list::const_iterator buildPatch = patchList.begin(); buildPatch != patchList.end(); buildPatch++ ) + ( *buildPatch )->BuildInRadiant(); } } @@ -527,188 +493,180 @@ void DEntity::BuildInRadiant(bool allowDestruction) int DEntity::GetIDMax( void ) { int max = -1; - for(std::list::const_iterator cntBrush=brushList.begin(); cntBrush!=brushList.end(); cntBrush++) { - if((*cntBrush)->m_nBrushID > max) - max = (*cntBrush)->m_nBrushID; + for ( std::list::const_iterator cntBrush = brushList.begin(); cntBrush != brushList.end(); cntBrush++ ) { + if ( ( *cntBrush )->m_nBrushID > max ) { + max = ( *cntBrush )->m_nBrushID; + } } - return max+1; + return max + 1; } void DEntity::SetClassname( const char *classname ) { m_Classname = classname; } -void DEntity::SaveToFile(FILE *pFile) -{ - fprintf(pFile, "{\n"); +void DEntity::SaveToFile( FILE *pFile ){ + fprintf( pFile, "{\n" ); - fprintf(pFile, "\"classname\" \"%s\"\n", (const char *)m_Classname); + fprintf( pFile, "\"classname\" \"%s\"\n", (const char *)m_Classname ); - for(std::list::const_iterator ep=epairList.begin(); ep!=epairList.end(); ep++) + for ( std::list::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++ ) { - fprintf(pFile, "\"%s\" \"%s\"\n", (const char *)(*ep)->key, (const char *)(*ep)->value); + fprintf( pFile, "\"%s\" \"%s\"\n", (const char *)( *ep )->key, (const char *)( *ep )->value ); } - for(std::list::const_iterator bp=brushList.begin(); bp!=brushList.end(); bp++) + for ( std::list::const_iterator bp = brushList.begin(); bp != brushList.end(); bp++ ) { - (*bp)->SaveToFile(pFile); + ( *bp )->SaveToFile( pFile ); } - fprintf(pFile, "}\n"); + fprintf( pFile, "}\n" ); } -void DEntity::ClearEPairs() -{ - for(std::list::const_iterator deadEPair=epairList.begin(); deadEPair!=epairList.end(); deadEPair++) +void DEntity::ClearEPairs(){ + for ( std::list::const_iterator deadEPair = epairList.begin(); deadEPair != epairList.end(); deadEPair++ ) { - delete (*deadEPair); + delete ( *deadEPair ); } epairList.clear(); } -void DEntity::AddEPair(const char *key, const char *value) { - DEPair* newEPair; +void DEntity::AddEPair( const char *key, const char *value ) { + DEPair* newEPair; newEPair = FindEPairByKey( key ); - if(!newEPair) { + if ( !newEPair ) { newEPair = new DEPair; - newEPair->Build(key, value); - epairList.push_back(newEPair); - } else { - newEPair->Build(key, value); + newEPair->Build( key, value ); + epairList.push_back( newEPair ); + } + else { + newEPair->Build( key, value ); } } -void DEntity::LoadEPairList(Entity *epl) -{ - class load_epairs_t : public Entity::Visitor - { - DEntity* m_entity; - public: - load_epairs_t(DEntity* entity) - : m_entity(entity) - { - } - void visit(const char* key, const char* value) - { - if(strcmp(key, "classname") == 0) - m_entity->SetClassname(value); - else - m_entity->AddEPair(key, value); - } - - } load_epairs(this); - - epl->forEachKeyValue(load_epairs); -} - -bool DEntity::ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild) -{ +void DEntity::LoadEPairList( Entity *epl ){ + class load_epairs_t : public Entity::Visitor + { + DEntity* m_entity; +public: + load_epairs_t( DEntity* entity ) + : m_entity( entity ){ + } + void visit( const char* key, const char* value ){ + if ( strcmp( key, "classname" ) == 0 ) { + m_entity->SetClassname( value ); + } + else{ + m_entity->AddEPair( key, value ); + } + } + + } load_epairs( this ); + + epl->forEachKeyValue( load_epairs ); +} + +bool DEntity::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ){ bool reset = false; - for(std::list::const_iterator resetBrush=brushList.begin(); resetBrush!=brushList.end(); resetBrush++) + for ( std::list::const_iterator resetBrush = brushList.begin(); resetBrush != brushList.end(); resetBrush++ ) { - bool tmp = (*resetBrush)->ResetTextures(textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation); + bool tmp = ( *resetBrush )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, + bResetTextureName, bResetScale, bResetShift, bResetRotation ); - if(tmp) - { + if ( tmp ) { reset = true; - if(rebuild) - { - Node_getTraversable(*(*resetBrush)->QER_entity)->erase(*(*resetBrush)->QER_brush); - (*resetBrush)->BuildInRadiant(false, NULL, (*resetBrush)->QER_entity); + if ( rebuild ) { + Node_getTraversable( *( *resetBrush )->QER_entity )->erase( *( *resetBrush )->QER_brush ); + ( *resetBrush )->BuildInRadiant( false, NULL, ( *resetBrush )->QER_entity ); } } } - if(bResetTextureName) - { - for(std::list::const_iterator resetPatch=patchList.begin(); resetPatch!=patchList.end(); resetPatch++) - { - bool tmp = (*resetPatch)->ResetTextures(textureName, newTextureName); - - if(tmp) - { - reset = true; - if(rebuild) - { - Node_getTraversable(*(*resetPatch)->QER_entity)->erase(*(*resetPatch)->QER_brush); - (*resetPatch)->BuildInRadiant((*resetPatch)->QER_entity); - } - } - } - } + if ( bResetTextureName ) { + for ( std::list::const_iterator resetPatch = patchList.begin(); resetPatch != patchList.end(); resetPatch++ ) + { + bool tmp = ( *resetPatch )->ResetTextures( textureName, newTextureName ); + + if ( tmp ) { + reset = true; + if ( rebuild ) { + Node_getTraversable( *( *resetPatch )->QER_entity )->erase( *( *resetPatch )->QER_brush ); + ( *resetPatch )->BuildInRadiant( ( *resetPatch )->QER_entity ); + } + } + } + } return reset; } -DEPair* DEntity::FindEPairByKey(const char* keyname) -{ - for(std::list::const_iterator ep=epairList.begin(); ep!=epairList.end(); ep++) +DEPair* DEntity::FindEPairByKey( const char* keyname ){ + for ( std::list::const_iterator ep = epairList.begin(); ep != epairList.end(); ep++ ) { - char* c = (*ep)->key; - if(!strcmp(c, keyname)) + char* c = ( *ep )->key; + if ( !strcmp( c, keyname ) ) { return *ep; + } } return NULL; } -void DEntity::RemoveFromRadiant() -{ - Node_getTraversable(GlobalSceneGraph().root())->erase(*QER_Entity); +void DEntity::RemoveFromRadiant(){ + Node_getTraversable( GlobalSceneGraph().root() )->erase( *QER_Entity ); QER_Entity = NULL; } -void DEntity::SpawnString(const char* key, const char* defaultstring, const char** out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { +void DEntity::SpawnString( const char* key, const char* defaultstring, const char** out ){ + DEPair* pEP = FindEPairByKey( key ); + if ( pEP ) { *out = pEP->value; - } else { + } + else { *out = defaultstring; } } -void DEntity::SpawnInt(const char* key, const char* defaultstring, int* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - *out = atoi(pEP->value); - } else { - *out = atoi(defaultstring); +void DEntity::SpawnInt( const char* key, const char* defaultstring, int* out ){ + DEPair* pEP = FindEPairByKey( key ); + if ( pEP ) { + *out = atoi( pEP->value ); + } + else { + *out = atoi( defaultstring ); } } -void DEntity::SpawnFloat(const char* key, const char* defaultstring, float* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - *out = static_cast(atof(pEP->value)); - } else { - *out = static_cast(atof(defaultstring)); +void DEntity::SpawnFloat( const char* key, const char* defaultstring, float* out ){ + DEPair* pEP = FindEPairByKey( key ); + if ( pEP ) { + *out = static_cast( atof( pEP->value ) ); + } + else { + *out = static_cast( atof( defaultstring ) ); } } -void DEntity::SpawnVector(const char* key, const char* defaultstring, vec_t* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - sscanf(pEP->value, "%f %f %f", &out[0], &out[1], &out[2]); - } else { - sscanf(defaultstring, "%f %f %f", &out[0], &out[1], &out[2]); +void DEntity::SpawnVector( const char* key, const char* defaultstring, vec_t* out ){ + DEPair* pEP = FindEPairByKey( key ); + if ( pEP ) { + sscanf( pEP->value, "%f %f %f", &out[0], &out[1], &out[2] ); + } + else { + sscanf( defaultstring, "%f %f %f", &out[0], &out[1], &out[2] ); } } int DEntity::GetBrushCount( void ) { - return static_cast(brushList.size()); + return static_cast( brushList.size() ); } DBrush* DEntity::FindBrushByPointer( scene::Node& brush ) { - for(std::list::const_iterator listBrush = brushList.begin(); listBrush != brushList.end(); listBrush++) { - DBrush* pBrush = (*listBrush); - if(pBrush->QER_brush == &brush) { + for ( std::list::const_iterator listBrush = brushList.begin(); listBrush != brushList.end(); listBrush++ ) { + DBrush* pBrush = ( *listBrush ); + if ( pBrush->QER_brush == &brush ) { return pBrush; } } diff --git a/contrib/bobtoolz/DEntity.h b/contrib/bobtoolz/DEntity.h index 5baa3d3d..415442a2 100644 --- a/contrib/bobtoolz/DEntity.h +++ b/contrib/bobtoolz/DEntity.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DEntity.h: interface for the DEntity class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -40,86 +40,86 @@ class Entity; namespace scene { - class Node; +class Node; } class _QERFaceData; -class DEntity +class DEntity { public: - void RemoveFromRadiant(); - scene::Node* QER_Entity; - int m_nID; +void RemoveFromRadiant(); +scene::Node* QER_Entity; +int m_nID; // Constrcution/Destruction - DEntity(const char* classname = "worldspawn", int ID = -1); // sets classname - virtual ~DEntity(); +DEntity( const char* classname = "worldspawn", int ID = -1 ); // sets classname +virtual ~DEntity(); // --------------------------------------------- // epair functions........ - void LoadEPairList(Entity* epl); - void AddEPair(const char* key, const char* value); - void ClearEPairs(); - DEPair* FindEPairByKey(const char* keyname); +void LoadEPairList( Entity* epl ); +void AddEPair( const char* key, const char* value ); +void ClearEPairs(); +DEPair* FindEPairByKey( const char* keyname ); // --------------------------------------------- // random functions........ - bool ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild); - void SaveToFile(FILE* pFile); - void SetClassname(const char* classname); - int GetIDMax(); - - void BuildInRadiant(bool allowDestruction); - void ResetChecks(std::list* exclusionList); - void RemoveNonCheckBrushes(std::list* exclusionList, bool useDetail); - - DPlane* AddFaceToBrush(vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID); // slow, try not to use much - int GetBrushCount( void ); - DBrush* FindBrushByPointer( scene::Node& brush ); +bool ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild ); +void SaveToFile( FILE* pFile ); +void SetClassname( const char* classname ); +int GetIDMax(); + +void BuildInRadiant( bool allowDestruction ); +void ResetChecks( std::list* exclusionList ); +void RemoveNonCheckBrushes( std::list* exclusionList, bool useDetail ); + +DPlane* AddFaceToBrush( vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID ); // slow, try not to use much +int GetBrushCount( void ); +DBrush* FindBrushByPointer( scene::Node& brush ); // --------------------------------------------- // bool list functions - void SelectBrushes(bool* selectList); - bool* BuildDuplicateList(); - bool* BuildIntersectList(); +void SelectBrushes( bool* selectList ); +bool* BuildDuplicateList(); +bool* BuildIntersectList(); // --------------------------------------------- - + // brush operations - void ClearBrushes(); // clears brush list and frees memory for brushes +void ClearBrushes(); // clears brush list and frees memory for brushes - DBrush* GetBrushForID(int ID); - DBrush* NewBrush(int ID = -1); +DBrush* GetBrushForID( int ID ); +DBrush* NewBrush( int ID = -1 ); // --------------------------------------------- // patch operations - void ClearPatches(); +void ClearPatches(); - DPatch* NewPatch(); +DPatch* NewPatch(); // --------------------------------------------- // vars - std::list epairList; - std::list brushList; - // new patches, wahey!!! - std::list patchList; - Str m_Classname; +std::list epairList; +std::list brushList; +// new patches, wahey!!! +std::list patchList; +Str m_Classname; // --------------------------------------------- - int FixBrushes(); +int FixBrushes(); - bool LoadFromEntity(scene::Node& ent, bool bLoadPatches = false); - void LoadSelectedBrushes(); - void LoadSelectedPatches(); +bool LoadFromEntity( scene::Node& ent, bool bLoadPatches = false ); +void LoadSelectedBrushes(); +void LoadSelectedPatches(); - bool LoadFromPrt(char* filename); +bool LoadFromPrt( char* filename ); // --------------------------------------------- - void SpawnString(const char* key, const char* defaultstring, const char** out); - void SpawnInt(const char* key, const char* defaultstring, int* out); - void SpawnFloat(const char* key, const char* defaultstring, float* out); - void SpawnVector(const char* key, const char* defaultstring, vec_t* out); +void SpawnString( const char* key, const char* defaultstring, const char** out ); +void SpawnInt( const char* key, const char* defaultstring, int* out ); +void SpawnFloat( const char* key, const char* defaultstring, float* out ); +void SpawnVector( const char* key, const char* defaultstring, vec_t* out ); }; #endif // !defined(AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/DMap.cpp b/contrib/bobtoolz/DMap.cpp index 18e43188..72356946 100644 --- a/contrib/bobtoolz/DMap.cpp +++ b/contrib/bobtoolz/DMap.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DMap.cpp: implementation of the DMap class. // @@ -49,130 +49,120 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DMap::DMap() -{ +DMap::DMap(){ m_nNextEntity = 1; - AddEntity("worldspawn", 0); + AddEntity( "worldspawn", 0 ); } -DMap::~DMap() -{ +DMap::~DMap(){ ClearEntities(); } -DEntity* DMap::AddEntity(char *classname, int ID) -{ +DEntity* DMap::AddEntity( char *classname, int ID ){ DEntity* newEntity; - if(ID == -1) - newEntity = new DEntity(classname, m_nNextEntity++); - else - newEntity = new DEntity(classname, ID); + if ( ID == -1 ) { + newEntity = new DEntity( classname, m_nNextEntity++ ); + } + else{ + newEntity = new DEntity( classname, ID ); + } + + entityList.push_back( newEntity ); - entityList.push_back(newEntity); - return newEntity; } -void DMap::ClearEntities() -{ +void DMap::ClearEntities(){ m_nNextEntity = 1; - for(std::list::const_iterator deadEntity=entityList.begin(); deadEntity!=entityList.end(); deadEntity++) + for ( std::list::const_iterator deadEntity = entityList.begin(); deadEntity != entityList.end(); deadEntity++ ) delete *deadEntity; entityList.clear(); } -DEntity* DMap::GetEntityForID(int ID) -{ +DEntity* DMap::GetEntityForID( int ID ){ DEntity* findEntity = NULL; - for(std::list::const_iterator chkEntity=entityList.begin(); chkEntity!=entityList.end(); chkEntity++) + for ( std::list::const_iterator chkEntity = entityList.begin(); chkEntity != entityList.end(); chkEntity++ ) { - if((*chkEntity)->m_nID == ID) - { - findEntity = (*chkEntity); + if ( ( *chkEntity )->m_nID == ID ) { + findEntity = ( *chkEntity ); break; } } - if(!findEntity) - findEntity = AddEntity("worldspawn", ID); + if ( !findEntity ) { + findEntity = AddEntity( "worldspawn", ID ); + } return findEntity; } -DEntity* DMap::GetWorldSpawn() -{ - return GetEntityForID(0); +DEntity* DMap::GetWorldSpawn(){ + return GetEntityForID( 0 ); } -void DMap::BuildInRadiant(bool bAllowDestruction) -{ - for(std::list::const_iterator buildEntity=entityList.begin(); buildEntity!=entityList.end(); buildEntity++) - (*buildEntity)->BuildInRadiant(bAllowDestruction); +void DMap::BuildInRadiant( bool bAllowDestruction ){ + for ( std::list::const_iterator buildEntity = entityList.begin(); buildEntity != entityList.end(); buildEntity++ ) + ( *buildEntity )->BuildInRadiant( bAllowDestruction ); } -void DMap::LoadAll(bool bLoadPatches) -{ +void DMap::LoadAll( bool bLoadPatches ){ ClearEntities(); - GlobalSelectionSystem().setSelectedAll(false); - - class load_entities_t : public scene::Traversable::Walker - { - DMap* m_map; - bool m_bLoadPatches; - public: - load_entities_t(DMap* map, bool bLoadPatches) - : m_map(map), m_bLoadPatches(bLoadPatches) - { - } - bool pre(scene::Node& node) const - { - if(Node_isEntity(node)) - { - DEntity* loadEntity = m_map->AddEntity("", 0); - loadEntity->LoadFromEntity(node, m_bLoadPatches); - } - return false; - } - } load_entities(this, bLoadPatches); - - Node_getTraversable(GlobalSceneGraph().root())->traverse(load_entities); + GlobalSelectionSystem().setSelectedAll( false ); + + class load_entities_t : public scene::Traversable::Walker + { + DMap* m_map; + bool m_bLoadPatches; +public: + load_entities_t( DMap* map, bool bLoadPatches ) + : m_map( map ), m_bLoadPatches( bLoadPatches ){ + } + bool pre( scene::Node& node ) const { + if ( Node_isEntity( node ) ) { + DEntity* loadEntity = m_map->AddEntity( "", 0 ); + loadEntity->LoadFromEntity( node, m_bLoadPatches ); + } + return false; + } + } load_entities( this, bLoadPatches ); + + Node_getTraversable( GlobalSceneGraph().root() )->traverse( load_entities ); } -int DMap::FixBrushes() -{ +int DMap::FixBrushes(){ int count = 0; - for(std::list::const_iterator fixEntity=entityList.begin(); fixEntity!=entityList.end(); fixEntity++) + for ( std::list::const_iterator fixEntity = entityList.begin(); fixEntity != entityList.end(); fixEntity++ ) { - count += (*fixEntity)->FixBrushes(); + count += ( *fixEntity )->FixBrushes(); } return count; } -void DMap::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation) -{ - for(std::list::const_iterator texEntity=entityList.begin(); texEntity!=entityList.end(); texEntity++) +void DMap::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, + int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ){ + for ( std::list::const_iterator texEntity = entityList.begin(); texEntity != entityList.end(); texEntity++ ) { - if(string_equal_nocase("worldspawn", (*texEntity)->m_Classname)) - (*texEntity)->ResetTextures(textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, true); + if ( string_equal_nocase( "worldspawn", ( *texEntity )->m_Classname ) ) { + ( *texEntity )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, + bResetTextureName, bResetScale, bResetShift, bResetRotation, true ); + } else { - if((*texEntity)->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, false)) - RebuildEntity(*texEntity); + if ( ( *texEntity )->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, + bResetTextureName, bResetScale, bResetShift, bResetRotation, false ) ) { + RebuildEntity( *texEntity ); + } } - } + } } -void DMap::RebuildEntity(DEntity *ent) -{ +void DMap::RebuildEntity( DEntity *ent ){ ent->RemoveFromRadiant(); - ent->BuildInRadiant(false); + ent->BuildInRadiant( false ); } diff --git a/contrib/bobtoolz/DMap.h b/contrib/bobtoolz/DMap.h index 018dbc0f..b4a3f79b 100644 --- a/contrib/bobtoolz/DMap.h +++ b/contrib/bobtoolz/DMap.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DMap.h: interface for the DMap class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_) +#if !defined( AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_ ) #define AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_ #if _MSC_VER > 1000 @@ -32,27 +32,27 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class DEntity; -class DMap +class DMap { public: - static void RebuildEntity(DEntity* ent); +static void RebuildEntity( DEntity* ent ); - void ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation); - void LoadAll(bool bLoadPatches = false); - void BuildInRadiant(bool bAllowDestruction); - int m_nNextEntity; - DEntity* GetWorldSpawn(); - void ClearEntities(); +void ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation ); +void LoadAll( bool bLoadPatches = false ); +void BuildInRadiant( bool bAllowDestruction ); +int m_nNextEntity; +DEntity* GetWorldSpawn(); +void ClearEntities(); - DEntity* GetEntityForID(int ID); - DEntity* AddEntity(char* classname = "worldspawn", int ID = -1); +DEntity* GetEntityForID( int ID ); +DEntity* AddEntity( char* classname = "worldspawn", int ID = -1 ); - std::list entityList; +std::list entityList; - DMap(); - virtual ~DMap(); +DMap(); +virtual ~DMap(); - int FixBrushes(); +int FixBrushes(); }; #endif // !defined(AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_) diff --git a/contrib/bobtoolz/DPatch.cpp b/contrib/bobtoolz/DPatch.cpp index 85a95cb0..2228b23b 100644 --- a/contrib/bobtoolz/DPatch.cpp +++ b/contrib/bobtoolz/DPatch.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPatch.cpp: implementation of the DPatch class. // @@ -42,195 +42,189 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // problem is, you cant put patches into entities as yet :( // -DPatch::DPatch() -{ +DPatch::DPatch(){ width = MIN_PATCH_WIDTH; height = MIN_PATCH_HEIGHT; QER_entity = NULL; QER_brush = NULL; } -DPatch::~DPatch() -{ +DPatch::~DPatch(){ } -void DPatch::SetTexture(const char *textureName) -{ - strcpy(texture, textureName); +void DPatch::SetTexture( const char *textureName ){ + strcpy( texture, textureName ); } -void CopyDrawVert(const drawVert_t* in, drawVert_t* out) -{ +void CopyDrawVert( const drawVert_t* in, drawVert_t* out ){ out->lightmap[0] = in->lightmap[0]; out->lightmap[1] = in->lightmap[1]; out->st[0] = in->st[0]; out->st[1] = in->st[1]; - VectorCopy(in->normal, out->normal); - VectorCopy(in->xyz, out->xyz); + VectorCopy( in->normal, out->normal ); + VectorCopy( in->xyz, out->xyz ); } -void DPatch::BuildInRadiant(scene::Node* entity) -{ - NodeSmartReference patch(GlobalPatchCreator().createPatch()); +void DPatch::BuildInRadiant( scene::Node* entity ){ + NodeSmartReference patch( GlobalPatchCreator().createPatch() ); - scene::Node& parent = entity != 0 ? *entity : GlobalRadiant().getMapWorldEntity(); - Node_getTraversable(parent)->insert(patch); + scene::Node& parent = entity != 0 ? *entity : GlobalRadiant().getMapWorldEntity(); + Node_getTraversable( parent )->insert( patch ); - GlobalPatchCreator().Patch_setShader(patch, texture); - GlobalPatchCreator().Patch_resize(patch, height, width); - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch); - for(int x = 0; x < width; x++) - { - for(int y = 0; y < height; y++) - { - PatchControl& p = matrix(x, y); - p.m_vertex[0] = points[x][y].xyz[0]; - p.m_vertex[1] = points[x][y].xyz[1]; - p.m_vertex[2] = points[x][y].xyz[2]; - p.m_texcoord[0] = points[x][y].st[0]; - p.m_texcoord[1] = points[x][y].st[1]; - } - } - GlobalPatchCreator().Patch_controlPointsChanged(patch); - - QER_entity = entity; + GlobalPatchCreator().Patch_setShader( patch, texture ); + GlobalPatchCreator().Patch_resize( patch, height, width ); + PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints( patch ); + for ( int x = 0; x < width; x++ ) + { + for ( int y = 0; y < height; y++ ) + { + PatchControl& p = matrix( x, y ); + p.m_vertex[0] = points[x][y].xyz[0]; + p.m_vertex[1] = points[x][y].xyz[1]; + p.m_vertex[2] = points[x][y].xyz[2]; + p.m_texcoord[0] = points[x][y].st[0]; + p.m_texcoord[1] = points[x][y].st[1]; + } + } + GlobalPatchCreator().Patch_controlPointsChanged( patch ); + + QER_entity = entity; QER_brush = patch.get_pointer(); #if 0 int nIndex = g_FuncTable.m_pfnCreatePatchHandle(); - //$ FIXME: m_pfnGetPatchHandle - patchMesh_t* pm = g_FuncTable.m_pfnGetPatchData(nIndex); + //$ FIXME: m_pfnGetPatchHandle + patchMesh_t* pm = g_FuncTable.m_pfnGetPatchData( nIndex ); - b->patchBrush = true; - b->pPatch = Patch_Alloc(); - b->pPatch->setDims(width,height); + b->patchBrush = true; + b->pPatch = Patch_Alloc(); + b->pPatch->setDims( width,height ); - for(int x = 0; x < width; x++) - for(int y = 0; y < height; y++) - CopyDrawVert(&points[x][y], &pm->ctrl[x][y]); + for ( int x = 0; x < width; x++ ) + for ( int y = 0; y < height; y++ ) + CopyDrawVert( &points[x][y], &pm->ctrl[x][y] ); /* if(entity) - { -// strcpy(pm->d_texture->name, texture); + { + // strcpy(pm->d_texture->name, texture); - brush_t* brush = (brush_t*)g_FuncTable.m_pfnCreateBrushHandle(); - brush->patchBrush = true; - brush->pPatch = pm; + brush_t* brush = (brush_t*)g_FuncTable.m_pfnCreateBrushHandle(); + brush->patchBrush = true; + brush->pPatch = pm; - pm->pSymbiot = brush; - pm->bSelected = false; - pm->bOverlay = false; // bleh, f*cks up, just have to wait for a proper function - pm->bDirty = true; // or get my own patch out.... - pm->nListID = -1; + pm->pSymbiot = brush; + pm->bSelected = false; + pm->bOverlay = false; // bleh, f*cks up, just have to wait for a proper function + pm->bDirty = true; // or get my own patch out.... + pm->nListID = -1; - g_FuncTable.m_pfnCommitBrushHandleToEntity(brush, entity); - } - else*/ // patch to entity just plain dont work atm + g_FuncTable.m_pfnCommitBrushHandleToEntity(brush, entity); + } + else*/ // patch to entity just plain dont work atm - if(entity) - g_FuncTable.m_pfnCommitPatchHandleToEntity(nIndex, pm, texture, entity); - else - g_FuncTable.m_pfnCommitPatchHandleToMap(nIndex, pm, texture); + if ( entity ) { + g_FuncTable.m_pfnCommitPatchHandleToEntity( nIndex, pm, texture, entity ); + } + else{ + g_FuncTable.m_pfnCommitPatchHandleToMap( nIndex, pm, texture ); + } QER_brush = pm->pSymbiot; #endif } -void DPatch::LoadFromPatch(scene::Instance& patch) -{ - QER_entity = patch.path().parent().get_pointer(); +void DPatch::LoadFromPatch( scene::Instance& patch ){ + QER_entity = patch.path().parent().get_pointer(); QER_brush = patch.path().top().get_pointer(); - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch.path().top()); + PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints( patch.path().top() ); - width = static_cast(matrix.x()); - height = static_cast(matrix.y()); + width = static_cast( matrix.x() ); + height = static_cast( matrix.y() ); - for(int x = 0; x < width; x++) - { - for(int y = 0; y < height; y++) - { - PatchControl& p = matrix(x, y); - points[x][y].xyz[0] = p.m_vertex[0]; - points[x][y].xyz[1] = p.m_vertex[1]; - points[x][y].xyz[2] = p.m_vertex[2]; - points[x][y].st[0] = p.m_texcoord[0]; - points[x][y].st[1] = p.m_texcoord[1]; - } - } - SetTexture(GlobalPatchCreator().Patch_getShader(patch.path().top())); + for ( int x = 0; x < width; x++ ) + { + for ( int y = 0; y < height; y++ ) + { + PatchControl& p = matrix( x, y ); + points[x][y].xyz[0] = p.m_vertex[0]; + points[x][y].xyz[1] = p.m_vertex[1]; + points[x][y].xyz[2] = p.m_vertex[2]; + points[x][y].st[0] = p.m_texcoord[0]; + points[x][y].st[1] = p.m_texcoord[1]; + } + } + SetTexture( GlobalPatchCreator().Patch_getShader( patch.path().top() ) ); #if 0 - SetTexture(brush->pPatch->GetShader()); + SetTexture( brush->pPatch->GetShader() ); width = brush->pPatch->getWidth(); height = brush->pPatch->getHeight(); - for(int x = 0; x < height; x++) - { - for(int y = 0; y < width; y++) - { - float *p = brush->pPatch->ctrlAt(ROW,x,y); - p[0] = points[x][y].xyz[0]; - p[1] = points[x][y].xyz[1]; - p[2] = points[x][y].xyz[2]; - p[3] = points[x][y].st[0]; - p[4] = points[x][y].st[1]; - } - } + for ( int x = 0; x < height; x++ ) + { + for ( int y = 0; y < width; y++ ) + { + float *p = brush->pPatch->ctrlAt( ROW,x,y ); + p[0] = points[x][y].xyz[0]; + p[1] = points[x][y].xyz[1]; + p[2] = points[x][y].xyz[2]; + p[3] = points[x][y].st[0]; + p[4] = points[x][y].st[1]; + } + } #endif } -bool DPatch::ResetTextures(const char *oldTextureName, const char *newTextureName) -{ - if( !oldTextureName || !strcmp(texture, oldTextureName)) - { - strcpy(texture, newTextureName); +bool DPatch::ResetTextures( const char *oldTextureName, const char *newTextureName ){ + if ( !oldTextureName || !strcmp( texture, oldTextureName ) ) { + strcpy( texture, newTextureName ); return true; } return false; } -void Build1dArray(vec3_t* array, drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT], - int startX, int startY, int number, bool horizontal, bool inverse) -{ +void Build1dArray( vec3_t* array, drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT], + int startX, int startY, int number, bool horizontal, bool inverse ){ int x = startX, y = startY, i, step; - if(inverse) + if ( inverse ) { step = -1; - else + } + else{ step = 1; + } - for(i = 0; i < number; i++) + for ( i = 0; i < number; i++ ) { - VectorCopy(points[x][y].xyz, array[i]); + VectorCopy( points[x][y].xyz, array[i] ); - if(horizontal) - x+=step; - else - y+=step; + if ( horizontal ) { + x += step; + } + else{ + y += step; + } } } -void Print1dArray(vec3_t* array, int size) -{ - for(int i = 0; i < size; i++) +void Print1dArray( vec3_t* array, int size ){ + for ( int i = 0; i < size; i++ ) globalOutputStream() << "(" << array[i][0] << " " << array[i][1] << " " << array[i][2] << ")\t"; globalOutputStream() << "\n"; } -bool Compare1dArrays(vec3_t* a1, vec3_t* a2, int size) -{ +bool Compare1dArrays( vec3_t* a1, vec3_t* a2, int size ){ int i; bool equal = true; - for(i = 0; i < size; i++) + for ( i = 0; i < size; i++ ) { - if(!VectorCompare(a1[i], a2[size-i-1])) - { + if ( !VectorCompare( a1[i], a2[size - i - 1] ) ) { equal = false; break; } @@ -238,8 +232,7 @@ bool Compare1dArrays(vec3_t* a1, vec3_t* a2, int size) return equal; } -patch_merge_t DPatch::IsMergable(DPatch *other) -{ +patch_merge_t DPatch::IsMergable( DPatch *other ){ int i, j; vec3_t p1Array[4][MAX_PATCH_HEIGHT]; vec3_t p2Array[4][MAX_PATCH_HEIGHT]; @@ -249,15 +242,15 @@ patch_merge_t DPatch::IsMergable(DPatch *other) patch_merge_t merge_info; - Build1dArray(p1Array[0], this->points, 0, 0, this->width, true, false); - Build1dArray(p1Array[1], this->points, this->width-1, 0, this->height, false, false); - Build1dArray(p1Array[2], this->points, this->width-1, this->height-1, this->width, true, true); - Build1dArray(p1Array[3], this->points, 0, this->height-1, this->height, false, true); + Build1dArray( p1Array[0], this->points, 0, 0, this->width, true, false ); + Build1dArray( p1Array[1], this->points, this->width - 1, 0, this->height, false, false ); + Build1dArray( p1Array[2], this->points, this->width - 1, this->height - 1, this->width, true, true ); + Build1dArray( p1Array[3], this->points, 0, this->height - 1, this->height, false, true ); - Build1dArray(p2Array[0], other->points, 0, 0, other->width, true, false); - Build1dArray(p2Array[1], other->points, other->width-1, 0, other->height, false, false); - Build1dArray(p2Array[2], other->points, other->width-1, other->height-1, other->width, true, true); - Build1dArray(p2Array[3], other->points, 0, other->height-1, other->height, false, true); + Build1dArray( p2Array[0], other->points, 0, 0, other->width, true, false ); + Build1dArray( p2Array[1], other->points, other->width - 1, 0, other->height, false, false ); + Build1dArray( p2Array[2], other->points, other->width - 1, other->height - 1, other->width, true, true ); + Build1dArray( p2Array[3], other->points, 0, other->height - 1, other->height, false, true ); p1ArraySizes[0] = this->width; p1ArraySizes[1] = this->height; @@ -269,14 +262,12 @@ patch_merge_t DPatch::IsMergable(DPatch *other) p2ArraySizes[2] = other->width; p2ArraySizes[3] = other->height; - for(i = 0; i < 4; i++) + for ( i = 0; i < 4; i++ ) { - for(j = 0; j < 4; j++) + for ( j = 0; j < 4; j++ ) { - if(p1ArraySizes[i] == p2ArraySizes[j]) - { - if(Compare1dArrays(p1Array[i], p2Array[j], p1ArraySizes[i])) - { + if ( p1ArraySizes[i] == p2ArraySizes[j] ) { + if ( Compare1dArrays( p1Array[i], p2Array[j], p1ArraySizes[i] ) ) { merge_info.pos1 = i; merge_info.pos2 = j; merge_info.mergable = true; @@ -285,145 +276,142 @@ patch_merge_t DPatch::IsMergable(DPatch *other) } } } - + merge_info.mergable = false; return merge_info; } -DPatch* DPatch::MergePatches(patch_merge_t merge_info, DPatch *p1, DPatch *p2) -{ - while(merge_info.pos1 != 2) +DPatch* DPatch::MergePatches( patch_merge_t merge_info, DPatch *p1, DPatch *p2 ){ + while ( merge_info.pos1 != 2 ) { p1->Transpose(); merge_info.pos1--; - if(merge_info.pos1 < 0) + if ( merge_info.pos1 < 0 ) { merge_info.pos1 += 4; + } } - while(merge_info.pos2 != 0) + while ( merge_info.pos2 != 0 ) { p2->Transpose(); merge_info.pos2--; - if(merge_info.pos2 < 0) + if ( merge_info.pos2 < 0 ) { merge_info.pos2 += 3; + } } - int newHeight = p1->height + p2->height - 1; - if(newHeight > MAX_PATCH_HEIGHT) + int newHeight = p1->height + p2->height - 1; + if ( newHeight > MAX_PATCH_HEIGHT ) { return false; + } DPatch* newPatch = new DPatch(); - newPatch->height = newHeight; - newPatch->width = p1->width; - newPatch->SetTexture(p1->texture); + newPatch->height = newHeight; + newPatch->width = p1->width; + newPatch->SetTexture( p1->texture ); - for(int y = 0; y < p1->height; y++) - for(int x = 0; x < p1->width; x++) + for ( int y = 0; y < p1->height; y++ ) + for ( int x = 0; x < p1->width; x++ ) newPatch->points[x][y] = p1->points[x][y]; - - for(int y = 1; y < p2->height; y++) - for(int x = 0; x < p2->width; x++) - newPatch->points[x][(y + p1->height - 1)] = p2->points[x][y]; - + + for ( int y = 1; y < p2->height; y++ ) + for ( int x = 0; x < p2->width; x++ ) + newPatch->points[x][( y + p1->height - 1 )] = p2->points[x][y]; + // newPatch->Invert(); return newPatch; } -void DPatch::Invert() -{ +void DPatch::Invert(){ int i, j; - for(i = 0 ; i < width ; i++ ) + for ( i = 0 ; i < width ; i++ ) { - for(j = 0; j < height / 2; j++) + for ( j = 0; j < height / 2; j++ ) { - std::swap(points[i][height - 1- j], points[i][j]); + std::swap( points[i][height - 1 - j], points[i][j] ); } } } /* -//Was used for debugging, obsolete function -DPatch* DPatch::TransposePatch(DPatch *p1) -{ - globalOutputStream() << "Source patch "; + //Was used for debugging, obsolete function + DPatch* DPatch::TransposePatch(DPatch *p1) + { + globalOutputStream() << "Source patch "; p1->DebugPrint(); p1->Transpose(); globalOutputStream() << "Transposed"; p1->DebugPrint(); - + DPatch* newPatch = new DPatch(); - newPatch->height = p1->height; - newPatch->width = p1->width; - newPatch->SetTexture(p1->texture); - - for(int x = 0; x < p1->height; x++) - { - for(int y = 0; y < p1->width; y++) - { + newPatch->height = p1->height; + newPatch->width = p1->width; + newPatch->SetTexture(p1->texture); + + for(int x = 0; x < p1->height; x++) + { + for(int y = 0; y < p1->width; y++) + { newPatch->points[x][y] = p1->points[x][y]; } } - return newPatch; -} + return newPatch; + } -//Function to figure out what is actually going wrong. -void DPatch::DebugPrint() -{ + //Function to figure out what is actually going wrong. + void DPatch::DebugPrint() + { globalOutputStream() << "width: " << width << "\theight: " << height << "\n"; for(int x = 0; x < height; x++) - { - for(int y = 0; y < width; y++) - { + { + for(int y = 0; y < width; y++) + { globalOutputStream() << "\t(" << points[x][y].xyz[0] << " " << points[x][y].xyz[1] << " " << points[x][y].xyz[2] << ")\t"; } globalOutputStream() << "\n"; } -} + } */ -void DPatch::Transpose() -{ - int i, j, w; +void DPatch::Transpose(){ + int i, j, w; - if ( width > height ) - { - for ( i = 0 ; i < height ; i++ ) + if ( width > height ) { + for ( i = 0 ; i < height ; i++ ) { - for ( j = i + 1 ; j < width ; j++ ) + for ( j = i + 1 ; j < width ; j++ ) { - if ( j < height ) - { + if ( j < height ) { // swap the value - std::swap(points[j][i], points[i][j]); - } - else + std::swap( points[j][i], points[i][j] ); + } + else { - // just copy + // just copy points[i][j] = points[j][i]; - } - } - } - } - else + } + } + } + } + else { - for ( i = 0 ; i < width ; i++ ) - { - for ( j = i + 1 ; j < height ; j++ ) + for ( i = 0 ; i < width ; i++ ) + { + for ( j = i + 1 ; j < height ; j++ ) { - if ( j < width ) - { + if ( j < width ) { // swap the value - std::swap(points[i][j], points[j][i]); - } - else + std::swap( points[i][j], points[j][i] ); + } + else { - // just copy + // just copy points[j][i] = points[i][j]; - } - } - } - } + } + } + } + } w = width; width = height; @@ -432,97 +420,94 @@ void DPatch::Transpose() Invert(); } -std::list DPatch::SplitCols() -{ +std::list DPatch::SplitCols(){ std::list patchList; int i; int x, y; - if(height >= 5) - { - for(i = 0; i < (height-1)/2; i++) + if ( height >= 5 ) { + for ( i = 0; i < ( height - 1 ) / 2; i++ ) { DPatch p; p.width = width; p.height = MIN_PATCH_HEIGHT; - p.SetTexture(texture); - for(x = 0; x < p.width; x++) + p.SetTexture( texture ); + for ( x = 0; x < p.width; x++ ) { - for(y = 0; y < MIN_PATCH_HEIGHT; y++) + for ( y = 0; y < MIN_PATCH_HEIGHT; y++ ) { - p.points[x][y] = points[x][(i*2)+y]; + p.points[x][y] = points[x][( i * 2 ) + y]; } - } - patchList.push_back(p); - } - } else { - //globalErrorStream() << "bobToolz SplitPatchRows: Patch has not enough rows for splitting.\n"; - patchList.push_back(*this); } + patchList.push_back( p ); + } + } + else { + //globalErrorStream() << "bobToolz SplitPatchRows: Patch has not enough rows for splitting.\n"; + patchList.push_back( *this ); + } return patchList; } -std::list DPatch::SplitRows() -{ +std::list DPatch::SplitRows(){ std::list patchList; int i; int x, y; - - if(width >= 5) - { - for(i = 0; i < (width-1)/2; i++) + + if ( width >= 5 ) { + for ( i = 0; i < ( width - 1 ) / 2; i++ ) { DPatch p; - + p.width = MIN_PATCH_WIDTH; p.height = height; - p.SetTexture(texture); - - for(x = 0; x < MIN_PATCH_WIDTH; x++) + p.SetTexture( texture ); + + for ( x = 0; x < MIN_PATCH_WIDTH; x++ ) { - for(y = 0; y < p.height; y++) + for ( y = 0; y < p.height; y++ ) { - p.points[x][y] = points[(i*2)+x][y]; + p.points[x][y] = points[( i * 2 ) + x][y]; } } - patchList.push_back(p); + patchList.push_back( p ); } - } else + } + else { - patchList.push_back(*this); - } + patchList.push_back( *this ); + } return patchList; } -std::list DPatch::Split() -{ +std::list DPatch::Split(){ std::list patchList; int i; int x, y; - - if(width >= 5) - { + + if ( width >= 5 ) { std::list patchColList = SplitCols(); - for(std::list::iterator patchesCol = patchColList.begin(); patchesCol != patchColList.end(); patchesCol++) + for ( std::list::iterator patchesCol = patchColList.begin(); patchesCol != patchColList.end(); patchesCol++ ) { - std::list patchRowList = (*patchesCol).SplitRows(); - for(std::list::iterator patchesRow = patchRowList.begin(); patchesRow != patchRowList.end(); patchesRow++) + std::list patchRowList = ( *patchesCol ).SplitRows(); + for ( std::list::iterator patchesRow = patchRowList.begin(); patchesRow != patchRowList.end(); patchesRow++ ) { - patchList.push_front(*patchesRow); - } + patchList.push_front( *patchesRow ); } - } else if(height >= 5) - { + } + } + else if ( height >= 5 ) { std::list patchRowList = SplitRows(); - for(std::list::iterator patchesRow = patchRowList.begin(); patchesRow != patchRowList.end(); patchesRow++) + for ( std::list::iterator patchesRow = patchRowList.begin(); patchesRow != patchRowList.end(); patchesRow++ ) { - patchList.push_front(*patchesRow); - } - } else + patchList.push_front( *patchesRow ); + } + } + else { - //globalErrorStream() << "bobToolz SplitPatchRows: Patch has not enough rows for splitting.\n"; - patchList.push_back(*this); - } + //globalErrorStream() << "bobToolz SplitPatchRows: Patch has not enough rows for splitting.\n"; + patchList.push_back( *this ); + } return patchList; } diff --git a/contrib/bobtoolz/DPatch.h b/contrib/bobtoolz/DPatch.h index 63e15eea..8808daeb 100644 --- a/contrib/bobtoolz/DPatch.h +++ b/contrib/bobtoolz/DPatch.h @@ -1,34 +1,34 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPatch.h: interface for the DPatch class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_) +#if !defined( AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_ ) #define AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_ #include #include typedef struct -{ +{ bool mergable; int pos1; int pos2; @@ -38,13 +38,13 @@ typedef struct { float xyz[3]; float st[2]; float normal[3]; - float lightmap[2]; + float lightmap[2]; } drawVert_t; namespace scene { - class Node; - class Instance; +class Node; +class Instance; } #define MAX_PATCH_WIDTH 32 @@ -52,29 +52,29 @@ namespace scene #define MIN_PATCH_WIDTH 3 #define MIN_PATCH_HEIGHT 3 -class DPatch +class DPatch { public: - std::list SplitRows(); - std::list SplitCols(); - std::list Split(); - void Transpose(); - //DPatch* TransposePatch(DPatch* p1); - //void DebugPrint(); - void Invert(); - DPatch* MergePatches(patch_merge_t merge_info, DPatch* p1, DPatch* p2); - patch_merge_t IsMergable(DPatch* other); - bool ResetTextures(const char *oldTextureName, const char *newTextureName); - scene::Node* QER_entity; - scene::Node* QER_brush; - void LoadFromPatch(scene::Instance& patch); - void BuildInRadiant(scene::Node* entity = NULL); - void SetTexture(const char* textureName); - char texture[256]; - int width, height; - drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; - DPatch(); - virtual ~DPatch(); +std::list SplitRows(); +std::list SplitCols(); +std::list Split(); +void Transpose(); +//DPatch* TransposePatch(DPatch* p1); +//void DebugPrint(); +void Invert(); +DPatch* MergePatches( patch_merge_t merge_info, DPatch* p1, DPatch* p2 ); +patch_merge_t IsMergable( DPatch* other ); +bool ResetTextures( const char *oldTextureName, const char *newTextureName ); +scene::Node* QER_entity; +scene::Node* QER_brush; +void LoadFromPatch( scene::Instance& patch ); +void BuildInRadiant( scene::Node* entity = NULL ); +void SetTexture( const char* textureName ); +char texture[256]; +int width, height; +drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; +DPatch(); +virtual ~DPatch(); }; diff --git a/contrib/bobtoolz/DPlane.cpp b/contrib/bobtoolz/DPlane.cpp index c16db749..46990854 100644 --- a/contrib/bobtoolz/DPlane.cpp +++ b/contrib/bobtoolz/DPlane.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPlane.cpp: implementation of the DPlane class. // @@ -35,28 +35,29 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DPlane::DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData) -{ +DPlane::DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ){ MakeNormal( va, vb, vc, normal ); - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length + if ( VectorNormalize( normal, normal ) == 0 ) { // normalizes and returns length globalErrorStream() << "DPlane::DPlane: Bad Normal.\n"; + } - _d = (normal[0]*va[0]) + (normal[1]*va[1]) + (normal[2]*va[2]); + _d = ( normal[0] * va[0] ) + ( normal[1] * va[1] ) + ( normal[2] * va[2] ); - VectorCopy(va, points[0]); - VectorCopy(vb, points[1]); - VectorCopy(vc, points[2]); + VectorCopy( va, points[0] ); + VectorCopy( vb, points[1] ); + VectorCopy( vc, points[2] ); m_bChkOk = true; - if(texData) - memcpy(&texInfo, texData, sizeof(_QERFaceData)); - else - FillDefaultTexture(&texInfo, points[0], points[1], points[2], "textures/common/caulk"); + if ( texData ) { + memcpy( &texInfo, texData, sizeof( _QERFaceData ) ); + } + else{ + FillDefaultTexture( &texInfo, points[0], points[1], points[2], "textures/common/caulk" ); + } } -DPlane::~DPlane() -{ +DPlane::~DPlane(){ } @@ -64,179 +65,177 @@ DPlane::~DPlane() // Implementation ////////////////////////////////////////////////////////////////////// -vec_t DPlane::DistanceToPoint(vec3_t pnt) -{ +vec_t DPlane::DistanceToPoint( vec3_t pnt ){ vec3_t tmp; - VectorSubtract(pnt, points[0], tmp); - return DotProduct(tmp, normal); + VectorSubtract( pnt, points[0], tmp ); + return DotProduct( tmp, normal ); } -bool DPlane::PlaneIntersection(DPlane *pl1, DPlane *pl2, vec3_t out) -{ +bool DPlane::PlaneIntersection( DPlane *pl1, DPlane *pl2, vec3_t out ){ float a1, a2, a3; float b1, b2, b3; float c1, c2, c3; - - a1 = normal[0]; a2 = normal[1]; a3 = normal[2]; - b1 = pl1->normal[0]; b2 = pl1->normal[1]; b3 = pl1->normal[2]; - c1 = pl2->normal[0]; c2 = pl2->normal[1]; c3 = pl2->normal[2]; - float d = Determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3); + a1 = normal[0]; a2 = normal[1]; a3 = normal[2]; + b1 = pl1->normal[0]; b2 = pl1->normal[1]; b3 = pl1->normal[2]; + c1 = pl2->normal[0]; c2 = pl2->normal[1]; c3 = pl2->normal[2]; + + float d = Determinant3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3 ); - if(d == 0) + if ( d == 0 ) { return false; - + } + float v1 = _d; float v2 = pl1->_d; float v3 = pl2->_d; - float d1 = Determinant3x3(v1, a2, a3, v2, b2, b3, v3, c2, c3); - float d2 = Determinant3x3(a1, v1, a3, b1, v2, b3, c1, v3, c3); - float d3 = Determinant3x3(a1, a2, v1, b1, b2, v2, c1, c2, v3); + float d1 = Determinant3x3( v1, a2, a3, v2, b2, b3, v3, c2, c3 ); + float d2 = Determinant3x3( a1, v1, a3, b1, v2, b3, c1, v3, c3 ); + float d3 = Determinant3x3( a1, a2, v1, b1, b2, v2, c1, c2, v3 ); - out[0] = d1/d; - out[1] = d2/d; - out[2] = d3/d; + out[0] = d1 / d; + out[1] = d2 / d; + out[2] = d3 / d; return true; } -bool DPlane::IsRedundant(std::list& pointList) -{ +bool DPlane::IsRedundant( std::list& pointList ){ int cnt = 0; //std::list::const_iterator point=pointList.begin(); - for(std::list::const_iterator point=pointList.begin(); point!=pointList.end(); point++) + for ( std::list::const_iterator point = pointList.begin(); point != pointList.end(); point++ ) { - if(fabs(DistanceToPoint((*point)->_pnt)) < MAX_ROUND_ERROR) - cnt++; + if ( fabs( DistanceToPoint( ( *point )->_pnt ) ) < MAX_ROUND_ERROR ) { + cnt++; + } - if(cnt == 3) - return false; + if ( cnt == 3 ) { + return false; + } } return true; } -bool DPlane::operator == (DPlane& other) -{ +bool DPlane::operator ==( DPlane& other ){ vec3_t chk; - VectorSubtract(other.normal, normal, chk); - if(fabs(VectorLength(chk)) > MAX_ROUND_ERROR) + VectorSubtract( other.normal, normal, chk ); + if ( fabs( VectorLength( chk ) ) > MAX_ROUND_ERROR ) { return false; + } - if(fabs(other._d - _d) > MAX_ROUND_ERROR) + if ( fabs( other._d - _d ) > MAX_ROUND_ERROR ) { return false; + } return true; } -bool DPlane::operator != (DPlane& other) -{ +bool DPlane::operator !=( DPlane& other ){ vec3_t chk; - VectorAdd(other.normal, normal, chk); - if(fabs(VectorLength(chk)) > MAX_ROUND_ERROR) + VectorAdd( other.normal, normal, chk ); + if ( fabs( VectorLength( chk ) ) > MAX_ROUND_ERROR ) { return false; + } return true; } -DWinding* DPlane::BaseWindingForPlane() -{ - int i, x; - vec_t max, v; - vec3_t org, vright, vup; - +DWinding* DPlane::BaseWindingForPlane(){ + int i, x; + vec_t max, v; + vec3_t org, vright, vup; + // find the major axis max = -131072; x = -1; - for (i=0 ; i<3; i++) + for ( i = 0 ; i < 3; i++ ) { - v = (float)fabs(normal[i]); - if (v > max) - { + v = (float)fabs( normal[i] ); + if ( v > max ) { x = i; max = v; } } - if (x==-1) + if ( x == -1 ) { globalOutputStream() << "BaseWindingForPlane: no axis found"; - - VectorCopy (vec3_origin, vup); - switch (x) + } + + VectorCopy( vec3_origin, vup ); + switch ( x ) { case 0: case 1: vup[2] = 1; - break; + break; case 2: vup[0] = 1; - break; + break; } - v = DotProduct (vup, normal); - VectorMA (vup, -v, normal, vup); - VectorNormalize (vup, vup); - - VectorScale (normal, _d, org); - - CrossProduct (vup, normal, vright); - - VectorScale (vup, 131072, vup); - VectorScale (vright, 131072, vright); + v = DotProduct( vup, normal ); + VectorMA( vup, -v, normal, vup ); + VectorNormalize( vup, vup ); + + VectorScale( normal, _d, org ); + + CrossProduct( vup, normal, vright ); + + VectorScale( vup, 131072, vup ); + VectorScale( vright, 131072, vright ); // project a really big axis aligned box onto the plane DWinding* w = new DWinding; - w->AllocWinding(4); - - VectorSubtract (org, vright, w->p[0]); - VectorAdd (w->p[0], vup, w->p[0]); - - VectorAdd (org, vright, w->p[1]); - VectorAdd (w->p[1], vup, w->p[1]); - - VectorAdd (org, vright, w->p[2]); - VectorSubtract (w->p[2], vup, w->p[2]); - - VectorSubtract (org, vright, w->p[3]); - VectorSubtract (w->p[3], vup, w->p[3]); - - return w; + w->AllocWinding( 4 ); + + VectorSubtract( org, vright, w->p[0] ); + VectorAdd( w->p[0], vup, w->p[0] ); + + VectorAdd( org, vright, w->p[1] ); + VectorAdd( w->p[1], vup, w->p[1] ); + + VectorAdd( org, vright, w->p[2] ); + VectorSubtract( w->p[2], vup, w->p[2] ); + + VectorSubtract( org, vright, w->p[3] ); + VectorSubtract( w->p[3], vup, w->p[3] ); + + return w; } -void DPlane::Rebuild() -{ +void DPlane::Rebuild(){ vec3_t v1, v2; - VectorSubtract(points[0], points[1], v1); - VectorSubtract(points[2], points[1], v2); - CrossProduct(v1, v2, normal); + VectorSubtract( points[0], points[1], v1 ); + VectorSubtract( points[2], points[1], v2 ); + CrossProduct( v1, v2, normal ); - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length + if ( VectorNormalize( normal, normal ) == 0 ) { // normalizes and returns length globalErrorStream() << "DPlane::Rebuild: Bad Normal.\n"; + } - _d = (normal[0]*points[0][0]) + (normal[1]*points[0][1]) + (normal[2]*points[0][2]); + _d = ( normal[0] * points[0][0] ) + ( normal[1] * points[0][1] ) + ( normal[2] * points[0][2] ); - VectorCopy(points[0], texInfo.m_p0); - VectorCopy(points[1], texInfo.m_p1); - VectorCopy(points[2], texInfo.m_p2); + VectorCopy( points[0], texInfo.m_p0 ); + VectorCopy( points[1], texInfo.m_p1 ); + VectorCopy( points[2], texInfo.m_p2 ); } -bool DPlane::AddToBrush(scene::Node& brush) -{ - bool changed = false; - if(!(m_bChkOk || !strcmp(m_shader.c_str(), "textures/common/caulk"))) - { - m_shader = "textures/common/caulk"; - changed = true; - } - - _QERFaceData faceData; - faceData.m_p0 = vector3_from_array(points[0]); - faceData.m_p1 = vector3_from_array(points[1]); - faceData.m_p2 = vector3_from_array(points[2]); - faceData.m_texdef = texInfo.m_texdef; - faceData.m_shader = m_shader.c_str(); - GlobalBrushCreator().Brush_addFace(brush, faceData); +bool DPlane::AddToBrush( scene::Node& brush ){ + bool changed = false; + if ( !( m_bChkOk || !strcmp( m_shader.c_str(), "textures/common/caulk" ) ) ) { + m_shader = "textures/common/caulk"; + changed = true; + } + + _QERFaceData faceData; + faceData.m_p0 = vector3_from_array( points[0] ); + faceData.m_p1 = vector3_from_array( points[1] ); + faceData.m_p2 = vector3_from_array( points[2] ); + faceData.m_texdef = texInfo.m_texdef; + faceData.m_shader = m_shader.c_str(); + GlobalBrushCreator().Brush_addFace( brush, faceData ); return changed; } @@ -244,25 +243,26 @@ bool DPlane::AddToBrush(scene::Node& brush) void DPlane::ScaleTexture() { } -DPlane::DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail) -{ +DPlane::DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ){ vec3_t v1, v2; - VectorSubtract(va, vb, v1); - VectorSubtract(vc, vb, v2); - CrossProduct(v1, v2, normal); + VectorSubtract( va, vb, v1 ); + VectorSubtract( vc, vb, v2 ); + CrossProduct( v1, v2, normal ); - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length + if ( VectorNormalize( normal, normal ) == 0 ) { // normalizes and returns length globalErrorStream() << "DPlane::DPlane: Bad Normal.\n"; + } - _d = (normal[0]*va[0]) + (normal[1]*va[1]) + (normal[2]*va[2]); + _d = ( normal[0] * va[0] ) + ( normal[1] * va[1] ) + ( normal[2] * va[2] ); - VectorCopy(va, points[0]); - VectorCopy(vb, points[1]); - VectorCopy(vc, points[2]); + VectorCopy( va, points[0] ); + VectorCopy( vb, points[1] ); + VectorCopy( vc, points[2] ); m_bChkOk = true; - FillDefaultTexture(&texInfo, points[0], points[1], points[2], textureName); - if(bDetail) + FillDefaultTexture( &texInfo, points[0], points[1], points[2], textureName ); + if ( bDetail ) { texInfo.contents |= FACE_DETAIL; + } } diff --git a/contrib/bobtoolz/DPlane.h b/contrib/bobtoolz/DPlane.h index 68db6ed9..6e840cdb 100644 --- a/contrib/bobtoolz/DPlane.h +++ b/contrib/bobtoolz/DPlane.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPlane.h: interface for the DPlane class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_ #include @@ -40,34 +40,34 @@ class DPoint; class DWinding; -class DPlane +class DPlane { public: - DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail); - void ScaleTexture(); - DWinding* BaseWindingForPlane(); +DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail ); +void ScaleTexture(); +DWinding* BaseWindingForPlane(); - void Rebuild(); +void Rebuild(); - bool AddToBrush(scene::Node& brush); - bool operator != (DPlane& other); - bool operator == (DPlane& other); +bool AddToBrush( scene::Node& brush ); +bool operator !=( DPlane& other ); +bool operator ==( DPlane& other ); - bool IsRedundant(std::list& pointList); - bool PlaneIntersection(DPlane* pl1, DPlane* pl2, vec3_t out);; +bool IsRedundant( std::list& pointList ); +bool PlaneIntersection( DPlane* pl1, DPlane* pl2, vec3_t out );; - vec_t DistanceToPoint(vec3_t pnt); +vec_t DistanceToPoint( vec3_t pnt ); - DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData); - DPlane() { } - virtual ~DPlane(); +DPlane( const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData ); +DPlane() { } +virtual ~DPlane(); - bool m_bChkOk; - _QERFaceData texInfo; - CopiedString m_shader; - vec3_t points[3]; // djbob:do we really need these any more? - vec3_t normal; - float _d; +bool m_bChkOk; +_QERFaceData texInfo; +CopiedString m_shader; +vec3_t points[3]; // djbob:do we really need these any more? +vec3_t normal; +float _d; }; //typedef CList DPlaneList; diff --git a/contrib/bobtoolz/DPoint.cpp b/contrib/bobtoolz/DPoint.cpp index b0b60153..58628e62 100644 --- a/contrib/bobtoolz/DPoint.cpp +++ b/contrib/bobtoolz/DPoint.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPoint.cpp: implementation of the DPoint class. // @@ -28,13 +28,11 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DPoint::DPoint() -{ +DPoint::DPoint(){ } -DPoint::~DPoint() -{ +DPoint::~DPoint(){ } @@ -42,11 +40,11 @@ DPoint::~DPoint() // Implementation ////////////////////////////////////////////////////////////////////// -bool DPoint::operator ==(vec3_t other) -{ +bool DPoint::operator ==( vec3_t other ){ vec3_t test; - VectorSubtract(other, _pnt, test); - if(fabs(VectorLength(test)) > MAX_ROUND_ERROR) + VectorSubtract( other, _pnt, test ); + if ( fabs( VectorLength( test ) ) > MAX_ROUND_ERROR ) { return false; + } return true; } diff --git a/contrib/bobtoolz/DPoint.h b/contrib/bobtoolz/DPoint.h index 12137341..f7b68396 100644 --- a/contrib/bobtoolz/DPoint.h +++ b/contrib/bobtoolz/DPoint.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DPoint.h: interface for the DPoint class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -30,16 +30,16 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "mathlib.h" -class DPoint +class DPoint { public: - DPoint(); - virtual ~DPoint(); +DPoint(); +virtual ~DPoint(); - bool operator ==(vec3_t other); +bool operator ==( vec3_t other ); - vec3_t _pnt; - unsigned char m_uData; +vec3_t _pnt; +unsigned char m_uData; }; //typedef CList DPointList; diff --git a/contrib/bobtoolz/DShape.cpp b/contrib/bobtoolz/DShape.cpp index 9201d29c..8c675ff9 100644 --- a/contrib/bobtoolz/DShape.cpp +++ b/contrib/bobtoolz/DShape.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DShape.cpp: implementation of the DShape class. // @@ -45,45 +45,41 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA bool bFacesAll[6] = {true, true, true, true, true, true}; -DShape::DShape() -{ +DShape::DShape(){ m_nNextBrush = 0; } -DShape::~DShape() -{ +DShape::~DShape(){ } -void DShape::BuildRegularPrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop) -{ - vec3_t vc[MAX_POLYGON_FACES+2], vd[MAX_POLYGON_FACES+2]; +void DShape::BuildRegularPrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ){ + vec3_t vc[MAX_POLYGON_FACES + 2], vd[MAX_POLYGON_FACES + 2]; vec3_t radius; vec3_t origin; - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); + VectorSubtract( max, min, radius ); + VectorScale( radius, 0.5f, radius ); // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); + VectorAdd( max, min, origin ); + VectorScale( origin, 0.5f, origin ); float phase = 0.0f; - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); + if ( bAlignTop ) { + phase = -( Q_PI / nSides ); + VectorScale( radius, static_cast( 1.0 / cos( phase ) ), radius ); } //----- Build Polygon Vertices ----- int i; - for(i = 0; i < nSides; i++) + for ( i = 0; i < nSides; i++ ) { - VectorCopy(origin, vc[i]); - VectorCopy(origin, vd[i]); - + VectorCopy( origin, vc[i] ); + VectorCopy( origin, vd[i] ); + vc[i][2] = min[2]; vd[i][2] = max[2]; @@ -94,55 +90,52 @@ void DShape::BuildRegularPrism(vec3_t min, vec3_t max, int nSides, bool bAlignTo vd[i][1] = vc[i][1]; } - VectorCopy(vc[0], vc[nSides]); - VectorCopy(vd[0], vd[nSides]); - VectorCopy(vc[1], vc[nSides+1]); - VectorCopy(vd[1], vd[nSides+1]); - + VectorCopy( vc[0], vc[nSides] ); + VectorCopy( vd[0], vd[nSides] ); + VectorCopy( vc[1], vc[nSides + 1] ); + VectorCopy( vd[1], vd[nSides + 1] ); + //---------------------------------- - DBrush* pB = m_Container.GetWorldSpawn()->NewBrush(m_nNextBrush++); + DBrush* pB = m_Container.GetWorldSpawn()->NewBrush( m_nNextBrush++ ); - for(i = 1; i <= nSides; i++) - pB->AddFace(vc[i-1], vc[i], vd[i], GetCurrentTexture(), false); + for ( i = 1; i <= nSides; i++ ) + pB->AddFace( vc[i - 1], vc[i], vd[i], GetCurrentTexture(), false ); - pB->AddFace(vc[2], vc[1], vc[0], "textures/common/caulk", false); - pB->AddFace(vd[0], vd[1], vd[2], "textures/common/caulk", false); + pB->AddFace( vc[2], vc[1], vc[0], "textures/common/caulk", false ); + pB->AddFace( vd[0], vd[1], vd[2], "textures/common/caulk", false ); } -void DShape::Commit() -{ +void DShape::Commit(){ m_Container.GetWorldSpawn()->FixBrushes(); - m_Container.BuildInRadiant(true); + m_Container.BuildInRadiant( true ); } -void DShape::BuildInversePrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop) -{ - vec3_t va[MAX_POLYGON_FACES+1], vb[MAX_POLYGON_FACES+1]; +void DShape::BuildInversePrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ){ + vec3_t va[MAX_POLYGON_FACES + 1], vb[MAX_POLYGON_FACES + 1]; vec3_t radius; vec3_t origin; - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); + VectorSubtract( max, min, radius ); + VectorScale( radius, 0.5f, radius ); // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); + VectorAdd( max, min, origin ); + VectorScale( origin, 0.5f, origin ); float phase = 0.0f; - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); + if ( bAlignTop ) { + phase = -( Q_PI / nSides ); + VectorScale( radius, static_cast( 1.0 / cos( phase ) ), radius ); } //----- Build Polygon Vertices ----- int i; - for(i = 0; i < nSides; i++) + for ( i = 0; i < nSides; i++ ) { - VectorCopy(origin, va[i]); - VectorCopy(origin, vb[i]); + VectorCopy( origin, va[i] ); + VectorCopy( origin, vb[i] ); va[i][2] = min[2]; vb[i][2] = max[2]; @@ -154,90 +147,85 @@ void DShape::BuildInversePrism(vec3_t min, vec3_t max, int nSides, bool bAlignTo vb[i][1] = va[i][1]; } - VectorCopy(va[0], va[nSides]); - VectorCopy(vb[0], vb[nSides]); - + VectorCopy( va[0], va[nSides] ); + VectorCopy( vb[0], vb[nSides] ); + //---------------------------------- - for(i = 1; i <= nSides; i++) + for ( i = 1; i <= nSides; i++ ) { - DBrush* pB = GetBoundingCube(min, max, "textures/common/caulk"); + DBrush* pB = GetBoundingCube( min, max, "textures/common/caulk" ); vec3_t top, bottom; - VectorCopy(va[i-1], top); - VectorCopy(va[i], bottom); + VectorCopy( va[i - 1], top ); + VectorCopy( va[i], bottom ); - if(va[i-1][1] > va[i][1]) - { + if ( va[i - 1][1] > va[i][1] ) { top[0] += 5; bottom[0] += 5; } - else // flip direction of plane on crossover + else // flip direction of plane on crossover { top[0] -= 5; bottom[0] -= 5; } - - if(top[1] != bottom[1]) // internal line is flat already if true - { - pB->AddFace(va[i-1], top, vb[i-1], "textures/common/caulk", false); - pB->AddFace(va[i], vb[i], bottom, "textures/common/caulk", false); - } // add cut-off planes - - pB->AddFace(va[i-1], vb[i-1], vb[i], GetCurrentTexture(), false); + + if ( top[1] != bottom[1] ) { // internal line is flat already if true + pB->AddFace( va[i - 1], top, vb[i - 1], "textures/common/caulk", false ); + pB->AddFace( va[i], vb[i], bottom, "textures/common/caulk", false ); + } // add cut-off planes + + pB->AddFace( va[i - 1], vb[i - 1], vb[i], GetCurrentTexture(), false ); // add internal polygon plane } } -void DShape::BuildBorderedPrism(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop) -{ - vec3_t va[MAX_POLYGON_FACES+2], vb[MAX_POLYGON_FACES+2]; - vec3_t vc[MAX_POLYGON_FACES+2], vd[MAX_POLYGON_FACES+2]; +void DShape::BuildBorderedPrism( vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop ){ + vec3_t va[MAX_POLYGON_FACES + 2], vb[MAX_POLYGON_FACES + 2]; + vec3_t vc[MAX_POLYGON_FACES + 2], vd[MAX_POLYGON_FACES + 2]; vec3_t radius; vec3_t origin; - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); + VectorSubtract( max, min, radius ); + VectorScale( radius, 0.5f, radius ); // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); + VectorAdd( max, min, origin ); + VectorScale( origin, 0.5f, origin ); - if(nBorder >= Min(radius[0], radius[1])) - { + if ( nBorder >= Min( radius[0], radius[1] ) ) { // DoMessageBox("Border is too large", "Error", MB_OK); return; } float phase = 0.0f; - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); + if ( bAlignTop ) { + phase = -( Q_PI / nSides ); + VectorScale( radius, static_cast( 1.0 / cos( phase ) ), radius ); } //----- Build Polygon Vertices ----- int i; - for(i = 0; i < nSides; i++) + for ( i = 0; i < nSides; i++ ) { - VectorCopy(origin, va[i]); - VectorCopy(origin, vb[i]); - VectorCopy(origin, vc[i]); - VectorCopy(origin, vd[i]); + VectorCopy( origin, va[i] ); + VectorCopy( origin, vb[i] ); + VectorCopy( origin, vc[i] ); + VectorCopy( origin, vd[i] ); va[i][2] = min[2]; vb[i][2] = max[2]; - va[i][0] += (radius[0] - nBorder) * sinf( ( 2 * Q_PI * i / nSides ) + phase ); - va[i][1] += (radius[1] - nBorder) * cosf( ( 2 * Q_PI * i / nSides ) + phase ); + va[i][0] += ( radius[0] - nBorder ) * sinf( ( 2 * Q_PI * i / nSides ) + phase ); + va[i][1] += ( radius[1] - nBorder ) * cosf( ( 2 * Q_PI * i / nSides ) + phase ); vb[i][0] = va[i][0]; vb[i][1] = va[i][1]; - + vc[i][2] = min[2]; vd[i][2] = max[2]; @@ -248,42 +236,41 @@ void DShape::BuildBorderedPrism(vec3_t min, vec3_t max, int nSides, int nBorder, vd[i][1] = vc[i][1]; } - VectorCopy(va[0], va[nSides]); - VectorCopy(vb[0], vb[nSides]); - VectorCopy(va[1], va[nSides+1]); - VectorCopy(vb[1], vb[nSides+1]); + VectorCopy( va[0], va[nSides] ); + VectorCopy( vb[0], vb[nSides] ); + VectorCopy( va[1], va[nSides + 1] ); + VectorCopy( vb[1], vb[nSides + 1] ); + + VectorCopy( vc[0], vc[nSides] ); + VectorCopy( vd[0], vd[nSides] ); + VectorCopy( vc[1], vc[nSides + 1] ); + VectorCopy( vd[1], vd[nSides + 1] ); - VectorCopy(vc[0], vc[nSides]); - VectorCopy(vd[0], vd[nSides]); - VectorCopy(vc[1], vc[nSides+1]); - VectorCopy(vd[1], vd[nSides+1]); - //---------------------------------- - for(i = 1; i <= nSides; i++) + for ( i = 1; i <= nSides; i++ ) { - DBrush* pB = GetBoundingCube(min, max, "textures/common/caulk"); + DBrush* pB = GetBoundingCube( min, max, "textures/common/caulk" ); - pB->AddFace(origin, vc[i-1], vd[i-1], "textures/common/caulk", false); - pB->AddFace(origin, vd[i], vc[i], "textures/common/caulk", false); + pB->AddFace( origin, vc[i - 1], vd[i - 1], "textures/common/caulk", false ); + pB->AddFace( origin, vd[i], vc[i], "textures/common/caulk", false ); - pB->AddFace(vc[i-1], vc[i], vd[i], GetCurrentTexture(), false); - pB->AddFace(vb[i], va[i], va[i-1], GetCurrentTexture(), false); + pB->AddFace( vc[i - 1], vc[i], vd[i], GetCurrentTexture(), false ); + pB->AddFace( vb[i], va[i], va[i - 1], GetCurrentTexture(), false ); } } -DBrush* DShape::GetBoundingCube_Ext(vec3_t min, vec3_t max, const char *textureName, bool* bUseFaces, bool detail) -{ +DBrush* DShape::GetBoundingCube_Ext( vec3_t min, vec3_t max, const char *textureName, bool* bUseFaces, bool detail ){ DBrush* pB = new DBrush; //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); v2[0] = max[0]; v3[1] = max[1]; @@ -295,42 +282,49 @@ DBrush* DShape::GetBoundingCube_Ext(vec3_t min, vec3_t max, const char *textureN //----- Add Six Cube Faces --------- - if(bUseFaces[0]) - pB->AddFace(v1, v2, v3, textureName, detail); - if(bUseFaces[1]) - pB->AddFace(v1, v3, v6, textureName, detail); - if(bUseFaces[2]) - pB->AddFace(v1, v7, v2, textureName, detail); + if ( bUseFaces[0] ) { + pB->AddFace( v1, v2, v3, textureName, detail ); + } + if ( bUseFaces[1] ) { + pB->AddFace( v1, v3, v6, textureName, detail ); + } + if ( bUseFaces[2] ) { + pB->AddFace( v1, v7, v2, textureName, detail ); + } - if(bUseFaces[3]) - pB->AddFace(v5, v6, v3, textureName, detail); - if(bUseFaces[4]) - pB->AddFace(v5, v2, v7, textureName, detail); - if(bUseFaces[5]) - pB->AddFace(v5, v7, v6, textureName, detail); + if ( bUseFaces[3] ) { + pB->AddFace( v5, v6, v3, textureName, detail ); + } + if ( bUseFaces[4] ) { + pB->AddFace( v5, v2, v7, textureName, detail ); + } + if ( bUseFaces[5] ) { + pB->AddFace( v5, v7, v6, textureName, detail ); + } //---------------------------------- return pB; } -DBrush* DShape::GetBoundingCube(vec3_t min, vec3_t max, const char *textureName, DEntity* ent, bool* bUseFaces) -{ +DBrush* DShape::GetBoundingCube( vec3_t min, vec3_t max, const char *textureName, DEntity* ent, bool* bUseFaces ){ DBrush* pB; - if(ent == NULL) - pB = m_Container.GetWorldSpawn()->NewBrush(m_nNextBrush++); - else - pB = ent->NewBrush(m_nNextBrush++); + if ( ent == NULL ) { + pB = m_Container.GetWorldSpawn()->NewBrush( m_nNextBrush++ ); + } + else{ + pB = ent->NewBrush( m_nNextBrush++ ); + } //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); v2[0] = max[0]; v3[1] = max[1]; @@ -342,96 +336,102 @@ DBrush* DShape::GetBoundingCube(vec3_t min, vec3_t max, const char *textureName, //----- Add Six Cube Faces --------- - if(bUseFaces[0]) - pB->AddFace(v1, v2, v3, textureName, false); - if(bUseFaces[1]) - pB->AddFace(v1, v3, v6, textureName, false); - if(bUseFaces[2]) - pB->AddFace(v1, v7, v2, textureName, false); + if ( bUseFaces[0] ) { + pB->AddFace( v1, v2, v3, textureName, false ); + } + if ( bUseFaces[1] ) { + pB->AddFace( v1, v3, v6, textureName, false ); + } + if ( bUseFaces[2] ) { + pB->AddFace( v1, v7, v2, textureName, false ); + } - if(bUseFaces[3]) - pB->AddFace(v5, v6, v3, textureName, false); - if(bUseFaces[4]) - pB->AddFace(v5, v2, v7, textureName, false); - if(bUseFaces[5]) - pB->AddFace(v5, v7, v6, textureName, false); + if ( bUseFaces[3] ) { + pB->AddFace( v5, v6, v3, textureName, false ); + } + if ( bUseFaces[4] ) { + pB->AddFace( v5, v2, v7, textureName, false ); + } + if ( bUseFaces[5] ) { + pB->AddFace( v5, v7, v6, textureName, false ); + } //---------------------------------- return pB; } -bool DShape::BuildPit(vec3_t min, vec3_t max) -{ - if((max[2] - min[2]) < 196) +bool DShape::BuildPit( vec3_t min, vec3_t max ){ + if ( ( max[2] - min[2] ) < 196 ) { return false; + } - srand(time(NULL)); + srand( time( NULL ) ); vec3_t centre; - VectorAdd(min, max, centre); - VectorScale(centre, 0.5f, centre); + VectorAdd( min, max, centre ); + VectorScale( centre, 0.5f, centre ); char buffer[256]; - int team = (rand()%10000)+5000; + int team = ( rand() % 10000 ) + 5000; // ************* SPEAKER *************** - sprintf(buffer, "t%i_1", team); + sprintf( buffer, "t%i_1", team ); // trigger for speaker vec3_t triggerVoiceBtm; - VectorCopy(min, triggerVoiceBtm); + VectorCopy( min, triggerVoiceBtm ); triggerVoiceBtm[2] = max[2] - 16; - DEntity* triggerVoice = m_Container.AddEntity("trigger_multiple"); - GetBoundingCube(triggerVoiceBtm, max, "textures/common/trigger", triggerVoice); - triggerVoice->AddEPair("target", buffer); + DEntity* triggerVoice = m_Container.AddEntity( "trigger_multiple" ); + GetBoundingCube( triggerVoiceBtm, max, "textures/common/trigger", triggerVoice ); + triggerVoice->AddEPair( "target", buffer ); //-------------------- // target for speaker vec3_t voiceOrigin; - VectorCopy(centre, voiceOrigin); - voiceOrigin[2] = max[2]+16; + VectorCopy( centre, voiceOrigin ); + voiceOrigin[2] = max[2] + 16; - DEntity* targetVoice = m_Container.AddEntity("target_speaker"); - targetVoice->AddEPair("targetname", buffer); + DEntity* targetVoice = m_Container.AddEntity( "target_speaker" ); + targetVoice->AddEPair( "targetname", buffer ); - sprintf(buffer, "%f %f %f", voiceOrigin[0], voiceOrigin[1], voiceOrigin[2]); - targetVoice->AddEPair("origin", buffer); - targetVoice->AddEPair("spawnflags", "8"); - targetVoice->AddEPair("noise", "*falling1.wav"); + sprintf( buffer, "%f %f %f", voiceOrigin[0], voiceOrigin[1], voiceOrigin[2] ); + targetVoice->AddEPair( "origin", buffer ); + targetVoice->AddEPair( "spawnflags", "8" ); + targetVoice->AddEPair( "noise", "*falling1.wav" ); //-------------------- // *********** END SPEAKER ************* // ********* POWERUP REMOVAL *********** - sprintf(buffer, "t%i_2", team); + sprintf( buffer, "t%i_2", team ); // trigger for powerup removal vec3_t triggerPwrRmvTop, triggerPwrRmvBtm; - VectorCopy(min, triggerPwrRmvBtm); - VectorCopy(max, triggerPwrRmvTop); + VectorCopy( min, triggerPwrRmvBtm ); + VectorCopy( max, triggerPwrRmvTop ); triggerPwrRmvTop[2] = triggerVoiceBtm[2] - 64; triggerPwrRmvBtm[2] = triggerPwrRmvTop[2] - 16; - DEntity* triggerPwrRmv = m_Container.AddEntity("trigger_multiple"); - GetBoundingCube(triggerPwrRmvBtm, triggerPwrRmvTop, "textures/common/trigger", triggerPwrRmv); - triggerPwrRmv->AddEPair("target", buffer); + DEntity* triggerPwrRmv = m_Container.AddEntity( "trigger_multiple" ); + GetBoundingCube( triggerPwrRmvBtm, triggerPwrRmvTop, "textures/common/trigger", triggerPwrRmv ); + triggerPwrRmv->AddEPair( "target", buffer ); //-------------------- // target for powerup removal vec3_t pwrRmvOrigin; - VectorCopy(centre, pwrRmvOrigin); - pwrRmvOrigin[2] = triggerPwrRmvTop[2]+16; + VectorCopy( centre, pwrRmvOrigin ); + pwrRmvOrigin[2] = triggerPwrRmvTop[2] + 16; - DEntity* targetPwrRmv = m_Container.AddEntity("target_remove_powerups"); - targetPwrRmv->AddEPair("targetname", buffer); + DEntity* targetPwrRmv = m_Container.AddEntity( "target_remove_powerups" ); + targetPwrRmv->AddEPair( "targetname", buffer ); - sprintf(buffer, "%f %f %f", pwrRmvOrigin[0], pwrRmvOrigin[1], pwrRmvOrigin[2]); - targetPwrRmv->AddEPair("origin", buffer); + sprintf( buffer, "%f %f %f", pwrRmvOrigin[0], pwrRmvOrigin[1], pwrRmvOrigin[2] ); + targetPwrRmv->AddEPair( "origin", buffer ); //-------------------- // ****** END POWERUP REMOVAL ******** @@ -440,16 +440,16 @@ bool DShape::BuildPit(vec3_t min, vec3_t max) // trigger for damage vec3_t triggerDmgTop, triggerDmgBtm; - VectorCopy(min, triggerDmgBtm); - VectorCopy(max, triggerDmgTop); + VectorCopy( min, triggerDmgBtm ); + VectorCopy( max, triggerDmgTop ); triggerDmgBtm[2] = min[2] + 64; triggerDmgTop[2] = triggerDmgBtm[2] + 16; - DEntity* triggerDmg = m_Container.AddEntity("trigger_hurt"); - GetBoundingCube(triggerDmgBtm, triggerDmgTop, "textures/common/trigger", triggerDmg); - triggerDmg->AddEPair("dmg", "9999"); - triggerDmg->AddEPair("spawnflags", "12"); + DEntity* triggerDmg = m_Container.AddEntity( "trigger_hurt" ); + GetBoundingCube( triggerDmgBtm, triggerDmgTop, "textures/common/trigger", triggerDmg ); + triggerDmg->AddEPair( "dmg", "9999" ); + triggerDmg->AddEPair( "spawnflags", "12" ); //-------------------- // ****** END DAMAGE ******** @@ -457,11 +457,11 @@ bool DShape::BuildPit(vec3_t min, vec3_t max) // ********* NODROP *********** vec3_t nodropTop; - VectorCopy(max, nodropTop); + VectorCopy( max, nodropTop ); nodropTop[2] = min[2] + 64; - GetBoundingCube(min, nodropTop, "textures/common/nodrop"); + GetBoundingCube( min, nodropTop, "textures/common/nodrop" ); // ****** END NODROP ******** diff --git a/contrib/bobtoolz/DShape.h b/contrib/bobtoolz/DShape.h index 29bca7fc..1f6c91fc 100644 --- a/contrib/bobtoolz/DShape.h +++ b/contrib/bobtoolz/DShape.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DShape.h: interface for the DShape class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_) +#if !defined( AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_ ) #define AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_ #if _MSC_VER > 1000 @@ -35,29 +35,29 @@ class DBrush; class DEntity; // defines for polygon stuff -#define MAX_POLYGON_FACES 128 +#define MAX_POLYGON_FACES 128 extern bool bFacesAll[]; -class DShape +class DShape { public: - bool BuildPit(vec3_t min, vec3_t max); - void BuildBorderedPrism(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop); - void BuildInversePrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop); - void BuildRegularPrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop); - - int m_nNextBrush; - static DBrush* GetBoundingCube_Ext(vec3_t min, vec3_t max, const char* textureName, bool* bUseFaces = bFacesAll, bool detail = false); - - DShape(); - virtual ~DShape(); - - void Commit(); +bool BuildPit( vec3_t min, vec3_t max ); +void BuildBorderedPrism( vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop ); +void BuildInversePrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); +void BuildRegularPrism( vec3_t min, vec3_t max, int nSides, bool bAlignTop ); + +int m_nNextBrush; +static DBrush* GetBoundingCube_Ext( vec3_t min, vec3_t max, const char* textureName, bool* bUseFaces = bFacesAll, bool detail = false ); + +DShape(); +virtual ~DShape(); + +void Commit(); private: - DBrush* GetBoundingCube(vec3_t min, vec3_t max, const char* textureName, DEntity* ent = NULL, bool* bUseFaces = bFacesAll); +DBrush* GetBoundingCube( vec3_t min, vec3_t max, const char* textureName, DEntity* ent = NULL, bool* bUseFaces = bFacesAll ); - DMap m_Container; +DMap m_Container; }; #endif // !defined(AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_) diff --git a/contrib/bobtoolz/DTrainDrawer.cpp b/contrib/bobtoolz/DTrainDrawer.cpp index 92b2333a..da7edcc1 100644 --- a/contrib/bobtoolz/DTrainDrawer.cpp +++ b/contrib/bobtoolz/DTrainDrawer.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "DTrainDrawer.h" @@ -42,70 +42,69 @@ DTrainDrawer::DTrainDrawer() { m_bDisplay = false; BuildPaths(); - constructShaders(); - GlobalShaderCache().attachRenderable(*this); + constructShaders(); + GlobalShaderCache().attachRenderable( *this ); } -DTrainDrawer::~DTrainDrawer(void) { - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); +DTrainDrawer::~DTrainDrawer( void ) { + GlobalShaderCache().detachRenderable( *this ); + destroyShaders(); ClearPoints(); ClearSplines(); } void DTrainDrawer::ClearSplines() { - for(std::list::const_iterator deadSpline = m_splineList.begin(); deadSpline != m_splineList.end(); deadSpline++) { - (*deadSpline)->m_pointList.clear(); - (*deadSpline)->m_vertexList.clear(); - delete (*deadSpline); + for ( std::list::const_iterator deadSpline = m_splineList.begin(); deadSpline != m_splineList.end(); deadSpline++ ) { + ( *deadSpline )->m_pointList.clear(); + ( *deadSpline )->m_vertexList.clear(); + delete ( *deadSpline ); } m_splineList.clear(); } void DTrainDrawer::ClearPoints() { - for(std::list::const_iterator deadPoint = m_pointList.begin(); deadPoint != m_pointList.end(); deadPoint++) { + for ( std::list::const_iterator deadPoint = m_pointList.begin(); deadPoint != m_pointList.end(); deadPoint++ ) { delete *deadPoint; } m_pointList.clear(); } -void CalculateSpline_r(vec3_t* v, int count, vec3_t out, float tension) { +void CalculateSpline_r( vec3_t* v, int count, vec3_t out, float tension ) { vec3_t dist; - if(count < 2) { + if ( count < 2 ) { return; } - if(count == 2) { + if ( count == 2 ) { VectorSubtract( v[1], v[0], dist ); - VectorMA(v[0], tension, dist, out); + VectorMA( v[0], tension, dist, out ); return; } - vec3_t* v2 = new vec3_t[count-1]; + vec3_t* v2 = new vec3_t[count - 1]; - for( int i = 0; i < count-1; i++ ) { - VectorSubtract( v[i+1], v[i], dist ); - VectorMA(v[i], tension, dist, v2[i]); + for ( int i = 0; i < count - 1; i++ ) { + VectorSubtract( v[i + 1], v[i], dist ); + VectorMA( v[i], tension, dist, v2[i] ); } - CalculateSpline_r( v2, count-1, out, tension); + CalculateSpline_r( v2, count - 1, out, tension ); delete[] v2; } -void DTrainDrawer::render(RenderStateFlags state) const -{ - for(std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); +void DTrainDrawer::render( RenderStateFlags state ) const { + for ( std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++ ) { + splinePoint_t* pSP = ( *sp ); - glBegin(GL_LINE_STRIP); - for(std::list::const_iterator v = pSP->m_vertexList.begin(); v != pSP->m_vertexList.end(); v++) { - glVertex3fv((*v)._pnt); - } + glBegin( GL_LINE_STRIP ); + for ( std::list::const_iterator v = pSP->m_vertexList.begin(); v != pSP->m_vertexList.end(); v++ ) { + glVertex3fv( ( *v )._pnt ); + } glEnd(); } @@ -114,136 +113,132 @@ void DTrainDrawer::render(RenderStateFlags state) const const char* DTrainDrawer_state_wireframe = "$bobtoolz/traindrawer/wireframe"; const char* DTrainDrawer_state_solid = "$bobtoolz/traindrawer/solid"; -void DTrainDrawer::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = 1; - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - state.m_linewidth = 1; - GlobalOpenGLStateLibrary().insert(DTrainDrawer_state_wireframe, state); - - state.m_colour[0] = 1; - state.m_colour[1] = 1; - state.m_colour[2] = 1; - state.m_colour[3] = 1; - state.m_linewidth = 2; - GlobalOpenGLStateLibrary().insert(DTrainDrawer_state_solid, state); - - m_shader_wireframe = GlobalShaderCache().capture(DTrainDrawer_state_wireframe); - m_shader_solid = GlobalShaderCache().capture(DTrainDrawer_state_solid); +void DTrainDrawer::constructShaders(){ + OpenGLState state; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_BLEND; + state.m_sort = OpenGLState::eSortOverlayFirst; + state.m_linewidth = 1; + state.m_colour[0] = 1; + state.m_colour[1] = 0; + state.m_colour[2] = 0; + state.m_colour[3] = 1; + state.m_linewidth = 1; + GlobalOpenGLStateLibrary().insert( DTrainDrawer_state_wireframe, state ); + + state.m_colour[0] = 1; + state.m_colour[1] = 1; + state.m_colour[2] = 1; + state.m_colour[3] = 1; + state.m_linewidth = 2; + GlobalOpenGLStateLibrary().insert( DTrainDrawer_state_solid, state ); + + m_shader_wireframe = GlobalShaderCache().capture( DTrainDrawer_state_wireframe ); + m_shader_solid = GlobalShaderCache().capture( DTrainDrawer_state_solid ); } -void DTrainDrawer::destroyShaders() -{ - GlobalOpenGLStateLibrary().erase(DTrainDrawer_state_wireframe); - GlobalOpenGLStateLibrary().erase(DTrainDrawer_state_solid); - GlobalShaderCache().release(DTrainDrawer_state_wireframe); - GlobalShaderCache().release(DTrainDrawer_state_solid); +void DTrainDrawer::destroyShaders(){ + GlobalOpenGLStateLibrary().erase( DTrainDrawer_state_wireframe ); + GlobalOpenGLStateLibrary().erase( DTrainDrawer_state_solid ); + GlobalShaderCache().release( DTrainDrawer_state_wireframe ); + GlobalShaderCache().release( DTrainDrawer_state_solid ); } -void DTrainDrawer::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_bDisplay) { +void DTrainDrawer::renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if ( !m_bDisplay ) { return; } - renderer.SetState(m_shader_wireframe, Renderer::eWireframeOnly); - renderer.SetState(m_shader_solid, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_matrix4_identity); + renderer.SetState( m_shader_wireframe, Renderer::eWireframeOnly ); + renderer.SetState( m_shader_solid, Renderer::eFullMaterials ); + renderer.addRenderable( *this, g_matrix4_identity ); } -void DTrainDrawer::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - renderSolid(renderer, volume); +void DTrainDrawer::renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + renderSolid( renderer, volume ); } -void AddSplineControl(const char* control, splinePoint_t* pSP) { +void AddSplineControl( const char* control, splinePoint_t* pSP ) { controlPoint_t cp; - strncpy(cp.strName, control, 64); + strncpy( cp.strName, control, 64 ); - pSP->m_pointList.push_front(cp); + pSP->m_pointList.push_front( cp ); } class EntityBuildPaths { - mutable DEntity e; - DTrainDrawer& drawer; +mutable DEntity e; +DTrainDrawer& drawer; public: - EntityBuildPaths(DTrainDrawer& drawer) : drawer(drawer) - { - } - void operator()(scene::Instance& instance) const - { - e.ClearEPairs(); - e.LoadEPairList(Node_getEntity(instance.path().top())); - - const char* classname = e.m_Classname.GetBuffer(); - const char* target; - const char* control; - const char* targetname; - vec3_t vOrigin; - - e.SpawnString("targetname", NULL, &targetname); - e.SpawnVector("origin", "0 0 0", vOrigin); - - if(!strcmp(classname, "info_train_spline_main")) { - if(!targetname) { - globalOutputStream() << "info_train_spline_main with no targetname"; - return; - } +EntityBuildPaths( DTrainDrawer& drawer ) : drawer( drawer ){ +} +void operator()( scene::Instance& instance ) const { + e.ClearEPairs(); + e.LoadEPairList( Node_getEntity( instance.path().top() ) ); + + const char* classname = e.m_Classname.GetBuffer(); + const char* target; + const char* control; + const char* targetname; + vec3_t vOrigin; + + e.SpawnString( "targetname", NULL, &targetname ); + e.SpawnVector( "origin", "0 0 0", vOrigin ); + + if ( !strcmp( classname, "info_train_spline_main" ) ) { + if ( !targetname ) { + globalOutputStream() << "info_train_spline_main with no targetname"; + return; + } - e.SpawnString("target", NULL, &target); + e.SpawnString( "target", NULL, &target ); - if(!target) { - drawer.AddControlPoint( targetname, vOrigin ); - } else { - splinePoint_t* pSP = drawer.AddSplinePoint( targetname, target, vOrigin ); + if ( !target ) { + drawer.AddControlPoint( targetname, vOrigin ); + } + else { + splinePoint_t* pSP = drawer.AddSplinePoint( targetname, target, vOrigin ); - e.SpawnString("control", NULL, &control); + e.SpawnString( "control", NULL, &control ); - if(control) { - AddSplineControl( control, pSP ); + if ( control ) { + AddSplineControl( control, pSP ); - for(int j = 2;; j++) { - char buffer[16]; - sprintf(buffer, "control%i", j); + for ( int j = 2;; j++ ) { + char buffer[16]; + sprintf( buffer, "control%i", j ); - e.SpawnString(buffer, NULL, &control); - if(!control) { - break; - } - - AddSplineControl( control, pSP ); + e.SpawnString( buffer, NULL, &control ); + if ( !control ) { + break; } + + AddSplineControl( control, pSP ); } } - } else if(!strcmp(classname, "info_train_spline_control")) { - if(!targetname) { - globalOutputStream() << "info_train_spline_control with no targetname"; - return; - } - - drawer.AddControlPoint( targetname, vOrigin ); } - } + } + else if ( !strcmp( classname, "info_train_spline_control" ) ) { + if ( !targetname ) { + globalOutputStream() << "info_train_spline_control with no targetname"; + return; + } + + drawer.AddControlPoint( targetname, vOrigin ); + } +} }; void DTrainDrawer::BuildPaths() { - Scene_forEachEntity(EntityBuildPaths(*this)); + Scene_forEachEntity( EntityBuildPaths( *this ) ); - std::list::const_iterator sp; - for(sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); + std::list::const_iterator sp; + for ( sp = m_splineList.begin(); sp != m_splineList.end(); sp++ ) { + splinePoint_t* pSP = ( *sp ); controlPoint_t* pTarget = FindControlPoint( pSP->strTarget ); - if(!pTarget) { + if ( !pTarget ) { globalOutputStream() << "couldn't find target " << pSP->strTarget; return; // continue; @@ -252,86 +247,83 @@ void DTrainDrawer::BuildPaths() { pSP->pTarget = pTarget; - for(std::list::iterator cp = pSP->m_pointList.begin(); cp != pSP->m_pointList.end(); cp++) { - controlPoint_t* pControl = FindControlPoint( (*cp).strName ); - if(!pControl) { - globalOutputStream() << "couldn't find control " << (*cp).strName; + for ( std::list::iterator cp = pSP->m_pointList.begin(); cp != pSP->m_pointList.end(); cp++ ) { + controlPoint_t* pControl = FindControlPoint( ( *cp ).strName ); + if ( !pControl ) { + globalOutputStream() << "couldn't find control " << ( *cp ).strName; return; } - VectorCopy(pControl->vOrigin, (*cp).vOrigin); + VectorCopy( pControl->vOrigin, ( *cp ).vOrigin ); } } m_bDisplay = true; - for(sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); + for ( sp = m_splineList.begin(); sp != m_splineList.end(); sp++ ) { + splinePoint_t* pSP = ( *sp ); DPoint out; - if(!pSP->pTarget) { + if ( !pSP->pTarget ) { continue; } - std::size_t count = pSP->m_pointList.size() + 2; + std::size_t count = pSP->m_pointList.size() + 2; vec3_t* v = new vec3_t[count]; - VectorCopy(pSP->point.vOrigin, v[0]); + VectorCopy( pSP->point.vOrigin, v[0] ); int i = 1; - for(std::list::reverse_iterator cp = pSP->m_pointList.rbegin(); cp != pSP->m_pointList.rend(); cp++) { - VectorCopy((*cp).vOrigin, v[i]); + for ( std::list::reverse_iterator cp = pSP->m_pointList.rbegin(); cp != pSP->m_pointList.rend(); cp++ ) { + VectorCopy( ( *cp ).vOrigin, v[i] ); i++; } - VectorCopy(pSP->pTarget->vOrigin, v[i]); + VectorCopy( pSP->pTarget->vOrigin, v[i] ); - for (float tension = 0.0f; tension <= 1.f; tension += 0.01f) { - CalculateSpline_r(v, static_cast(count), out._pnt, tension); - pSP->m_vertexList.push_front(out); + for ( float tension = 0.0f; tension <= 1.f; tension += 0.01f ) { + CalculateSpline_r( v, static_cast( count ), out._pnt, tension ); + pSP->m_vertexList.push_front( out ); } delete[] v; - VectorCopy(pSP->pTarget->vOrigin, out._pnt); - pSP->m_vertexList.push_front(out); + VectorCopy( pSP->pTarget->vOrigin, out._pnt ); + pSP->m_vertexList.push_front( out ); } - SceneChangeNotify(); + SceneChangeNotify(); } -void DTrainDrawer::AddControlPoint(const char* name, vec_t* origin) -{ +void DTrainDrawer::AddControlPoint( const char* name, vec_t* origin ){ controlPoint_t* pCP = new controlPoint_t; - strncpy(pCP->strName, name, 64); + strncpy( pCP->strName, name, 64 ); VectorCopy( origin, pCP->vOrigin ); m_pointList.push_back( pCP ); } -splinePoint_t* DTrainDrawer::AddSplinePoint(const char* name, const char* target, vec_t* origin) -{ +splinePoint_t* DTrainDrawer::AddSplinePoint( const char* name, const char* target, vec_t* origin ){ splinePoint_t* pSP = new splinePoint_t; - strncpy(pSP->point.strName, name, 64); - strncpy(pSP->strTarget, target, 64); + strncpy( pSP->point.strName, name, 64 ); + strncpy( pSP->strTarget, target, 64 ); VectorCopy( origin, pSP->point.vOrigin ); m_splineList.push_back( pSP ); return pSP; } -controlPoint_t* DTrainDrawer::FindControlPoint(const char* name) -{ - for(std::list::const_iterator cp = m_pointList.begin(); cp != m_pointList.end(); cp++) { - if(!strcmp(name, (*cp)->strName)) { - return (*cp); +controlPoint_t* DTrainDrawer::FindControlPoint( const char* name ){ + for ( std::list::const_iterator cp = m_pointList.begin(); cp != m_pointList.end(); cp++ ) { + if ( !strcmp( name, ( *cp )->strName ) ) { + return ( *cp ); } } - for(std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - if(!strcmp(name, (*sp)->point.strName)) { - return &((*sp)->point); + for ( std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++ ) { + if ( !strcmp( name, ( *sp )->point.strName ) ) { + return &( ( *sp )->point ); } } diff --git a/contrib/bobtoolz/DTrainDrawer.h b/contrib/bobtoolz/DTrainDrawer.h index 9d8903ee..2b79f674 100644 --- a/contrib/bobtoolz/DTrainDrawer.h +++ b/contrib/bobtoolz/DTrainDrawer.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DTrainDrawer.h: interface for the DTrainDrawer class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -59,30 +59,30 @@ typedef struct { class DTrainDrawer : public Renderable, public OpenGLRenderable { private: - std::list m_splineList; - std::list m_pointList; +std::list m_splineList; +std::list m_pointList; - bool m_bDisplay; - Shader* m_shader_wireframe; - Shader* m_shader_solid; +bool m_bDisplay; +Shader* m_shader_wireframe; +Shader* m_shader_solid; public: - - DTrainDrawer(); - virtual ~DTrainDrawer(void); - - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; - - void constructShaders(); - void destroyShaders(); - - void ClearSplines(); - void ClearPoints(); - void BuildPaths(); - void AddControlPoint(const char* name, vec_t* origin); - splinePoint_t* AddSplinePoint(const char* name, const char* target, vec_t* origin); - controlPoint_t* FindControlPoint(const char* name); + +DTrainDrawer(); +virtual ~DTrainDrawer( void ); + +void render( RenderStateFlags state ) const; +void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; +void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; + +void constructShaders(); +void destroyShaders(); + +void ClearSplines(); +void ClearPoints(); +void BuildPaths(); +void AddControlPoint( const char* name, vec_t* origin ); +splinePoint_t* AddSplinePoint( const char* name, const char* target, vec_t* origin ); +controlPoint_t* FindControlPoint( const char* name ); }; #endif // !defined(AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/DTreePlanter.cpp b/contrib/bobtoolz/DTreePlanter.cpp index 6ad221be..78fa550d 100644 --- a/contrib/bobtoolz/DTreePlanter.cpp +++ b/contrib/bobtoolz/DTreePlanter.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "DTreePlanter.h" @@ -37,121 +37,120 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "funchandlers.h" -SignalHandlerResult DTreePlanter::mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) -{ - if(button != c_buttonLeft) - { - return SIGNAL_CONTINUE_EMISSION; - } +SignalHandlerResult DTreePlanter::mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){ + if ( button != c_buttonLeft ) { + return SIGNAL_CONTINUE_EMISSION; + } VIEWTYPE vt = GlobalRadiant().XYWindow_getViewType(); - switch(vt) { - case XY: - break; - case YZ: - case XZ: - default: - return SIGNAL_CONTINUE_EMISSION; + switch ( vt ) { + case XY: + break; + case YZ: + case XZ: + default: + return SIGNAL_CONTINUE_EMISSION; } Vector3 pt, vhit; - pt = vector3_snapped(GlobalRadiant().XYWindow_windowToWorld(position), GlobalRadiant().getGridSize()); + pt = vector3_snapped( GlobalRadiant().XYWindow_windowToWorld( position ), GlobalRadiant().getGridSize() ); - if(FindDropPoint(vector3_to_array(pt), vector3_to_array(vhit))) { + if ( FindDropPoint( vector3_to_array( pt ), vector3_to_array( vhit ) ) ) { vhit[2] += m_offset; char buffer[128]; - DEntity e(m_entType); + DEntity e( m_entType ); - sprintf(buffer, "%i %i %i", (int)vhit[0], (int)vhit[1], (int)vhit[2]); - e.AddEPair("origin", buffer); + sprintf( buffer, "%i %i %i", (int)vhit[0], (int)vhit[1], (int)vhit[2] ); + e.AddEPair( "origin", buffer ); - if(m_autoLink) { + if ( m_autoLink ) { - const scene::Path* pLastEntity = NULL; + const scene::Path* pLastEntity = NULL; const scene::Path* pThisEntity = NULL; int entpos; - for(int i = 0; i < 256; i++) { - sprintf(buffer, m_linkName, i); - pThisEntity = FindEntityFromTargetname( buffer ); + for ( int i = 0; i < 256; i++ ) { + sprintf( buffer, m_linkName, i ); + pThisEntity = FindEntityFromTargetname( buffer ); - if(pThisEntity) { + if ( pThisEntity ) { entpos = i; pLastEntity = pThisEntity; } } - if(!pLastEntity) { - sprintf(buffer, m_linkName, 0); - } else { - sprintf(buffer, m_linkName, entpos + 1); + if ( !pLastEntity ) { + sprintf( buffer, m_linkName, 0 ); + } + else { + sprintf( buffer, m_linkName, entpos + 1 ); } e.AddEPair( "targetname", buffer ); - if(pLastEntity) { + if ( pLastEntity ) { DEntity e2; - e2.LoadFromEntity(pLastEntity->top(), true); - e2.AddEPair("target", buffer); + e2.LoadFromEntity( pLastEntity->top(), true ); + e2.AddEPair( "target", buffer ); e2.RemoveFromRadiant(); - e2.BuildInRadiant(false); + e2.BuildInRadiant( false ); } } - if(m_setAngles) { - int angleYaw = (rand() % (m_maxYaw - m_minYaw + 1)) + m_minYaw; - int anglePitch = (rand() % (m_maxPitch - m_minPitch + 1)) + m_minPitch; + if ( m_setAngles ) { + int angleYaw = ( rand() % ( m_maxYaw - m_minYaw + 1 ) ) + m_minYaw; + int anglePitch = ( rand() % ( m_maxPitch - m_minPitch + 1 ) ) + m_minPitch; - sprintf(buffer, "%i %i 0", anglePitch, angleYaw); - e.AddEPair("angles", buffer); + sprintf( buffer, "%i %i 0", anglePitch, angleYaw ); + e.AddEPair( "angles", buffer ); } - if(m_numModels) { + if ( m_numModels ) { int treetype = rand() % m_numModels; - e.AddEPair("model", m_trees[treetype].name); + e.AddEPair( "model", m_trees[treetype].name ); } - if(m_useScale) { - float scale = (((rand()%1000)*0.001f) * (m_maxScale - m_minScale)) + m_minScale; + if ( m_useScale ) { + float scale = ( ( ( rand() % 1000 ) * 0.001f ) * ( m_maxScale - m_minScale ) ) + m_minScale; - sprintf(buffer, "%f", scale ); - e.AddEPair("modelscale", buffer); + sprintf( buffer, "%f", scale ); + e.AddEPair( "modelscale", buffer ); } e.BuildInRadiant( false ); } - if(m_autoLink) { + if ( m_autoLink ) { DoTrainPathPlot(); } return SIGNAL_STOP_EMISSION; } -bool DTreePlanter::FindDropPoint(vec3_t in, vec3_t out) { +bool DTreePlanter::FindDropPoint( vec3_t in, vec3_t out ) { DPlane p1; DPlane p2; - vec3_t vUp = { 0, 0, 1 }; - vec3_t vForward = { 0, 1, 0 }; - vec3_t vLeft = { 1, 0, 0 }; + vec3_t vUp = { 0, 0, 1 }; + vec3_t vForward = { 0, 1, 0 }; + vec3_t vLeft = { 1, 0, 0 }; in[2] = 65535; - VectorCopy(in, p1.points[0]); - VectorCopy(in, p1.points[1]); - VectorCopy(in, p1.points[2]); - VectorMA(p1.points[1], 20, vUp, p1.points[1]); - VectorMA(p1.points[1], 20, vLeft, p1.points[2]); + VectorCopy( in, p1.points[0] ); + VectorCopy( in, p1.points[1] ); + VectorCopy( in, p1.points[2] ); + VectorMA( p1.points[1], 20, vUp, p1.points[1] ); + VectorMA( p1.points[1], 20, vLeft, p1.points[2] ); - VectorCopy(in, p2.points[0]); - VectorCopy(in, p2.points[1]); - VectorCopy(in, p2.points[2]); - VectorMA(p1.points[1], 20, vUp, p2.points[1]); - VectorMA(p1.points[1], 20, vForward, p2.points[2]); + VectorCopy( in, p2.points[0] ); + VectorCopy( in, p2.points[1] ); + VectorCopy( in, p2.points[2] ); + VectorMA( p1.points[1], 20, vUp, p2.points[1] ); + VectorMA( p1.points[1], 20, vForward, p2.points[2] ); p1.Rebuild(); p2.Rebuild(); @@ -160,15 +159,15 @@ bool DTreePlanter::FindDropPoint(vec3_t in, vec3_t out) { vec3_t temp; vec_t dist; int cnt = m_world.GetIDMax(); - for(int i = 0; i < cnt; i++) { + for ( int i = 0; i < cnt; i++ ) { DBrush* pBrush = m_world.GetBrushForID( i ); - - if(pBrush->IntersectsWith( &p1, &p2, temp )) { + + if ( pBrush->IntersectsWith( &p1, &p2, temp ) ) { vec3_t diff; vec_t tempdist; - VectorSubtract(in, temp, diff); + VectorSubtract( in, temp, diff ); tempdist = VectorLength( diff ); - if(!found || (tempdist < dist)) { + if ( !found || ( tempdist < dist ) ) { dist = tempdist; VectorCopy( temp, out ); found = true; @@ -181,47 +180,44 @@ bool DTreePlanter::FindDropPoint(vec3_t in, vec3_t out) { class TreePlanterDropEntityIfSelected { - mutable DEntity ent; - DTreePlanter& planter; +mutable DEntity ent; +DTreePlanter& planter; public: - TreePlanterDropEntityIfSelected(DTreePlanter& planter) : planter(planter) - { - } - void operator()(scene::Instance& instance) const - { - if(!instance.isSelected()) - { - return; - } - ent.LoadFromEntity(instance.path().top()); +TreePlanterDropEntityIfSelected( DTreePlanter& planter ) : planter( planter ){ +} +void operator()( scene::Instance& instance ) const { + if ( !instance.isSelected() ) { + return; + } + ent.LoadFromEntity( instance.path().top() ); - DEPair* pEpair = ent.FindEPairByKey("origin"); - if(!pEpair) { - return; - } + DEPair* pEpair = ent.FindEPairByKey( "origin" ); + if ( !pEpair ) { + return; + } - vec3_t vec, out; - sscanf( pEpair->value.GetBuffer(), "%f %f %f", &vec[0], &vec[1], &vec[2]); + vec3_t vec, out; + sscanf( pEpair->value.GetBuffer(), "%f %f %f", &vec[0], &vec[1], &vec[2] ); - planter.FindDropPoint( vec, out ); + planter.FindDropPoint( vec, out ); - char buffer[256]; - sprintf( buffer, "%f %f %f", out[0], out[1], out[2] ); - ent.AddEPair( "origin", buffer ); - ent.RemoveFromRadiant(); - ent.BuildInRadiant(false); - } + char buffer[256]; + sprintf( buffer, "%f %f %f", out[0], out[1], out[2] ); + ent.AddEPair( "origin", buffer ); + ent.RemoveFromRadiant(); + ent.BuildInRadiant( false ); +} }; void DTreePlanter::DropEntsToGround( void ) { - Scene_forEachEntity(TreePlanterDropEntityIfSelected(*this)); + Scene_forEachEntity( TreePlanterDropEntityIfSelected( *this ) ); } void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { char buffer[256]; int i; - for(i = 0; i < linkNum; i++) { - DEntity e("info_train_spline_main"); + for ( i = 0; i < linkNum; i++ ) { + DEntity e( "info_train_spline_main" ); sprintf( buffer, "%s_pt%i", linkName, i ); e.AddEPair( "targetname", buffer ); @@ -229,8 +225,8 @@ void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { sprintf( buffer, "0 %i 0", i * 64 ); e.AddEPair( "origin", buffer ); - if(i != m_linkNum-1) { - sprintf( buffer, "%s_pt%i", linkName, i+1 ); + if ( i != m_linkNum - 1 ) { + sprintf( buffer, "%s_pt%i", linkName, i + 1 ); e.AddEPair( "target", buffer ); sprintf( buffer, "%s_ctl%i", linkName, i ); @@ -239,13 +235,13 @@ void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { e.BuildInRadiant( false ); } - for(i = 0; i < linkNum-1; i++) { - DEntity e("info_train_spline_control"); + for ( i = 0; i < linkNum - 1; i++ ) { + DEntity e( "info_train_spline_control" ); sprintf( buffer, "%s_ctl%i", linkName, i ); e.AddEPair( "targetname", buffer ); - sprintf( buffer, "0 %i 0", (i * 64) + 32); + sprintf( buffer, "0 %i 0", ( i * 64 ) + 32 ); e.AddEPair( "origin", buffer ); e.BuildInRadiant( false ); @@ -254,36 +250,36 @@ void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { void DTreePlanter::SelectChain( void ) { /* char buffer[256]; - - for(int i = 0; i < m_linkNum; i++) { - DEntity e("info_train_spline_main"); - sprintf( buffer, "%s_pt%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); + for(int i = 0; i < m_linkNum; i++) { + DEntity e("info_train_spline_main"); - sprintf( buffer, "0 %i 0", i * 64 ); - e.AddEPair( "origin", buffer ); + sprintf( buffer, "%s_pt%i", m_linkName, i ); + e.AddEPair( "targetname", buffer ); - if(i != m_linkNum-1) { - sprintf( buffer, "%s_pt%i", m_linkName, i+1 ); - e.AddEPair( "target", buffer ); + sprintf( buffer, "0 %i 0", i * 64 ); + e.AddEPair( "origin", buffer ); - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "control", buffer ); - } + if(i != m_linkNum-1) { + sprintf( buffer, "%s_pt%i", m_linkName, i+1 ); + e.AddEPair( "target", buffer ); - e.BuildInRadiant( false ); - } + sprintf( buffer, "%s_ctl%i", m_linkName, i ); + e.AddEPair( "control", buffer ); + } - for(int i = 0; i < m_linkNum-1; i++) { - DEntity e("info_train_spline_control"); + e.BuildInRadiant( false ); + } - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); + for(int i = 0; i < m_linkNum-1; i++) { + DEntity e("info_train_spline_control"); - sprintf( buffer, "0 %i 0", (i * 64) + 32); - e.AddEPair( "origin", buffer ); + sprintf( buffer, "%s_ctl%i", m_linkName, i ); + e.AddEPair( "targetname", buffer ); - e.BuildInRadiant( false ); - }*/ + sprintf( buffer, "0 %i 0", (i * 64) + 32); + e.AddEPair( "origin", buffer ); + + e.BuildInRadiant( false ); + }*/ } diff --git a/contrib/bobtoolz/DTreePlanter.h b/contrib/bobtoolz/DTreePlanter.h index fec8910f..1d198ae6 100644 --- a/contrib/bobtoolz/DTreePlanter.h +++ b/contrib/bobtoolz/DTreePlanter.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef __DTREE_H__ #define __DTREE_H__ @@ -38,174 +38,177 @@ typedef struct treeModel_s { #define MAX_TP_MODELS 256 class DTreePlanter { - MouseEventHandlerId m_mouseDown; - SignalHandlerId m_destroyed; +MouseEventHandlerId m_mouseDown; +SignalHandlerId m_destroyed; public: - SignalHandlerResult mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers); - typedef Member3 MouseDownCaller; - void destroyed() - { - m_mouseDown = MouseEventHandlerId(); - m_destroyed = SignalHandlerId(); - } - typedef Member DestroyedCaller; - - DTreePlanter() { - m_numModels = 0; - m_offset = 0; - m_maxPitch = 0; - m_minPitch = 0; - m_maxYaw = 0; - m_minYaw = 0; - m_setAngles = false; - m_useScale = false; - m_autoLink = false; - m_linkNum = 0; - - m_world.LoadSelectedBrushes(); - - char buffer[256]; - GetFilename( buffer, "bt/tp_ent.txt" ); - - FILE* file = fopen( buffer, "rb" ); - if(file) { - fseek( file, 0, SEEK_END ); - int len = ftell( file ); - fseek( file, 0, SEEK_SET ); - - if(len) { - char* buf = new char[len+1]; - buf[len] = '\0'; - // parser will do the cleanup, dont delete. - - fread( buf, len, 1, file ); - - CScriptParser parser; - parser.SetScript( buf ); - - ReadConfig( &parser ); - } - - fclose( file ); +SignalHandlerResult mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ); +typedef Member3 MouseDownCaller; +void destroyed(){ + m_mouseDown = MouseEventHandlerId(); + m_destroyed = SignalHandlerId(); +} +typedef Member DestroyedCaller; + +DTreePlanter() { + m_numModels = 0; + m_offset = 0; + m_maxPitch = 0; + m_minPitch = 0; + m_maxYaw = 0; + m_minYaw = 0; + m_setAngles = false; + m_useScale = false; + m_autoLink = false; + m_linkNum = 0; + + m_world.LoadSelectedBrushes(); + + char buffer[256]; + GetFilename( buffer, "bt/tp_ent.txt" ); + + FILE* file = fopen( buffer, "rb" ); + if ( file ) { + fseek( file, 0, SEEK_END ); + int len = ftell( file ); + fseek( file, 0, SEEK_SET ); + + if ( len ) { + char* buf = new char[len + 1]; + buf[len] = '\0'; + // parser will do the cleanup, dont delete. + + fread( buf, len, 1, file ); + + CScriptParser parser; + parser.SetScript( buf ); + + ReadConfig( &parser ); } - m_mouseDown = GlobalRadiant().XYWindowMouseDown_connect(makeSignalHandler3(MouseDownCaller(), *this)); - m_destroyed = GlobalRadiant().XYWindowDestroyed_connect(makeSignalHandler(DestroyedCaller(), *this)); + fclose( file ); } - virtual ~DTreePlanter() - { - if(!m_mouseDown.isNull()) - { - GlobalRadiant().XYWindowMouseDown_disconnect(m_mouseDown); - } - if(!m_destroyed.isNull()) - { - GlobalRadiant().XYWindowDestroyed_disconnect(m_destroyed); - } - } - -#define MT(t) string_equal_nocase( pToken, t ) -#define GT pToken = pScriptParser->GetToken( true ) -#define CT if(!*pToken) { return; } - - void ReadConfig( CScriptParser* pScriptParser ) { - const char* GT; - CT; - - do { - GT; - if(*pToken == '}') { - break; - } + m_mouseDown = GlobalRadiant().XYWindowMouseDown_connect( makeSignalHandler3( MouseDownCaller(), *this ) ); + m_destroyed = GlobalRadiant().XYWindowDestroyed_connect( makeSignalHandler( DestroyedCaller(), *this ) ); +} - if(MT("model")) { - if(m_numModels >= MAX_TP_MODELS) { - return; - } +virtual ~DTreePlanter(){ + if ( !m_mouseDown.isNull() ) { + GlobalRadiant().XYWindowMouseDown_disconnect( m_mouseDown ); + } + if ( !m_destroyed.isNull() ) { + GlobalRadiant().XYWindowDestroyed_disconnect( m_destroyed ); + } +} - GT; CT; +#define MT( t ) string_equal_nocase( pToken, t ) +#define GT pToken = pScriptParser->GetToken( true ) +#define CT if ( !*pToken ) { return; } - strncpy( m_trees[m_numModels++].name, pToken, MAX_QPATH ); - } else if(MT("link")) { - GT; CT; +void ReadConfig( CScriptParser* pScriptParser ) { + const char* GT; + CT; - strncpy( m_linkName, pToken, MAX_QPATH ); + do { + GT; + if ( *pToken == '}' ) { + break; + } - m_autoLink = true; - } else if(MT("entity")) { - GT; CT; + if ( MT( "model" ) ) { + if ( m_numModels >= MAX_TP_MODELS ) { + return; + } - strncpy( m_entType, pToken, MAX_QPATH ); - } else if(MT("offset")) { - GT; CT; + GT; CT; - m_offset = atoi(pToken); - } else if(MT("pitch")) { - GT; CT; + strncpy( m_trees[m_numModels++].name, pToken, MAX_QPATH ); + } + else if ( MT( "link" ) ) { + GT; CT; - m_minPitch = atoi(pToken); + strncpy( m_linkName, pToken, MAX_QPATH ); - GT; CT; + m_autoLink = true; + } + else if ( MT( "entity" ) ) { + GT; CT; - m_maxPitch = atoi(pToken); + strncpy( m_entType, pToken, MAX_QPATH ); + } + else if ( MT( "offset" ) ) { + GT; CT; - m_setAngles = true; - } else if(MT("yaw")) { - GT; CT; + m_offset = atoi( pToken ); + } + else if ( MT( "pitch" ) ) { + GT; CT; - m_minYaw = atoi(pToken); + m_minPitch = atoi( pToken ); - GT; CT; + GT; CT; - m_maxYaw = atoi(pToken); + m_maxPitch = atoi( pToken ); - m_setAngles = true; - } else if(MT("scale")) { - GT; CT; + m_setAngles = true; + } + else if ( MT( "yaw" ) ) { + GT; CT; - m_minScale = static_cast(atof(pToken)); + m_minYaw = atoi( pToken ); - GT; CT; + GT; CT; - m_maxScale = static_cast(atof(pToken)); + m_maxYaw = atoi( pToken ); - m_useScale = true; - } else if(MT("numlinks")) { - GT; CT; + m_setAngles = true; + } + else if ( MT( "scale" ) ) { + GT; CT; - m_linkNum = atoi( pToken ); - } - } while( true ); - } + m_minScale = static_cast( atof( pToken ) ); + + GT; CT; + + m_maxScale = static_cast( atof( pToken ) ); + + m_useScale = true; + } + else if ( MT( "numlinks" ) ) { + GT; CT; + + m_linkNum = atoi( pToken ); + } + } while ( true ); +} - bool FindDropPoint(vec3_t in, vec3_t out); - void DropEntsToGround( void ); - void MakeChain( int linkNum, const char* linkName ); - void SelectChain( void ); +bool FindDropPoint( vec3_t in, vec3_t out ); +void DropEntsToGround( void ); +void MakeChain( int linkNum, const char* linkName ); +void SelectChain( void ); private: - DEntity m_world; +DEntity m_world; - treeModel_t m_trees[MAX_TP_MODELS]; +treeModel_t m_trees[MAX_TP_MODELS]; - int m_numModels; - int m_offset; - int m_maxPitch; - int m_minPitch; - int m_maxYaw; - int m_minYaw; +int m_numModels; +int m_offset; +int m_maxPitch; +int m_minPitch; +int m_maxYaw; +int m_minYaw; - char m_entType[MAX_QPATH]; - char m_linkName[MAX_QPATH]; - int m_linkNum; +char m_entType[MAX_QPATH]; +char m_linkName[MAX_QPATH]; +int m_linkNum; - float m_minScale; - float m_maxScale; +float m_minScale; +float m_maxScale; - bool m_useScale; - bool m_setAngles; - bool m_autoLink; +bool m_useScale; +bool m_setAngles; +bool m_autoLink; }; #endif diff --git a/contrib/bobtoolz/DVisDrawer.cpp b/contrib/bobtoolz/DVisDrawer.cpp index 0a936941..9dc37db5 100644 --- a/contrib/bobtoolz/DVisDrawer.cpp +++ b/contrib/bobtoolz/DVisDrawer.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // BobView.cpp: implementation of the DVisDrawer class. // @@ -39,18 +39,16 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DVisDrawer::DVisDrawer() -{ +DVisDrawer::DVisDrawer(){ m_list = NULL; - constructShaders(); - GlobalShaderCache().attachRenderable(*this); + constructShaders(); + GlobalShaderCache().attachRenderable( *this ); } -DVisDrawer::~DVisDrawer() -{ - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); +DVisDrawer::~DVisDrawer(){ + GlobalShaderCache().detachRenderable( *this ); + destroyShaders(); g_VisView = NULL; } @@ -61,84 +59,80 @@ DVisDrawer::~DVisDrawer() const char* g_state_solid = "$bobtoolz/visdrawer/solid"; const char* g_state_wireframe = "$bobtoolz/visdrawer/wireframe"; -void DVisDrawer::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_COLOURCHANGE; - state.m_linewidth = 1; +void DVisDrawer::constructShaders(){ + OpenGLState state; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_COLOURCHANGE; + state.m_linewidth = 1; - GlobalOpenGLStateLibrary().insert(g_state_wireframe, state); + GlobalOpenGLStateLibrary().insert( g_state_wireframe, state ); - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_COLOURCHANGE|RENDER_SMOOTH|RENDER_DEPTHWRITE; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_FILL | RENDER_BLEND | RENDER_COLOURWRITE | RENDER_COLOURCHANGE | RENDER_SMOOTH | RENDER_DEPTHWRITE; - GlobalOpenGLStateLibrary().insert(g_state_solid, state); + GlobalOpenGLStateLibrary().insert( g_state_solid, state ); - m_shader_solid = GlobalShaderCache().capture(g_state_solid); - m_shader_wireframe = GlobalShaderCache().capture(g_state_wireframe); + m_shader_solid = GlobalShaderCache().capture( g_state_solid ); + m_shader_wireframe = GlobalShaderCache().capture( g_state_wireframe ); } -void DVisDrawer::destroyShaders() -{ - GlobalShaderCache().release(g_state_solid); - GlobalShaderCache().release(g_state_wireframe); - GlobalOpenGLStateLibrary().erase(g_state_solid); - GlobalOpenGLStateLibrary().erase(g_state_wireframe); +void DVisDrawer::destroyShaders(){ + GlobalShaderCache().release( g_state_solid ); + GlobalShaderCache().release( g_state_wireframe ); + GlobalOpenGLStateLibrary().erase( g_state_solid ); + GlobalOpenGLStateLibrary().erase( g_state_wireframe ); } -void DVisDrawer::render(RenderStateFlags state) const -{ +void DVisDrawer::render( RenderStateFlags state ) const { //bleh - std::list::const_iterator l=m_list->begin(); + std::list::const_iterator l = m_list->begin(); - for(; l != m_list->end(); l++) + for (; l != m_list->end(); l++ ) { DWinding* w = *l; - glColor4f(w->clr[0], w->clr[1], w->clr[2], 0.5f); + glColor4f( w->clr[0], w->clr[1], w->clr[2], 0.5f ); - glBegin(GL_POLYGON); - for(int i = 0; i < w->numpoints; i++) { - glVertex3f((w->p[i])[0], (w->p[i])[1], (w->p[i])[2]); + glBegin( GL_POLYGON ); + for ( int i = 0; i < w->numpoints; i++ ) { + glVertex3f( ( w->p[i] )[0], ( w->p[i] )[1], ( w->p[i] )[2] ); } glEnd(); } } -void DVisDrawer::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_list) +void DVisDrawer::renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + if ( !m_list ) { return; + } - renderer.SetState(m_shader_wireframe, Renderer::eWireframeOnly); + renderer.SetState( m_shader_wireframe, Renderer::eWireframeOnly ); - renderer.addRenderable(*this, g_matrix4_identity); + renderer.addRenderable( *this, g_matrix4_identity ); } -void DVisDrawer::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_list) +void DVisDrawer::renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if ( !m_list ) { return; + } - renderer.SetState(m_shader_solid, Renderer::eWireframeOnly); - renderer.SetState(m_shader_solid, Renderer::eFullMaterials); + renderer.SetState( m_shader_solid, Renderer::eWireframeOnly ); + renderer.SetState( m_shader_solid, Renderer::eFullMaterials ); - renderer.addRenderable(*this, g_matrix4_identity); + renderer.addRenderable( *this, g_matrix4_identity ); } -void DVisDrawer::SetList(std::list *pointList) -{ - if(m_list) +void DVisDrawer::SetList( std::list *pointList ){ + if ( m_list ) { ClearPoints(); + } m_list = pointList; } -void DVisDrawer::ClearPoints() -{ - std::list::const_iterator deadPoint=m_list->begin(); - for(; deadPoint!=m_list->end(); deadPoint++) +void DVisDrawer::ClearPoints(){ + std::list::const_iterator deadPoint = m_list->begin(); + for (; deadPoint != m_list->end(); deadPoint++ ) delete *deadPoint; m_list->clear(); } diff --git a/contrib/bobtoolz/DVisDrawer.h b/contrib/bobtoolz/DVisDrawer.h index 83a80cb1..3ec5e217 100644 --- a/contrib/bobtoolz/DVisDrawer.h +++ b/contrib/bobtoolz/DVisDrawer.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DBobView.h: interface for the DBobView class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -37,25 +37,25 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class DVisDrawer : public Renderable, public OpenGLRenderable { - Shader* m_shader_solid; - Shader* m_shader_wireframe; +Shader* m_shader_solid; +Shader* m_shader_wireframe; public: - DVisDrawer(); - virtual ~DVisDrawer(); +DVisDrawer(); +virtual ~DVisDrawer(); protected: - std::list* m_list; - int refCount; +std::list* m_list; +int refCount; public: - void ClearPoints(); - void SetList(std::list* pointList); +void ClearPoints(); +void SetList( std::list* pointList ); - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; +void render( RenderStateFlags state ) const; +void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; +void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; - void constructShaders(); - void destroyShaders(); +void constructShaders(); +void destroyShaders(); }; diff --git a/contrib/bobtoolz/DWinding.cpp b/contrib/bobtoolz/DWinding.cpp index 2068f3f8..c3d81180 100644 --- a/contrib/bobtoolz/DWinding.cpp +++ b/contrib/bobtoolz/DWinding.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DWinding.cpp: implementation of the DWinding class. // @@ -32,315 +32,323 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DWinding::DWinding() -{ +DWinding::DWinding(){ numpoints = 0; p = NULL; } -DWinding::~DWinding() -{ - if(p) +DWinding::~DWinding(){ + if ( p ) { delete[] p; + } } ////////////////////////////////////////////////////////////////////// // Implementation ////////////////////////////////////////////////////////////////////// -#define BOGUS_RANGE 4096 +#define BOGUS_RANGE 4096 -void DWinding::AllocWinding(int points) -{ +void DWinding::AllocWinding( int points ){ numpoints = points; - if(p) + if ( p ) { delete[] p; + } p = new vec3_t[points]; } -vec_t DWinding::WindingArea() -{ - vec3_t d1, d2, cross; - vec_t total; +vec_t DWinding::WindingArea(){ + vec3_t d1, d2, cross; + vec_t total; total = 0; - for (int i = 2; i < numpoints ; i++) + for ( int i = 2; i < numpoints ; i++ ) { - VectorSubtract (p[i-1], p[0], d1); - VectorSubtract (p[i], p[0], d2); + VectorSubtract( p[i - 1], p[0], d1 ); + VectorSubtract( p[i], p[0], d2 ); - CrossProduct (d1, d2, cross); + CrossProduct( d1, d2, cross ); - total += 0.5f * VectorLength ( cross ); + total += 0.5f * VectorLength( cross ); } return total; } -void DWinding::RemoveColinearPoints() -{ - vec3_t p2[MAX_POINTS_ON_WINDING]; +void DWinding::RemoveColinearPoints(){ + vec3_t p2[MAX_POINTS_ON_WINDING]; int nump = 0; - for (int i = 0; i < numpoints; i++) + for ( int i = 0; i < numpoints; i++ ) { - int j = (i+1)%numpoints; - int k = (i+numpoints-1)%numpoints; + int j = ( i + 1 ) % numpoints; + int k = ( i + numpoints - 1 ) % numpoints; - vec3_t v1, v2; - VectorSubtract (p[j], p[i], v1); - VectorSubtract (p[i], p[k], v2); - VectorNormalize(v1, v1); - VectorNormalize(v2, v2); + vec3_t v1, v2; + VectorSubtract( p[j], p[i], v1 ); + VectorSubtract( p[i], p[k], v2 ); + VectorNormalize( v1, v1 ); + VectorNormalize( v2, v2 ); - if (DotProduct(v1, v2) < 0.999) - { - VectorCopy (p[i], p2[nump]); + if ( DotProduct( v1, v2 ) < 0.999 ) { + VectorCopy( p[i], p2[nump] ); nump++; } } - if (nump == numpoints) + if ( nump == numpoints ) { return; + } - AllocWinding(nump); - memcpy (p, p2, nump*sizeof(vec3_t)); + AllocWinding( nump ); + memcpy( p, p2, nump * sizeof( vec3_t ) ); } -DPlane* DWinding::WindingPlane() -{ - DPlane* newPlane = new DPlane(p[0], p[1], p[2], NULL); +DPlane* DWinding::WindingPlane(){ + DPlane* newPlane = new DPlane( p[0], p[1], p[2], NULL ); return newPlane; } -void DWinding::WindingBounds(vec3_t mins, vec3_t maxs) -{ - if(numpoints == 0) +void DWinding::WindingBounds( vec3_t mins, vec3_t maxs ){ + if ( numpoints == 0 ) { return; + } - VectorCopy(mins, p[0]); - VectorCopy(maxs, p[0]); + VectorCopy( mins, p[0] ); + VectorCopy( maxs, p[0] ); - for (int i = 1; i < numpoints ;i++) + for ( int i = 1; i < numpoints ; i++ ) { - for (int j = 0; j < 3; j++) + for ( int j = 0; j < 3; j++ ) { vec_t v = p[i][j]; - if (v < mins[j]) + if ( v < mins[j] ) { mins[j] = v; - if (v > maxs[j]) + } + if ( v > maxs[j] ) { maxs[j] = v; + } } } } -void DWinding::WindingCentre(vec3_t centre) -{ - VectorCopy (vec3_origin, centre); - for (int i = 0; i < numpoints; i++) - VectorAdd (p[i], centre, centre); +void DWinding::WindingCentre( vec3_t centre ){ + VectorCopy( vec3_origin, centre ); + for ( int i = 0; i < numpoints; i++ ) + VectorAdd( p[i], centre, centre ); - float scale = 1.0f/numpoints; - VectorScale (centre, scale, centre); + float scale = 1.0f / numpoints; + VectorScale( centre, scale, centre ); } -DWinding* DWinding::CopyWinding() -{ +DWinding* DWinding::CopyWinding(){ DWinding* c = new DWinding; - c->AllocWinding(numpoints); - memcpy (c->p, p, numpoints*sizeof(vec3_t)); + c->AllocWinding( numpoints ); + memcpy( c->p, p, numpoints * sizeof( vec3_t ) ); return c; } -int DWinding::WindingOnPlaneSide(vec3_t normal, vec_t dist) -{ +int DWinding::WindingOnPlaneSide( vec3_t normal, vec_t dist ){ bool front = false; bool back = false; - for (int i = 0; i < numpoints; i++) + for ( int i = 0; i < numpoints; i++ ) { - vec_t d = DotProduct (p[i], normal) - dist; - if (d < -ON_EPSILON) - { - if (front) + vec_t d = DotProduct( p[i], normal ) - dist; + if ( d < -ON_EPSILON ) { + if ( front ) { return SIDE_CROSS; + } back = true; continue; } - if (d > ON_EPSILON) - { - if (back) + if ( d > ON_EPSILON ) { + if ( back ) { return SIDE_CROSS; + } front = true; continue; } } - if (back) + if ( back ) { return SIDE_BACK; - if (front) + } + if ( front ) { return SIDE_FRONT; + } return SIDE_ON; } -void DWinding::CheckWinding() -{ - vec_t *p1, *p2; - vec_t edgedist; - vec3_t dir, edgenormal; +void DWinding::CheckWinding(){ + vec_t *p1, *p2; + vec_t edgedist; + vec3_t dir, edgenormal; - if (numpoints < 3) + if ( numpoints < 3 ) { globalOutputStream() << "CheckWinding: " << numpoints << " points\n"; - + } + vec_t area = WindingArea(); - if (area < 1) + if ( area < 1 ) { globalOutputStream() << "CheckWinding: " << area << " area\n"; + } - DPlane* wPlane = WindingPlane (); + DPlane* wPlane = WindingPlane(); int i; - for (i = 0; i < numpoints; i++) + for ( i = 0; i < numpoints; i++ ) { p1 = p[i]; int j; - for (j = 0; j < 3; j++) - if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) + for ( j = 0; j < 3; j++ ) + if ( p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE ) { globalOutputStream() << "CheckFace: BOGUS_RANGE: " << p1[j] << "\n"; + } j = i + 1 == numpoints ? 0 : i + 1; - + // check the point is on the face plane - vec_t d = DotProduct (p1, wPlane->normal) - wPlane->_d; - if (d < -ON_EPSILON || d > ON_EPSILON) + vec_t d = DotProduct( p1, wPlane->normal ) - wPlane->_d; + if ( d < -ON_EPSILON || d > ON_EPSILON ) { globalOutputStream() << "CheckWinding: point off plane\n"; - + } + // check the edge isnt degenerate p2 = p[j]; - VectorSubtract (p2, p1, dir); - - if (VectorLength (dir) < ON_EPSILON) + VectorSubtract( p2, p1, dir ); + + if ( VectorLength( dir ) < ON_EPSILON ) { globalOutputStream() << "CheckWinding: degenerate edge\n"; - - CrossProduct (wPlane->normal, dir, edgenormal); - VectorNormalize (edgenormal, edgenormal); - edgedist = DotProduct (p1, edgenormal); - + } + + CrossProduct( wPlane->normal, dir, edgenormal ); + VectorNormalize( edgenormal, edgenormal ); + edgedist = DotProduct( p1, edgenormal ); + // all other points must be on front side - for (j = 0 ; j < numpoints ; j++) + for ( j = 0 ; j < numpoints ; j++ ) { - if (j == i) + if ( j == i ) { continue; + } - d = DotProduct (p[j], edgenormal); - if (d > (edgedist + ON_EPSILON)) + d = DotProduct( p[j], edgenormal ); + if ( d > ( edgedist + ON_EPSILON ) ) { globalOutputStream() << "CheckWinding: non-convex\n"; + } } } delete wPlane; } -DWinding* DWinding::ReverseWinding() -{ +DWinding* DWinding::ReverseWinding(){ DWinding* c = new DWinding; - c->AllocWinding(numpoints); + c->AllocWinding( numpoints ); - for (int i = 0; i < numpoints ; i++) - VectorCopy (p[numpoints-1-i], c->p[i]); + for ( int i = 0; i < numpoints ; i++ ) + VectorCopy( p[numpoints - 1 - i], c->p[i] ); return c; } -bool DWinding::ChopWindingInPlace(DPlane* chopPlane, vec_t epsilon) -{ - vec_t dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - vec_t *p1, *p2; - vec3_t mid; +bool DWinding::ChopWindingInPlace( DPlane* chopPlane, vec_t epsilon ){ + vec_t dists[MAX_POINTS_ON_WINDING + 4]; + int sides[MAX_POINTS_ON_WINDING + 4]; + int counts[3]; + vec_t *p1, *p2; + vec3_t mid; counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - int i; - for (i = 0; i < numpoints; i++) + int i; + for ( i = 0; i < numpoints; i++ ) { - vec_t dot = DotProduct (p[i], chopPlane->normal); + vec_t dot = DotProduct( p[i], chopPlane->normal ); dot -= chopPlane->_d; dists[i] = dot; - - if (dot > epsilon) + + if ( dot > epsilon ) { sides[i] = SIDE_FRONT; - else if (dot < -epsilon) + } + else if ( dot < -epsilon ) { sides[i] = SIDE_BACK; - else + } + else{ sides[i] = SIDE_ON; + } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; - - if (!counts[0]) - { + + if ( !counts[0] ) { delete this; return false; } - if (!counts[1]) + if ( !counts[1] ) { return true; + } - int maxpts = numpoints+4; // cant use counts[0]+2 because - // of fp grouping errors + int maxpts = numpoints + 4; // cant use counts[0]+2 because + // of fp grouping errors DWinding* f = new DWinding; - f->AllocWinding(maxpts); + f->AllocWinding( maxpts ); f->numpoints = 0; - - for (i = 0; i < numpoints; i++) + + for ( i = 0; i < numpoints; i++ ) { p1 = p[i]; - - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_ON ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; continue; } - - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_FRONT ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; } - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; - - // generate a split point - p2 = p[(i+1)%numpoints]; - - vec_t dot = dists[i] / (dists[i]-dists[i+1]); - for (int j = 0; j < 3; j++) + } + + // generate a split point + p2 = p[( i + 1 ) % numpoints]; + + vec_t dot = dists[i] / ( dists[i] - dists[i + 1] ); + for ( int j = 0; j < 3; j++ ) { - if (chopPlane->normal[j] == 1) + if ( chopPlane->normal[j] == 1 ) { mid[j] = chopPlane->_d; - else if (chopPlane->normal[j] == -1) + } + else if ( chopPlane->normal[j] == -1 ) { mid[j] = -chopPlane->_d; - else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + } + else{ + mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); + } } - - VectorCopy (mid, f->p[f->numpoints]); + + VectorCopy( mid, f->p[f->numpoints] ); f->numpoints++; } - - if (f->numpoints > maxpts) + + if ( f->numpoints > maxpts ) { globalOutputStream() << "ClipWinding: points exceeded estimate\n"; - if (f->numpoints > MAX_POINTS_ON_WINDING) + } + if ( f->numpoints > MAX_POINTS_ON_WINDING ) { globalOutputStream() << "ClipWinding: MAX_POINTS_ON_WINDING\n"; + } delete[] p; p = f->p; @@ -349,128 +357,130 @@ bool DWinding::ChopWindingInPlace(DPlane* chopPlane, vec_t epsilon) return true; } -void DWinding::ClipWindingEpsilon(DPlane* chopPlane, vec_t epsilon, DWinding **front, DWinding **back) -{ - vec_t dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - vec_t *p1, *p2; - vec3_t mid; - +void DWinding::ClipWindingEpsilon( DPlane* chopPlane, vec_t epsilon, DWinding **front, DWinding **back ){ + vec_t dists[MAX_POINTS_ON_WINDING + 4]; + int sides[MAX_POINTS_ON_WINDING + 4]; + int counts[3]; + vec_t *p1, *p2; + vec3_t mid; + counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - int i; - for (i = 0; i < numpoints; i++) + int i; + for ( i = 0; i < numpoints; i++ ) { - vec_t dot = -chopPlane->DistanceToPoint(p[i]); + vec_t dot = -chopPlane->DistanceToPoint( p[i] ); dists[i] = dot; - - if (dot > epsilon) + + if ( dot > epsilon ) { sides[i] = SIDE_FRONT; - else if (dot < -epsilon) + } + else if ( dot < -epsilon ) { sides[i] = SIDE_BACK; - else + } + else{ sides[i] = SIDE_ON; + } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; - + *front = *back = NULL; - if (!counts[0]) - { + if ( !counts[0] ) { *back = CopyWinding(); return; } - if (!counts[1]) - { + if ( !counts[1] ) { *front = CopyWinding(); return; } - int maxpts = numpoints+4; // cant use counts[0]+2 because - // of fp grouping errors + int maxpts = numpoints + 4; // cant use counts[0]+2 because + // of fp grouping errors DWinding* f = new DWinding; DWinding* b = new DWinding; - f->AllocWinding(maxpts); + f->AllocWinding( maxpts ); f->numpoints = 0; - b->AllocWinding(maxpts); + b->AllocWinding( maxpts ); b->numpoints = 0; - + *front = f; *back = b; - for (i = 0; i < numpoints ; i++) + for ( i = 0; i < numpoints ; i++ ) { p1 = p[i]; - - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_ON ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; - VectorCopy (p1, b->p[b->numpoints]); + VectorCopy( p1, b->p[b->numpoints] ); b->numpoints++; continue; } - - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_FRONT ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; } - if (sides[i] == SIDE_BACK) - { - VectorCopy (p1, b->p[b->numpoints]); + if ( sides[i] == SIDE_BACK ) { + VectorCopy( p1, b->p[b->numpoints] ); b->numpoints++; } - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; - - // generate a split point - p2 = p[(i+1)%numpoints]; - - vec_t dot = dists[i] / (dists[i]-dists[i+1]); - for (int j = 0; j < 3; j++) + } + + // generate a split point + p2 = p[( i + 1 ) % numpoints]; + + vec_t dot = dists[i] / ( dists[i] - dists[i + 1] ); + for ( int j = 0; j < 3; j++ ) { - if (chopPlane->normal[j] == 1) + if ( chopPlane->normal[j] == 1 ) { mid[j] = chopPlane->_d; - else if (chopPlane->normal[j] == -1) + } + else if ( chopPlane->normal[j] == -1 ) { mid[j] = -chopPlane->_d; - else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + } + else{ + mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); + } } - - VectorCopy (mid, f->p[f->numpoints]); + + VectorCopy( mid, f->p[f->numpoints] ); f->numpoints++; - VectorCopy (mid, b->p[b->numpoints]); + VectorCopy( mid, b->p[b->numpoints] ); b->numpoints++; } - - if (f->numpoints > maxpts || b->numpoints > maxpts) + + if ( f->numpoints > maxpts || b->numpoints > maxpts ) { globalOutputStream() << "ClipWinding: points exceeded estimate\n"; - if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING) + } + if ( f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING ) { globalOutputStream() << "ClipWinding: MAX_POINTS_ON_WINDING\n"; + } } -bool DWinding::ChopWinding(DPlane* chopPlane) -{ +bool DWinding::ChopWinding( DPlane* chopPlane ){ DWinding *f, *b; - ClipWindingEpsilon (chopPlane, (float)ON_EPSILON, &f, &b); + ClipWindingEpsilon( chopPlane, (float)ON_EPSILON, &f, &b ); - if (b) - delete (b); + if ( b ) { + delete ( b ); + } - if(!f) - { + if ( !f ) { delete this; return false; } diff --git a/contrib/bobtoolz/DWinding.h b/contrib/bobtoolz/DWinding.h index 52846aab..94a28096 100644 --- a/contrib/bobtoolz/DWinding.h +++ b/contrib/bobtoolz/DWinding.h @@ -1,27 +1,27 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DWinding.h: interface for the DWinding class. // ////////////////////////////////////////////////////////////////////// -#if !defined(AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -32,39 +32,39 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class DPlane; -class DWinding +class DWinding { public: - DWinding(); - virtual ~DWinding(); +DWinding(); +virtual ~DWinding(); - void AllocWinding(int points); +void AllocWinding( int points ); - bool ChopWinding(DPlane* chopPlane); - bool ChopWindingInPlace(DPlane* chopPlane, vec_t ON_EPSILON); - void ClipWindingEpsilon(DPlane* chopPlane, vec_t epsilon, DWinding** front, DWinding** back); +bool ChopWinding( DPlane* chopPlane ); +bool ChopWindingInPlace( DPlane* chopPlane, vec_t ON_EPSILON ); +void ClipWindingEpsilon( DPlane* chopPlane, vec_t epsilon, DWinding** front, DWinding** back ); - void CheckWinding(); - void WindingCentre(vec3_t centre); - void WindingBounds(vec3_t mins, vec3_t maxs); - void RemoveColinearPoints(); +void CheckWinding(); +void WindingCentre( vec3_t centre ); +void WindingBounds( vec3_t mins, vec3_t maxs ); +void RemoveColinearPoints(); - DWinding* ReverseWinding(); - DWinding* CopyWinding(); - DPlane* WindingPlane(); +DWinding* ReverseWinding(); +DWinding* CopyWinding(); +DPlane* WindingPlane(); - int WindingOnPlaneSide(vec3_t normal, vec_t dist); +int WindingOnPlaneSide( vec3_t normal, vec_t dist ); - vec_t WindingArea(); +vec_t WindingArea(); // members - int numpoints; - vec3_t* p; - vec3_t clr; +int numpoints; +vec3_t* p; +vec3_t clr; }; -#define MAX_POINTS_ON_WINDING 64 +#define MAX_POINTS_ON_WINDING 64 -#define ON_EPSILON 0.01 +#define ON_EPSILON 0.01 #endif // !defined(AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/contrib/bobtoolz/ScriptParser.cpp b/contrib/bobtoolz/ScriptParser.cpp index 826613e4..d53c7fe8 100644 --- a/contrib/bobtoolz/ScriptParser.cpp +++ b/contrib/bobtoolz/ScriptParser.cpp @@ -1,73 +1,73 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "ScriptParser.h" #include -CScriptParser::CScriptParser(void): - m_pScript(NULL), - m_pScriptSection(NULL), - m_pLastScriptSection(NULL), - m_pToken(NULL) { +CScriptParser::CScriptParser( void ) : + m_pScript( NULL ), + m_pScriptSection( NULL ), + m_pLastScriptSection( NULL ), + m_pToken( NULL ) { ClearBuffer(); } -CScriptParser::~CScriptParser(void) { +CScriptParser::~CScriptParser( void ) { ClearBuffer(); } -void CScriptParser::ClearBuffer(void) { - if(m_pScript) { +void CScriptParser::ClearBuffer( void ) { + if ( m_pScript ) { delete[] m_pScript; m_pScript = NULL; } - if(m_pToken) { + if ( m_pToken ) { delete[] m_pToken; m_pToken = NULL; } m_pScriptSection = NULL; m_pLastScriptSection = NULL; - memset(m_breakChars, 0, sizeof(m_breakChars)); + memset( m_breakChars, 0, sizeof( m_breakChars ) ); } -const char* CScriptParser::MakeToken(const char* pToken) { - if(m_pToken) { +const char* CScriptParser::MakeToken( const char* pToken ) { + if ( m_pToken ) { delete[] m_pToken; m_pToken = NULL; } - if(!pToken) { + if ( !pToken ) { pToken = ""; } - int len = static_cast(strlen(pToken)); + int len = static_cast( strlen( pToken ) ); m_pToken = new char[len + 1]; m_pToken[len] = '\0'; - strcpy(m_pToken, pToken); + strcpy( m_pToken, pToken ); return m_pToken; } #define MAX_TOKEN_STRING 1024 // Should NEVER return NULL -const char* CScriptParser::GetToken(bool bAllowLinebreaks) { +const char* CScriptParser::GetToken( bool bAllowLinebreaks ) { int c = 0, len; char token[MAX_TOKEN_STRING]; bool bNewLines = false; @@ -77,27 +77,28 @@ const char* CScriptParser::GetToken(bool bAllowLinebreaks) { len = 0; *token = '\0'; - if(!m_pScript || !m_pScriptSection) { - return MakeToken(token); + if ( !m_pScript || !m_pScriptSection ) { + return MakeToken( token ); } while ( true ) { SkipWhitespace( &bNewLines ); if ( !*m_pScriptSection ) { - return MakeToken(token); + return MakeToken( token ); } if ( bNewLines && !bAllowLinebreaks ) { - return MakeToken(token); + return MakeToken( token ); } c = *m_pScriptSection; - + if ( c == '/' && m_pScriptSection[1] == '/' ) { // C style comments m_pScriptSection += 2; - while (*m_pScriptSection && *m_pScriptSection != '\n') { + while ( *m_pScriptSection && *m_pScriptSection != '\n' ) { m_pScriptSection++; } - } else if ( c=='/' && m_pScriptSection[1] == '*' ) { // C++ style comments + } + else if ( c == '/' && m_pScriptSection[1] == '*' ) { // C++ style comments m_pScriptSection += 2; while ( *m_pScriptSection && ( *m_pScriptSection != '*' || m_pScriptSection[1] != '/' ) ) { m_pScriptSection++; @@ -105,20 +106,21 @@ const char* CScriptParser::GetToken(bool bAllowLinebreaks) { if ( *m_pScriptSection ) { m_pScriptSection += 2; } - } else { + } + else { break; } } - if (c == '\"') { + if ( c == '\"' ) { m_pScriptSection++; while ( true ) { c = *m_pScriptSection++; - if (c=='\"' || !c) { + if ( c == '\"' || !c ) { token[len] = 0; - return MakeToken(token); + return MakeToken( token ); } - if (len < MAX_TOKEN_STRING) { + if ( len < MAX_TOKEN_STRING ) { token[len] = c; len++; } @@ -126,72 +128,73 @@ const char* CScriptParser::GetToken(bool bAllowLinebreaks) { } do { - if(len > 0 && IsBreakChar(*m_pScriptSection)) { + if ( len > 0 && IsBreakChar( *m_pScriptSection ) ) { break; } - if (len < MAX_TOKEN_STRING) { + if ( len < MAX_TOKEN_STRING ) { token[len] = c; len++; } m_pScriptSection++; - if(IsBreakChar(c)) { + if ( IsBreakChar( c ) ) { break; } c = *m_pScriptSection; - } while (c > 32); + } while ( c > 32 ); - if (len == MAX_TOKEN_STRING) { + if ( len == MAX_TOKEN_STRING ) { len = 0; } token[len] = 0; - return MakeToken(token); + return MakeToken( token ); } -void CScriptParser::SkipWhitespace(bool* pbNewLines) { +void CScriptParser::SkipWhitespace( bool* pbNewLines ) { int c; - if(!m_pScript || !m_pScriptSection) { + if ( !m_pScript || !m_pScriptSection ) { return; } - while( (c = *m_pScriptSection) <= ' ') { - if( !c ) { + while ( ( c = *m_pScriptSection ) <= ' ' ) { + if ( !c ) { return; } - if( c == '\n' ) { + if ( c == '\n' ) { *pbNewLines = true; } m_pScriptSection++; } } -void CScriptParser::SkipBracedSection(void) { - const char *token; - int depth; +void CScriptParser::SkipBracedSection( void ) { + const char *token; + int depth; depth = 0; do { token = GetToken( true ); - if( token[1] == 0 ) { - if( *token == '{' ) { + if ( token[1] == 0 ) { + if ( *token == '{' ) { depth++; - } else if( *token == '}' ) { + } + else if ( *token == '}' ) { depth--; } } - } while( depth && *m_pScriptSection ); + } while ( depth && *m_pScriptSection ); } -void CScriptParser::SkipRestOfLine(void) { - char *p; - int c; +void CScriptParser::SkipRestOfLine( void ) { + char *p; + int c; p = m_pScriptSection; - while ( (c = *p++) != 0 ) { + while ( ( c = *p++ ) != 0 ) { if ( c == '\n' ) { break; } @@ -199,16 +202,16 @@ void CScriptParser::SkipRestOfLine(void) { m_pScriptSection = p; } -void CScriptParser::UndoGetToken(void) { - if(!m_pLastScriptSection) { +void CScriptParser::UndoGetToken( void ) { + if ( !m_pLastScriptSection ) { return; } m_pScriptSection = m_pLastScriptSection; m_pLastScriptSection = NULL; } -void CScriptParser::ResetParseSession(void) { - if(!m_pScript) { +void CScriptParser::ResetParseSession( void ) { + if ( !m_pScript ) { return; } @@ -216,43 +219,43 @@ void CScriptParser::ResetParseSession(void) { m_pLastScriptSection = NULL; } -char* CScriptParser::GetBufferCopy(void) { - if(!m_pScript) { +char* CScriptParser::GetBufferCopy( void ) { + if ( !m_pScript ) { return NULL; } - int len = static_cast(strlen(m_pScript)); + int len = static_cast( strlen( m_pScript ) ); char* pBuffer = new char[len + 1]; - strcpy(pBuffer, m_pScript); + strcpy( pBuffer, m_pScript ); return pBuffer; } -int CScriptParser::GetTokenOffset(void) { - if(!m_pScript || !m_pScriptSection) { +int CScriptParser::GetTokenOffset( void ) { + if ( !m_pScript || !m_pScriptSection ) { return 0; } - return static_cast(m_pScriptSection - m_pScript); + return static_cast( m_pScriptSection - m_pScript ); } -void CScriptParser::LoadScript(const char* pScript) { +void CScriptParser::LoadScript( const char* pScript ) { ClearBuffer(); - int len = static_cast(strlen(pScript)); - if(len <= 0) { + int len = static_cast( strlen( pScript ) ); + if ( len <= 0 ) { return; } m_pScript = new char[len + 1]; m_pScript[len] = '\0'; - strcpy(m_pScript, pScript); + strcpy( m_pScript, pScript ); m_pScriptSection = m_pScript; } -void CScriptParser::AddBreakChar(char c) { - for(int i = 0; i < SP_MAX_BREAKCHARS; i++) { - if(!m_breakChars[i]) { +void CScriptParser::AddBreakChar( char c ) { + for ( int i = 0; i < SP_MAX_BREAKCHARS; i++ ) { + if ( !m_breakChars[i] ) { m_breakChars[i] = c; return; } @@ -261,23 +264,23 @@ void CScriptParser::AddBreakChar(char c) { // TODO: Error: max break chars hit } -bool CScriptParser::IsBreakChar(char c) { - for(int i = 0; i < SP_MAX_BREAKCHARS; i++) { - if(!m_breakChars[i]) { +bool CScriptParser::IsBreakChar( char c ) { + for ( int i = 0; i < SP_MAX_BREAKCHARS; i++ ) { + if ( !m_breakChars[i] ) { return false; } - if(m_breakChars[i] == c) { + if ( m_breakChars[i] == c ) { return true; } } return false; } -void CScriptParser::SetScript(char* pScript) { +void CScriptParser::SetScript( char* pScript ) { ClearBuffer(); - int len = static_cast(strlen(pScript)); - if(len <= 0) { + int len = static_cast( strlen( pScript ) ); + if ( len <= 0 ) { return; } diff --git a/contrib/bobtoolz/ScriptParser.h b/contrib/bobtoolz/ScriptParser.h index 27eb6df7..b9ec823d 100644 --- a/contrib/bobtoolz/ScriptParser.h +++ b/contrib/bobtoolz/ScriptParser.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef _SCRIPTPARSER_H_ @@ -28,33 +28,33 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class CScriptParser //: public IScriptParser { public: - CScriptParser(void); - ~CScriptParser(void); +CScriptParser( void ); +~CScriptParser( void ); private: - char m_breakChars[SP_MAX_BREAKCHARS]; - char* m_pScript; - char* m_pScriptSection; - char* m_pLastScriptSection; - char* m_pToken; - - void SkipWhitespace(bool* pbNewLines); - void ClearBuffer(void); - const char* MakeToken(const char* pToken); - bool IsBreakChar(char c); +char m_breakChars[SP_MAX_BREAKCHARS]; +char* m_pScript; +char* m_pScriptSection; +char* m_pLastScriptSection; +char* m_pToken; + +void SkipWhitespace( bool* pbNewLines ); +void ClearBuffer( void ); +const char* MakeToken( const char* pToken ); +bool IsBreakChar( char c ); public: - const char* GetToken(bool bAllowLinebreaks); - void SkipBracedSection(void); - void SkipRestOfLine(void); - void UndoGetToken(void); - void ResetParseSession(void); +const char* GetToken( bool bAllowLinebreaks ); +void SkipBracedSection( void ); +void SkipRestOfLine( void ); +void UndoGetToken( void ); +void ResetParseSession( void ); - char* GetBufferCopy(void); - int GetTokenOffset(void); +char* GetBufferCopy( void ); +int GetTokenOffset( void ); - void LoadScript(const char* pScript); - void SetScript(char* pScript); +void LoadScript( const char* pScript ); +void SetScript( char* pScript ); - void AddBreakChar(char c); +void AddBreakChar( char c ); private: }; diff --git a/contrib/bobtoolz/StdAfx.cpp b/contrib/bobtoolz/StdAfx.cpp index 1a02f66b..5c7495fa 100644 --- a/contrib/bobtoolz/StdAfx.cpp +++ b/contrib/bobtoolz/StdAfx.cpp @@ -1,25 +1,24 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // stdafx.cpp : source file that includes just the standard includes // plugin.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "StdAfx.h" - diff --git a/contrib/bobtoolz/StdAfx.h b/contrib/bobtoolz/StdAfx.h index b8897f39..cfce5a4e 100644 --- a/contrib/bobtoolz/StdAfx.h +++ b/contrib/bobtoolz/StdAfx.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef __STDAFX_BOBTOOLZ__ #define __STDAFX_BOBTOOLZ__ diff --git a/contrib/bobtoolz/bobToolz-GTK.cpp b/contrib/bobtoolz/bobToolz-GTK.cpp index 78f4a5b3..d7893955 100644 --- a/contrib/bobtoolz/bobToolz-GTK.cpp +++ b/contrib/bobtoolz/bobToolz-GTK.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ @@ -34,25 +34,23 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "dialogs/dialogs-gtk.h" #include "../../libs/cmdlib.h" -void BobToolz_construct() -{ +void BobToolz_construct(){ } -void BobToolz_destroy() -{ - if(g_PathView) { +void BobToolz_destroy(){ + if ( g_PathView ) { delete g_PathView; g_PathView = NULL; } - if(g_VisView) { + if ( g_VisView ) { delete g_VisView; g_VisView = NULL; } - if(g_TrainView) { + if ( g_TrainView ) { delete g_TrainView; g_TrainView = NULL; } - if(g_TreePlanter) { + if ( g_TreePlanter ) { delete g_TreePlanter; g_TreePlanter = NULL; } @@ -67,7 +65,7 @@ static char* PLUGIN_COMMANDS = "About...,-,Reset Textures...,PitOMatic,-,Vis Vie // globals GtkWidget *g_pRadiantWnd = NULL; -static const char *PLUGIN_ABOUT = "bobToolz for SDRadiant\n" +static const char *PLUGIN_ABOUT = "bobToolz for SDRadiant\n" "by digibob (digibob@splashdamage.com)\n" "http://www.splashdamage.com\n\n" "Additional Contributors:\n" @@ -87,55 +85,73 @@ extern "C" const char* QERPlug_GetCommandList() { return PLUGIN_COMMANDS; } -extern "C" void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) { +extern "C" void QERPlug_Dispatch( const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ) { LoadLists(); - if( string_equal_nocase( p, "brush cleanup" ) ) { - DoFixBrushes(); - } else if( string_equal_nocase( p, "polygon builder" ) ) { - DoPolygonsTB(); - } else if( string_equal_nocase( p, "caulk selection" ) ) { - DoCaulkSelection(); - } else if( string_equal_nocase( p, "tree planter" ) ) { - DoTreePlanter(); - } else if( string_equal_nocase( p, "plot splines" ) ) { - DoTrainPathPlot(); - } else if( string_equal_nocase( p, "drop entity" ) ) { - DoDropEnts(); - } else if( string_equal_nocase( p, "merge patches" ) ) { - DoMergePatches(); - } else if( string_equal_nocase( p, "split patches" ) ) { - DoSplitPatch(); - } else if( string_equal_nocase( p, "split patches rows" ) ) { - DoSplitPatchRows(); - } else if( string_equal_nocase( p, "split patches cols" ) ) { - DoSplitPatchCols(); - } else if( string_equal_nocase( p, "turn edge" ) ) { - DoFlipTerrain(); - } else if( string_equal_nocase(p, "reset textures...") ) { + if ( string_equal_nocase( p, "brush cleanup" ) ) { + DoFixBrushes(); + } + else if ( string_equal_nocase( p, "polygon builder" ) ) { + DoPolygonsTB(); + } + else if ( string_equal_nocase( p, "caulk selection" ) ) { + DoCaulkSelection(); + } + else if ( string_equal_nocase( p, "tree planter" ) ) { + DoTreePlanter(); + } + else if ( string_equal_nocase( p, "plot splines" ) ) { + DoTrainPathPlot(); + } + else if ( string_equal_nocase( p, "drop entity" ) ) { + DoDropEnts(); + } + else if ( string_equal_nocase( p, "merge patches" ) ) { + DoMergePatches(); + } + else if ( string_equal_nocase( p, "split patches" ) ) { + DoSplitPatch(); + } + else if ( string_equal_nocase( p, "split patches rows" ) ) { + DoSplitPatchRows(); + } + else if ( string_equal_nocase( p, "split patches cols" ) ) { + DoSplitPatchCols(); + } + else if ( string_equal_nocase( p, "turn edge" ) ) { + DoFlipTerrain(); + } + else if ( string_equal_nocase( p, "reset textures..." ) ) { DoResetTextures(); - } else if( string_equal_nocase(p, "pitomatic") ) { + } + else if ( string_equal_nocase( p, "pitomatic" ) ) { DoPitBuilder(); - } else if( string_equal_nocase(p, "vis viewer") ) { + } + else if ( string_equal_nocase( p, "vis viewer" ) ) { DoVisAnalyse(); - } else if( string_equal_nocase(p, "stair builder...") ) { + } + else if ( string_equal_nocase( p, "stair builder..." ) ) { DoBuildStairs(); - } else if( string_equal_nocase(p, "door builder...") ) { + } + else if ( string_equal_nocase( p, "door builder..." ) ) { DoBuildDoors(); - } else if( string_equal_nocase(p, "intersect...") ) { + } + else if ( string_equal_nocase( p, "intersect..." ) ) { DoIntersect(); - } else if( string_equal_nocase(p, "make chain...") ) { + } + else if ( string_equal_nocase( p, "make chain..." ) ) { DoMakeChain(); - } else if( string_equal_nocase(p, "path plotter...") ) { + } + else if ( string_equal_nocase( p, "path plotter..." ) ) { DoPathPlotter(); - } else if( string_equal_nocase(p, "about...") ) { - DoMessageBox(PLUGIN_ABOUT, "About", eMB_OK); + } + else if ( string_equal_nocase( p, "about..." ) ) { + DoMessageBox( PLUGIN_ABOUT, "About", eMB_OK ); } } -const char* QERPlug_GetCommandTitleList() -{ - return ""; +const char* QERPlug_GetCommandTitleList(){ + return ""; } @@ -148,99 +164,93 @@ std::size_t ToolbarButtonCount( void ) { class CBobtoolzToolbarButton : public IToolbarButton { public: - virtual const char* getImage() const - { - switch( mIndex ) { - case 0: return "bobtoolz_cleanup.bmp"; - case 1: return "bobtoolz_poly.bmp"; - case 2: return "bobtoolz_caulk.bmp"; - case 3: return ""; - case 4: return "bobtoolz_treeplanter.bmp"; - case 5: return "bobtoolz_trainpathplot.bmp"; - case 6: return "bobtoolz_dropent.bmp"; - case 7: return ""; - case 8: return "bobtoolz_merge.bmp"; - case 9: return "bobtoolz_split.bmp"; - case 10: return "bobtoolz_splitrow.bmp"; - case 11: return "bobtoolz_splitcol.bmp"; - case 12: return ""; - case 13: return "bobtoolz_turnedge.bmp"; - } - return NULL; - } - virtual EType getType() const - { - switch( mIndex ) { - case 3: return eSpace; - case 4: return eToggleButton; - case 7: return eSpace; - case 12: return eSpace; - default: return eButton; - } - } - virtual const char* getText() const - { - switch( mIndex ) { - case 0: return "Cleanup"; - case 1: return "Polygons"; - case 2: return "Caulk"; - case 4: return "Tree Planter"; - case 5: return "Plot Splines"; - case 6: return "Drop Entity"; - case 8: return "Merge 2 Patches"; - case 9: return "Split Patch"; - case 10: return "Split Patch Rows"; - case 11: return "Split Patch Columns"; - case 13: return "Flip Terrain"; - } - return NULL; - } - virtual const char* getTooltip() const - { - switch( mIndex ) { - case 0: return "Brush Cleanup"; - case 1: return "Polygons"; - case 2: return "Caulk selection"; - case 4: return "Tree Planter"; - case 5: return "Plot Splines"; - case 6: return "Drop Entity"; - case 8: return "Merge 2 Patches"; - case 9: return "Split Patch"; - case 10: return "Split Patch Rows"; - case 11: return "Split Patch Columns"; - case 13: return "Flip Terrain (Turn Edge)"; - } - return NULL; - } - - virtual void activate() const - { - LoadLists(); - - switch( mIndex ) { - case 0: DoFixBrushes(); break; - case 1: DoPolygonsTB(); break; - case 2: DoCaulkSelection(); break; - case 4: DoTreePlanter(); break; - case 5: DoTrainPathPlot(); break; - case 6: DoDropEnts(); break; - case 8: DoMergePatches(); break; - case 9: DoSplitPatch(); break; - case 10: DoSplitPatchRows(); break; - case 11: DoSplitPatchCols(); break; - case 13: DoFlipTerrain(); break; - } - } - - std::size_t mIndex; +virtual const char* getImage() const { + switch ( mIndex ) { + case 0: return "bobtoolz_cleanup.bmp"; + case 1: return "bobtoolz_poly.bmp"; + case 2: return "bobtoolz_caulk.bmp"; + case 3: return ""; + case 4: return "bobtoolz_treeplanter.bmp"; + case 5: return "bobtoolz_trainpathplot.bmp"; + case 6: return "bobtoolz_dropent.bmp"; + case 7: return ""; + case 8: return "bobtoolz_merge.bmp"; + case 9: return "bobtoolz_split.bmp"; + case 10: return "bobtoolz_splitrow.bmp"; + case 11: return "bobtoolz_splitcol.bmp"; + case 12: return ""; + case 13: return "bobtoolz_turnedge.bmp"; + } + return NULL; +} +virtual EType getType() const { + switch ( mIndex ) { + case 3: return eSpace; + case 4: return eToggleButton; + case 7: return eSpace; + case 12: return eSpace; + default: return eButton; + } +} +virtual const char* getText() const { + switch ( mIndex ) { + case 0: return "Cleanup"; + case 1: return "Polygons"; + case 2: return "Caulk"; + case 4: return "Tree Planter"; + case 5: return "Plot Splines"; + case 6: return "Drop Entity"; + case 8: return "Merge 2 Patches"; + case 9: return "Split Patch"; + case 10: return "Split Patch Rows"; + case 11: return "Split Patch Columns"; + case 13: return "Flip Terrain"; + } + return NULL; +} +virtual const char* getTooltip() const { + switch ( mIndex ) { + case 0: return "Brush Cleanup"; + case 1: return "Polygons"; + case 2: return "Caulk selection"; + case 4: return "Tree Planter"; + case 5: return "Plot Splines"; + case 6: return "Drop Entity"; + case 8: return "Merge 2 Patches"; + case 9: return "Split Patch"; + case 10: return "Split Patch Rows"; + case 11: return "Split Patch Columns"; + case 13: return "Flip Terrain (Turn Edge)"; + } + return NULL; +} + +virtual void activate() const { + LoadLists(); + + switch ( mIndex ) { + case 0: DoFixBrushes(); break; + case 1: DoPolygonsTB(); break; + case 2: DoCaulkSelection(); break; + case 4: DoTreePlanter(); break; + case 5: DoTrainPathPlot(); break; + case 6: DoDropEnts(); break; + case 8: DoMergePatches(); break; + case 9: DoSplitPatch(); break; + case 10: DoSplitPatchRows(); break; + case 11: DoSplitPatchCols(); break; + case 13: DoFlipTerrain(); break; + } +} + +std::size_t mIndex; }; CBobtoolzToolbarButton g_bobtoolzToolbarButtons[NUM_TOOLBARBUTTONS]; -const IToolbarButton* GetToolbarButton(std::size_t index) -{ - g_bobtoolzToolbarButtons[index].mIndex = index; - return &g_bobtoolzToolbarButtons[index]; +const IToolbarButton* GetToolbarButton( std::size_t index ){ + g_bobtoolzToolbarButtons[index].mIndex = index; + return &g_bobtoolzToolbarButtons[index]; } @@ -258,55 +268,51 @@ const IToolbarButton* GetToolbarButton(std::size_t index) #include "iplugin.h" class BobToolzPluginDependencies : - public GlobalRadiantModuleRef, - public GlobalUndoModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalSelectionModuleRef, - public GlobalEntityModuleRef, - public GlobalEntityClassManagerModuleRef, - public GlobalShadersModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalBrushModuleRef, - public GlobalPatchModuleRef, - public GlobalOpenGLModuleRef, - public GlobalOpenGLStateLibraryModuleRef + public GlobalRadiantModuleRef, + public GlobalUndoModuleRef, + public GlobalSceneGraphModuleRef, + public GlobalSelectionModuleRef, + public GlobalEntityModuleRef, + public GlobalEntityClassManagerModuleRef, + public GlobalShadersModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalBrushModuleRef, + public GlobalPatchModuleRef, + public GlobalOpenGLModuleRef, + public GlobalOpenGLStateLibraryModuleRef { public: - BobToolzPluginDependencies() : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")), - GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")), - GlobalPatchModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("patchtypes")), - GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")) - { - } +BobToolzPluginDependencies() : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ), + GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ), + GlobalPatchModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "patchtypes" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ +} }; class BobToolzPluginModule : public TypeSystemRef { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "bobToolz"); - - BobToolzPluginModule() - { - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - - BobToolz_construct(); - } - ~BobToolzPluginModule() - { - BobToolz_destroy(); - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "bobToolz" ); + +BobToolzPluginModule(){ + m_plugin.m_pfnQERPlug_Init = QERPlug_Init; + m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; + m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + + BobToolz_construct(); +} +~BobToolzPluginModule(){ + BobToolz_destroy(); +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonBobToolzPluginModule; @@ -315,31 +321,28 @@ SingletonBobToolzPluginModule g_BobToolzPluginModule; class BobToolzToolbarDependencies : - public ModuleRef<_QERPluginTable> + public ModuleRef<_QERPluginTable> { public: - BobToolzToolbarDependencies() : - ModuleRef<_QERPluginTable>("bobToolz") - { - } +BobToolzToolbarDependencies() : + ModuleRef<_QERPluginTable>( "bobToolz" ){ +} }; class BobToolzToolbarModule : public TypeSystemRef { - _QERPlugToolbarTable m_table; +_QERPlugToolbarTable m_table; public: - typedef _QERPlugToolbarTable Type; - STRING_CONSTANT(Name, "bobToolz"); - - BobToolzToolbarModule() - { - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; - } - _QERPlugToolbarTable* getTable() - { - return &m_table; - } +typedef _QERPlugToolbarTable Type; +STRING_CONSTANT( Name, "bobToolz" ); + +BobToolzToolbarModule(){ + m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; + m_table.m_pfnGetToolbarButton = GetToolbarButton; +} +_QERPlugToolbarTable* getTable(){ + return &m_table; +} }; typedef SingletonModule SingletonBobToolzToolbarModule; @@ -347,10 +350,9 @@ typedef SingletonModule Sing SingletonBobToolzToolbarModule g_BobToolzToolbarModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); - g_BobToolzPluginModule.selfRegister(); - g_BobToolzToolbarModule.selfRegister(); + g_BobToolzPluginModule.selfRegister(); + g_BobToolzToolbarModule.selfRegister(); } diff --git a/contrib/bobtoolz/bobToolz.h b/contrib/bobtoolz/bobToolz.h index 6101e877..4b80ee73 100644 --- a/contrib/bobtoolz/bobToolz.h +++ b/contrib/bobtoolz/bobToolz.h @@ -1,26 +1,26 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // plugin.h : main header file for the PLUGIN DLL // -#if !defined(AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) +#if !defined( AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ ) #define AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ #if _MSC_VER >= 1000 @@ -31,7 +31,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #error include 'StdAfx.h' before including this file for PCH #endif -#include "resource.h" // main symbols +#include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CPluginApp @@ -41,18 +41,18 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class CPluginApp : public CWinApp { public: - CPluginApp(); +CPluginApp(); // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPluginApp) - //}}AFX_VIRTUAL - - //{{AFX_MSG(CPluginApp) - // NOTE - the ClassWizard will add and remove member functions here. - // DO NOT EDIT what you see in these blocks of generated code ! - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CPluginApp) +//}}AFX_VIRTUAL + +//{{AFX_MSG(CPluginApp) +// NOTE - the ClassWizard will add and remove member functions here. +// DO NOT EDIT what you see in these blocks of generated code ! +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; diff --git a/contrib/bobtoolz/bsploader.cpp b/contrib/bobtoolz/bsploader.cpp index 287c5fff..6c8b09e9 100644 --- a/contrib/bobtoolz/bsploader.cpp +++ b/contrib/bobtoolz/bsploader.cpp @@ -2,100 +2,97 @@ #include "dialogs/dialogs-gtk.h" #include "cmdlib.h" -int numnodes; -int numplanes; -int numleafs; -int numleafsurfaces; -int numVisBytes; -int numDrawVerts; -int numDrawSurfaces; -int numbrushes; -int numbrushsides; -int numleafbrushes; - -byte *visBytes = NULL; -dnode_t *dnodes = NULL; -dplane_t *dplanes = NULL; -dleaf_t *dleafs = NULL; -qdrawVert_t *drawVerts = NULL; -dsurface_t *drawSurfaces = NULL; -int *dleafsurfaces = NULL; -dbrush_t *dbrushes = NULL; -dbrushside_t *dbrushsides = NULL; -int *dleafbrushes = NULL; - -#define BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I') -#define Q3_BSP_VERSION 46 -#define WOLF_BSP_VERSION 47 +int numnodes; +int numplanes; +int numleafs; +int numleafsurfaces; +int numVisBytes; +int numDrawVerts; +int numDrawSurfaces; +int numbrushes; +int numbrushsides; +int numleafbrushes; + +byte *visBytes = NULL; +dnode_t *dnodes = NULL; +dplane_t *dplanes = NULL; +dleaf_t *dleafs = NULL; +qdrawVert_t *drawVerts = NULL; +dsurface_t *drawSurfaces = NULL; +int *dleafsurfaces = NULL; +dbrush_t *dbrushes = NULL; +dbrushside_t *dbrushsides = NULL; +int *dleafbrushes = NULL; + +#define BSP_IDENT ( ( 'P' << 24 ) + ( 'S' << 16 ) + ( 'B' << 8 ) + 'I' ) +#define Q3_BSP_VERSION 46 +#define WOLF_BSP_VERSION 47 /* -================ -FileLength -================ -*/ -int FileLength (FILE *f) -{ - int pos; - int end; - - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); + ================ + FileLength + ================ + */ +int FileLength( FILE *f ){ + int pos; + int end; + + pos = ftell( f ); + fseek( f, 0, SEEK_END ); + end = ftell( f ); + fseek( f, pos, SEEK_SET ); return end; } /* -============== -LoadFile -============== -*/ -bool LoadFile( const char *filename, byte **bufferptr) -{ - FILE *f; - int length; + ============== + LoadFile + ============== + */ +bool LoadFile( const char *filename, byte **bufferptr ){ + FILE *f; + int length; byte *buffer; - f = fopen(filename, "rb"); - if(!f) + f = fopen( filename, "rb" ); + if ( !f ) { return false; + } - length = FileLength (f); - buffer = new byte[length+1]; + length = FileLength( f ); + buffer = new byte[length + 1]; buffer[length] = 0; - fread(buffer, 1, length, f); - fclose (f); + fread( buffer, 1, length, f ); + fclose( f ); *bufferptr = buffer; return true; } -int LittleLong (int l) -{ -#if defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&l), reinterpret_cast(&l) + sizeof(int)); +int LittleLong( int l ){ +#if defined( __BIG_ENDIAN__ ) + std::reverse( reinterpret_cast( &l ), reinterpret_cast( &l ) + sizeof( int ) ); #endif return l; } -float LittleFloat (float l) -{ -#if defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&l), reinterpret_cast(&l) + sizeof(float)); +float LittleFloat( float l ){ +#if defined( __BIG_ENDIAN__ ) + std::reverse( reinterpret_cast( &l ), reinterpret_cast( &l ) + sizeof( float ) ); #endif return l; } /* -============= -SwapBlock + ============= + SwapBlock -If all values are 32 bits, this can be used to swap everything -============= -*/ + If all values are 32 bits, this can be used to swap everything + ============= + */ void SwapBlock( int *block, int sizeOfBlock ) { - int i; + int i; sizeOfBlock >>= 2; for ( i = 0 ; i < sizeOfBlock ; i++ ) { @@ -104,16 +101,16 @@ void SwapBlock( int *block, int sizeOfBlock ) { } /* -============= -SwapBSPFile + ============= + SwapBSPFile -Byte swaps all data in a bsp file. -============= -*/ + Byte swaps all data in a bsp file. + ============= + */ void SwapBSPFile( void ) { - int i; - - // models + int i; + + // models // SwapBlock( (int *)dmodels, nummodels * sizeof( dmodels[0] ) ); // shaders (don't swap the name) @@ -124,7 +121,7 @@ void SwapBSPFile( void ) { // planes SwapBlock( (int *)dplanes, numplanes * sizeof( dplanes[0] ) ); - + // nodes SwapBlock( (int *)dnodes, numnodes * sizeof( dnodes[0] ) ); @@ -144,8 +141,8 @@ void SwapBSPFile( void ) { SwapBlock( (int *)dbrushsides, numbrushsides * sizeof( dbrushsides[0] ) ); // vis - ((int *)&visBytes)[0] = LittleLong( ((int *)&visBytes)[0] ); - ((int *)&visBytes)[1] = LittleLong( ((int *)&visBytes)[1] ); + ( (int *)&visBytes )[0] = LittleLong( ( (int *)&visBytes )[0] ); + ( (int *)&visBytes )[1] = LittleLong( ( (int *)&visBytes )[1] ); // drawverts (don't swap colors ) for ( i = 0 ; i < numDrawVerts ; i++ ) { @@ -175,19 +172,20 @@ void SwapBSPFile( void ) { } /* -============= -CopyLump -============= -*/ -int CopyLump( dheader_t *header, int lump, void **dest, int size ) { - int length, ofs; + ============= + CopyLump + ============= + */ +int CopyLump( dheader_t *header, int lump, void **dest, int size ) { + int length, ofs; length = header->lumps[lump].filelen; ofs = header->lumps[lump].fileofs; - - if(length == 0) + + if ( length == 0 ) { return 0; - + } + *dest = new byte[length]; memcpy( *dest, (byte *)header + ofs, length ); @@ -195,69 +193,79 @@ int CopyLump( dheader_t *header, int lump, void **dest, int size ) { } /* -============= -LoadBSPFile -============= -*/ -bool LoadBSPFile( const char *filename ) { - dheader_t *header; + ============= + LoadBSPFile + ============= + */ +bool LoadBSPFile( const char *filename ) { + dheader_t *header; // load the file header - if(!LoadFile (filename, (byte **)&header)) + if ( !LoadFile( filename, (byte **)&header ) ) { return false; + } // swap the header - SwapBlock( (int *)header, sizeof(*header) ); + SwapBlock( (int *)header, sizeof( *header ) ); if ( header->ident != BSP_IDENT ) { - DoMessageBox( "Cant find a valid IBSP file", "Error", eMB_OK); + DoMessageBox( "Cant find a valid IBSP file", "Error", eMB_OK ); return false; } - if ( (header->version != Q3_BSP_VERSION) && - (header->version != WOLF_BSP_VERSION) ) { - DoMessageBox( "File is incorrect version", "Error", eMB_OK); + if ( ( header->version != Q3_BSP_VERSION ) && + ( header->version != WOLF_BSP_VERSION ) ) { + DoMessageBox( "File is incorrect version", "Error", eMB_OK ); return false; } - numbrushsides = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushsides, sizeof(dbrushside_t) ); - numbrushes = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushes, sizeof(dbrush_t) ); - numplanes = CopyLump( header, LUMP_PLANES, (void**)&dplanes, sizeof(dplane_t) ); - numleafs = CopyLump( header, LUMP_LEAFS, (void**)&dleafs, sizeof(dleaf_t) ); - numnodes = CopyLump( header, LUMP_NODES, (void**)&dnodes, sizeof(dnode_t) ); - numDrawVerts = CopyLump( header, LUMP_DRAWVERTS, (void**)&drawVerts, sizeof(qdrawVert_t) ); - numDrawSurfaces = CopyLump( header, LUMP_SURFACES, (void**)&drawSurfaces, sizeof(dsurface_t) ); - numleafsurfaces = CopyLump( header, LUMP_LEAFSURFACES, (void**)&dleafsurfaces, sizeof(int) ); - numVisBytes = CopyLump( header, LUMP_VISIBILITY, (void**)&visBytes, 1 ); - numleafbrushes = CopyLump( header, LUMP_LEAFBRUSHES, (void**)&dleafbrushes, sizeof(int) ); - - delete header; // everything has been copied out - + numbrushsides = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushsides, sizeof( dbrushside_t ) ); + numbrushes = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushes, sizeof( dbrush_t ) ); + numplanes = CopyLump( header, LUMP_PLANES, (void**)&dplanes, sizeof( dplane_t ) ); + numleafs = CopyLump( header, LUMP_LEAFS, (void**)&dleafs, sizeof( dleaf_t ) ); + numnodes = CopyLump( header, LUMP_NODES, (void**)&dnodes, sizeof( dnode_t ) ); + numDrawVerts = CopyLump( header, LUMP_DRAWVERTS, (void**)&drawVerts, sizeof( qdrawVert_t ) ); + numDrawSurfaces = CopyLump( header, LUMP_SURFACES, (void**)&drawSurfaces, sizeof( dsurface_t ) ); + numleafsurfaces = CopyLump( header, LUMP_LEAFSURFACES, (void**)&dleafsurfaces, sizeof( int ) ); + numVisBytes = CopyLump( header, LUMP_VISIBILITY, (void**)&visBytes, 1 ); + numleafbrushes = CopyLump( header, LUMP_LEAFBRUSHES, (void**)&dleafbrushes, sizeof( int ) ); + + delete header; // everything has been copied out + // swap everything SwapBSPFile(); return true; } -void FreeBSPData() -{ - if(visBytes) +void FreeBSPData(){ + if ( visBytes ) { delete visBytes; - if(dnodes) + } + if ( dnodes ) { delete dnodes; - if(dplanes) + } + if ( dplanes ) { delete dplanes; - if(dleafs) + } + if ( dleafs ) { delete dleafs; - if(drawVerts) + } + if ( drawVerts ) { delete drawVerts; - if(drawSurfaces) + } + if ( drawSurfaces ) { delete drawSurfaces; - if(dleafsurfaces) + } + if ( dleafsurfaces ) { delete dleafsurfaces; - if(dleafbrushes) + } + if ( dleafbrushes ) { delete dleafbrushes; - if(dbrushes) + } + if ( dbrushes ) { delete dbrushes; - if(dbrushsides) + } + if ( dbrushsides ) { delete dbrushsides; + } } diff --git a/contrib/bobtoolz/bsploader.h b/contrib/bobtoolz/bsploader.h index 3cea233b..7bee8fd0 100644 --- a/contrib/bobtoolz/bsploader.h +++ b/contrib/bobtoolz/bsploader.h @@ -1,101 +1,101 @@ #include "mathlib.h" -#define LUMP_ENTITIES 0 -#define LUMP_SHADERS 1 -#define LUMP_PLANES 2 -#define LUMP_NODES 3 -#define LUMP_LEAFS 4 -#define LUMP_LEAFSURFACES 5 -#define LUMP_LEAFBRUSHES 6 -#define LUMP_MODELS 7 -#define LUMP_BRUSHES 8 -#define LUMP_BRUSHSIDES 9 -#define LUMP_DRAWVERTS 10 -#define LUMP_DRAWINDEXES 11 -#define LUMP_FOGS 12 -#define LUMP_SURFACES 13 -#define LUMP_LIGHTMAPS 14 -#define LUMP_LIGHTGRID 15 -#define LUMP_VISIBILITY 16 -#define HEADER_LUMPS 17 +#define LUMP_ENTITIES 0 +#define LUMP_SHADERS 1 +#define LUMP_PLANES 2 +#define LUMP_NODES 3 +#define LUMP_LEAFS 4 +#define LUMP_LEAFSURFACES 5 +#define LUMP_LEAFBRUSHES 6 +#define LUMP_MODELS 7 +#define LUMP_BRUSHES 8 +#define LUMP_BRUSHSIDES 9 +#define LUMP_DRAWVERTS 10 +#define LUMP_DRAWINDEXES 11 +#define LUMP_FOGS 12 +#define LUMP_SURFACES 13 +#define LUMP_LIGHTMAPS 14 +#define LUMP_LIGHTGRID 15 +#define LUMP_VISIBILITY 16 +#define HEADER_LUMPS 17 typedef struct { - int fileofs, filelen; + int fileofs, filelen; } lump_t; typedef struct { - int ident; - int version; + int ident; + int version; - lump_t lumps[HEADER_LUMPS]; + lump_t lumps[HEADER_LUMPS]; } dheader_t; typedef struct { - float normal[3]; - float dist; + float normal[3]; + float dist; } dplane_t; typedef struct { - int planeNum; - int children[2]; // negative numbers are -(leafs+1), not nodes - int mins[3]; // for frustom culling - int maxs[3]; + int planeNum; + int children[2]; // negative numbers are -(leafs+1), not nodes + int mins[3]; // for frustom culling + int maxs[3]; } dnode_t; typedef struct { - int cluster; // -1 = opaque cluster (do I still store these?) - int area; + int cluster; // -1 = opaque cluster (do I still store these?) + int area; - int mins[3]; // for frustum culling - int maxs[3]; + int mins[3]; // for frustum culling + int maxs[3]; - int firstLeafSurface; - int numLeafSurfaces; + int firstLeafSurface; + int numLeafSurfaces; - int firstLeafBrush; - int numLeafBrushes; + int firstLeafBrush; + int numLeafBrushes; } dleaf_t; typedef struct { - vec3_t xyz; - float st[2]; - float lightmap[2]; - vec3_t normal; - byte color[4]; + vec3_t xyz; + float st[2]; + float lightmap[2]; + vec3_t normal; + byte color[4]; } qdrawVert_t; typedef struct { - int shaderNum; - int fogNum; - int surfaceType; + int shaderNum; + int fogNum; + int surfaceType; - int firstVert; - int numVerts; + int firstVert; + int numVerts; - int firstIndex; - int numIndexes; + int firstIndex; + int numIndexes; - int lightmapNum; - int lightmapX, lightmapY; - int lightmapWidth, lightmapHeight; + int lightmapNum; + int lightmapX, lightmapY; + int lightmapWidth, lightmapHeight; - vec3_t lightmapOrigin; - vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds + vec3_t lightmapOrigin; + vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds - int patchWidth; - int patchHeight; + int patchWidth; + int patchHeight; } dsurface_t; typedef struct { - int planeNum; // positive plane side faces out of the leaf - int shaderNum; + int planeNum; // positive plane side faces out of the leaf + int shaderNum; } dbrushside_t; typedef struct { - int firstSide; - int numSides; - int shaderNum; // the shader that determines the contents flags + int firstSide; + int numSides; + int shaderNum; // the shader that determines the contents flags } dbrush_t; typedef enum { @@ -106,32 +106,32 @@ typedef enum { MST_FLARE } mapSurfaceType_t; -#define MAX_MAP_VISIBILITY 0x200000 -#define MAX_MAP_NODES 0x20000 -#define MAX_MAP_PLANES 0x20000 -#define MAX_MAP_LEAFS 0x20000 - -extern int numVisBytes; -extern int numleafs; -extern int numplanes; -extern int numnodes; -extern int numDrawVerts; -extern int numDrawSurfaces; -extern int numleafsurfaces; -extern int numbrushes; -extern int numbrushsides; -extern int numleafbrushes; - -extern dnode_t *dnodes; -extern dplane_t *dplanes; -extern dleaf_t *dleafs; -extern byte *visBytes; -extern qdrawVert_t *drawVerts; -extern dsurface_t *drawSurfaces; -extern int *dleafsurfaces; -extern dbrush_t *dbrushes; -extern dbrushside_t *dbrushsides; -extern int *dleafbrushes; +#define MAX_MAP_VISIBILITY 0x200000 +#define MAX_MAP_NODES 0x20000 +#define MAX_MAP_PLANES 0x20000 +#define MAX_MAP_LEAFS 0x20000 + +extern int numVisBytes; +extern int numleafs; +extern int numplanes; +extern int numnodes; +extern int numDrawVerts; +extern int numDrawSurfaces; +extern int numleafsurfaces; +extern int numbrushes; +extern int numbrushsides; +extern int numleafbrushes; + +extern dnode_t *dnodes; +extern dplane_t *dplanes; +extern dleaf_t *dleafs; +extern byte *visBytes; +extern qdrawVert_t *drawVerts; +extern dsurface_t *drawSurfaces; +extern int *dleafsurfaces; +extern dbrush_t *dbrushes; +extern dbrushside_t *dbrushsides; +extern int *dleafbrushes; bool LoadBSPFile( const char *filename ); void FreeBSPData(); diff --git a/contrib/bobtoolz/cportals.cpp b/contrib/bobtoolz/cportals.cpp index 5048eef0..073c979d 100644 --- a/contrib/bobtoolz/cportals.cpp +++ b/contrib/bobtoolz/cportals.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "CPortals.h" @@ -27,142 +27,137 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define LINE_BUF 1000 #define MSG_PREFIX "bobToolz plugin: " -// these classes are far less of a mess than my code was, +// these classes are far less of a mess than my code was, // thanq to G.DeWan 4 the prtview source on which it was based -CBspPortal::CBspPortal() -{ - memset(this, 0, sizeof(CBspPortal)); +CBspPortal::CBspPortal(){ + memset( this, 0, sizeof( CBspPortal ) ); } -CBspPortal::~CBspPortal() -{ +CBspPortal::~CBspPortal(){ delete[] point; } -void ClampFloat(float* p) -{ +void ClampFloat( float* p ){ double i; - double frac = modf(*p, &i); + double frac = modf( *p, &i ); - if(!frac) + if ( !frac ) { return; + } - if(fabs(*p - ceil(*p)) < MAX_ROUND_ERROR) - *p = static_cast(ceil(*p)); + if ( fabs( *p - ceil( *p ) ) < MAX_ROUND_ERROR ) { + *p = static_cast( ceil( *p ) ); + } - if(fabs(*p - floor(*p)) < MAX_ROUND_ERROR) - *p = static_cast(floor(*p)); + if ( fabs( *p - floor( *p ) ) < MAX_ROUND_ERROR ) { + *p = static_cast( floor( *p ) ); + } } -bool CBspPortal::Build(char *def, unsigned int pointCnt, bool bInverse) -{ +bool CBspPortal::Build( char *def, unsigned int pointCnt, bool bInverse ){ char *c = def; unsigned int n; point_count = pointCnt; - if(point_count < 3) + if ( point_count < 3 ) { return false; + } point = new CBspPoint[point_count]; - for(n = 0; n < point_count; n++) + for ( n = 0; n < point_count; n++ ) { - for(; *c != 0 && *c != '('; c++); + for (; *c != 0 && *c != '('; c++ ) ; - if(*c == 0) + if ( *c == 0 ) { return false; + } c++; int x; - if(bInverse) + if ( bInverse ) { x = point_count - n - 1; - else + } + else{ x = n; + } - sscanf(c, "%f %f %f", &point[x].p[0], &point[x].p[1], &point[x].p[2]); + sscanf( c, "%f %f %f", &point[x].p[0], &point[x].p[1], &point[x].p[2] ); - ClampFloat(&point[x].p[0]); - ClampFloat(&point[x].p[1]); - ClampFloat(&point[x].p[2]); + ClampFloat( &point[x].p[0] ); + ClampFloat( &point[x].p[1] ); + ClampFloat( &point[x].p[2] ); } return true; } -CPortals::CPortals() -{ - memset(this, 0, sizeof(CPortals)); +CPortals::CPortals(){ + memset( this, 0, sizeof( CPortals ) ); } -CPortals::~CPortals() -{ +CPortals::~CPortals(){ Purge(); } -void CPortals::Purge() -{ - if(node) +void CPortals::Purge(){ + if ( node ) { delete[] node; + } node = NULL; node_count = 0; } -void CPortals::Load() -{ - char buf[LINE_BUF+1]; +void CPortals::Load(){ + char buf[LINE_BUF + 1]; + + memset( buf, 0, LINE_BUF + 1 ); - memset(buf, 0, LINE_BUF + 1); - Purge(); globalOutputStream() << MSG_PREFIX "Loading portal file " << fn << ".\n"; FILE *in; - in = fopen(fn, "rt"); + in = fopen( fn, "rt" ); - if(in == NULL) - { + if ( in == NULL ) { globalOutputStream() << " ERROR - could not open file.\n"; return; } - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); globalOutputStream() << " ERROR - File ended prematurely.\n"; return; } - if(strncmp("PRT1", buf, 4) != 0) - { - fclose(in); + if ( strncmp( "PRT1", buf, 4 ) != 0 ) { + fclose( in ); globalOutputStream() << " ERROR - File header indicates wrong file type (should be \"PRT1\").\n"; return; } - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); globalOutputStream() << " ERROR - File ended prematurely.\n"; return; } - sscanf(buf, "%u", &node_count); + sscanf( buf, "%u", &node_count ); - if(node_count > 0xFFFF) - { - fclose(in); + if ( node_count > 0xFFFF ) { + fclose( in ); node_count = 0; @@ -171,9 +166,8 @@ void CPortals::Load() return; } - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); node_count = 0; @@ -183,11 +177,10 @@ void CPortals::Load() } unsigned int p_count; - sscanf(buf, "%u", &p_count); + sscanf( buf, "%u", &p_count ); - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); node_count = 0; @@ -197,16 +190,15 @@ void CPortals::Load() } unsigned int p_count2; - sscanf(buf, "%u", &p_count2); + sscanf( buf, "%u", &p_count2 ); node = new CBspNode[node_count]; unsigned int i; - for(i = 0; i < p_count; i++) + for ( i = 0; i < p_count; i++ ) { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); node_count = 0; @@ -216,17 +208,16 @@ void CPortals::Load() } unsigned int dummy, node1, node2; - sscanf(buf, "%u %u %u", &dummy, &node1, &node2); + sscanf( buf, "%u %u %u", &dummy, &node1, &node2 ); node[node1].portal_count++; node[node2].portal_count++; } - for(i = 0; i < p_count2; i++) + for ( i = 0; i < p_count2; i++ ) { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); node_count = 0; @@ -236,29 +227,28 @@ void CPortals::Load() } unsigned int dummy, node1; - sscanf(buf, "%u %u", &dummy, &node1); + sscanf( buf, "%u %u", &dummy, &node1 ); node[node1].portal_count++; } - for(i = 0; i < node_count; i++) + for ( i = 0; i < node_count; i++ ) node[i].portal = new CBspPortal[node[i].portal_count]; - fclose(in); + fclose( in ); - in = fopen(fn, "rt"); + in = fopen( fn, "rt" ); - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); + fgets( buf, LINE_BUF, in ); + fgets( buf, LINE_BUF, in ); + fgets( buf, LINE_BUF, in ); + fgets( buf, LINE_BUF, in ); unsigned int n; - for(n = 0; n < p_count; n++) + for ( n = 0; n < p_count; n++ ) { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); Purge(); @@ -268,11 +258,10 @@ void CPortals::Load() } unsigned int pCount, node1, node2; - sscanf(buf, "%u %u %u", &pCount, &node1, &node2); + sscanf( buf, "%u %u %u", &pCount, &node1, &node2 ); - if(!node[node1].AddPortal(buf, pCount, false)) - { - fclose(in); + if ( !node[node1].AddPortal( buf, pCount, false ) ) { + fclose( in ); Purge(); @@ -281,9 +270,8 @@ void CPortals::Load() return; } - if(!node[node2].AddPortal(buf, pCount, true)) - { - fclose(in); + if ( !node[node2].AddPortal( buf, pCount, true ) ) { + fclose( in ); Purge(); @@ -293,11 +281,10 @@ void CPortals::Load() } } - for(n = 0; n < p_count2; n++) + for ( n = 0; n < p_count2; n++ ) { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); Purge(); @@ -307,11 +294,10 @@ void CPortals::Load() } unsigned int pCount, node1; - sscanf(buf, "%u %u", &pCount, &node1); + sscanf( buf, "%u %u", &pCount, &node1 ); - if(!node[node1].AddPortal(buf, pCount, false)) - { - fclose(in); + if ( !node[node1].AddPortal( buf, pCount, false ) ) { + fclose( in ); Purge(); @@ -321,23 +307,21 @@ void CPortals::Load() } } - fclose(in); + fclose( in ); } -CBspNode::CBspNode() -{ +CBspNode::CBspNode(){ portal = NULL; portal_count = 0; portal_next = 0; } -CBspNode::~CBspNode() -{ - if(portal != NULL) +CBspNode::~CBspNode(){ + if ( portal != NULL ) { delete[] portal; + } } -bool CBspNode::AddPortal(char *def, unsigned int pointCnt, bool bInverse) -{ - return portal[portal_next++].Build(def, pointCnt, bInverse); +bool CBspNode::AddPortal( char *def, unsigned int pointCnt, bool bInverse ){ + return portal[portal_next++].Build( def, pointCnt, bInverse ); } diff --git a/contrib/bobtoolz/ctfToolz-GTK.cpp b/contrib/bobtoolz/ctfToolz-GTK.cpp index fe0e1d95..4e5231d1 100644 --- a/contrib/bobtoolz/ctfToolz-GTK.cpp +++ b/contrib/bobtoolz/ctfToolz-GTK.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "StdAfx.h" @@ -25,10 +25,10 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "dialogs/dialogs-gtk.h" // Radiant function table -_QERFuncTable_1 g_FuncTable; -_QERAppBSPFrontendTable g_BSPTable; // for map name +_QERFuncTable_1 g_FuncTable; +_QERAppBSPFrontendTable g_BSPTable; // for map name -BOOL g_bBSPInitDone = FALSE; +BOOL g_bBSPInitDone = FALSE; // plugin name static const char *PLUGIN_NAME = "ctfToolz"; @@ -37,61 +37,61 @@ static const char *PLUGIN_NAME = "ctfToolz"; static const char *PLUGIN_COMMANDS = "About...,Colour Changer...,Swap Light Colours,Change Angles 180,Swap Spawn Points"; // globals -GtkWidget *g_pRadiantWnd=NULL; +GtkWidget *g_pRadiantWnd = NULL; static const char *PLUGIN_ABOUT = "ctfToolz for NetRadiant\n" - "by djbob\n" + "by djbob\n" "http://www.planetquake.com/toolz\n\n"; -extern "C" LPVOID WINAPI QERPlug_GetFuncTable() -{ - return &g_FuncTable; +extern "C" LPVOID WINAPI QERPlug_GetFuncTable(){ + return &g_FuncTable; } -extern "C" LPCSTR WINAPI QERPlug_Init(HMODULE hApp, GtkWidget* pMainWidget) -{ +extern "C" LPCSTR WINAPI QERPlug_Init( HMODULE hApp, GtkWidget* pMainWidget ){ g_pRadiantWnd = pMainWidget; - memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); + memset( &g_FuncTable, 0, sizeof( _QERFuncTable_1 ) ); g_FuncTable.m_fVersion = QER_PLUG_VERSION; - g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); + g_FuncTable.m_nSize = sizeof( _QERFuncTable_1 ); return "ctfToolz for GTKradiant"; } -extern "C" LPCSTR WINAPI QERPlug_GetName() -{ +extern "C" LPCSTR WINAPI QERPlug_GetName(){ return (char*)PLUGIN_NAME; } -extern "C" LPCSTR WINAPI QERPlug_GetCommandList() -{ +extern "C" LPCSTR WINAPI QERPlug_GetCommandList(){ return (char*)PLUGIN_COMMANDS; } -extern "C" void WINAPI QERPlug_Dispatch (LPCSTR p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ +extern "C" void WINAPI QERPlug_Dispatch( LPCSTR p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ){ LoadLists(); - if (!g_bBSPInitDone) - { - g_BSPTable.m_nSize = sizeof(_QERAppBSPFrontendTable); - if ( g_FuncTable.m_pfnRequestInterface( QERAppBSPFrontendTable_GUID, static_cast(&g_BSPTable) ) ) + if ( !g_bBSPInitDone ) { + g_BSPTable.m_nSize = sizeof( _QERAppBSPFrontendTable ); + if ( g_FuncTable.m_pfnRequestInterface( QERAppBSPFrontendTable_GUID, static_cast( &g_BSPTable ) ) ) { g_bBSPInitDone = TRUE; + } else { - Sys_ERROR("_QERAppBSPFrontendTable interface request failed\n"); + Sys_ERROR( "_QERAppBSPFrontendTable interface request failed\n" ); return; } } - - if(!strcmp(p, "About...")) - DoMessageBox(PLUGIN_ABOUT, "About", IDOK); - else if(!strcmp(p, "Colour Changer...")) + + if ( !strcmp( p, "About..." ) ) { + DoMessageBox( PLUGIN_ABOUT, "About", IDOK ); + } + else if ( !strcmp( p, "Colour Changer..." ) ) { DoCTFColourChanger(); - else if(!strcmp(p, "Swap Light Colours")) + } + else if ( !strcmp( p, "Swap Light Colours" ) ) { DoSwapLights(); - else if(!strcmp(p, "Change Angles 180")) + } + else if ( !strcmp( p, "Change Angles 180" ) ) { DoChangeAngles(); - else if(!strcmp(p, "Swap Spawn Points")) + } + else if ( !strcmp( p, "Swap Spawn Points" ) ) { DoSwapSpawns(); + } } diff --git a/contrib/bobtoolz/ctfresource_gtk.h b/contrib/bobtoolz/ctfresource_gtk.h index 3f706a04..3be1d0d2 100644 --- a/contrib/bobtoolz/ctfresource_gtk.h +++ b/contrib/bobtoolz/ctfresource_gtk.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. @@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 diff --git a/contrib/bobtoolz/dialogs/AboutDialog.cpp b/contrib/bobtoolz/dialogs/AboutDialog.cpp index e5d37038..6ba6df14 100644 --- a/contrib/bobtoolz/dialogs/AboutDialog.cpp +++ b/contrib/bobtoolz/dialogs/AboutDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // AboutDialog.cpp : implementation file // @@ -33,30 +33,27 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // CAboutDialog dialog -CAboutDialog::CAboutDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAboutDialog::IDD, pParent) -{ +CAboutDialog::CAboutDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CAboutDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CAboutDialog) - // NOTE: the ClassWizard will add member initialization here + // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } -void CAboutDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CAboutDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CAboutDialog) - // NOTE: the ClassWizard will add DDX and DDV calls here + // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CAboutDialog, CDialog) - //{{AFX_MSG_MAP(CAboutDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CAboutDialog, CDialog ) +//{{AFX_MSG_MAP(CAboutDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAboutDialog message handlers - diff --git a/contrib/bobtoolz/dialogs/AboutDialog.h b/contrib/bobtoolz/dialogs/AboutDialog.h index 54cfd017..64b4eb2c 100644 --- a/contrib/bobtoolz/dialogs/AboutDialog.h +++ b/contrib/bobtoolz/dialogs/AboutDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) +#if !defined( AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ ) #define AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ #if _MSC_VER >= 1000 @@ -33,29 +33,29 @@ class CAboutDialog : public CDialog { // Construction public: - CAboutDialog(CWnd* pParent = NULL); // standard constructor +CAboutDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CAboutDialog) - enum { IDD = IDD_ABOUT }; - //}}AFX_DATA +//{{AFX_DATA(CAboutDialog) +enum { IDD = IDD_ABOUT }; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAboutDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CAboutDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CAboutDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CAboutDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp b/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp index fd46b7fb..bcbb4957 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp +++ b/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // AutoCaulkDialog.cpp : implementation file // @@ -34,29 +34,27 @@ static char THIS_FILE[] = __FILE__; // CAutoCaulkDialog dialog -CAutoCaulkDialog::CAutoCaulkDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAutoCaulkDialog::IDD, pParent) -{ +CAutoCaulkDialog::CAutoCaulkDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CAutoCaulkDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CAutoCaulkDialog) - // NOTE: the ClassWizard will add member initialization here + // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } -void CAutoCaulkDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CAutoCaulkDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CAutoCaulkDialog) - DDX_Control(pDX, IDC_PROGRESS2, m_prog2); - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); + DDX_Control( pDX, IDC_PROGRESS2, m_prog2 ); + DDX_Control( pDX, IDC_PROGRESS1, m_prog1 ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CAutoCaulkDialog, CDialog) - //{{AFX_MSG_MAP(CAutoCaulkDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CAutoCaulkDialog, CDialog ) +//{{AFX_MSG_MAP(CAutoCaulkDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/AutoCaulkDialog.h b/contrib/bobtoolz/dialogs/AutoCaulkDialog.h index a8740275..30ca2e75 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkDialog.h +++ b/contrib/bobtoolz/dialogs/AutoCaulkDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_) +#if !defined( AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_ ) #define AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,31 +33,31 @@ class CAutoCaulkDialog : public CDialog { // Construction public: - CAutoCaulkDialog(CWnd* pParent = NULL); // standard constructor +CAutoCaulkDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CAutoCaulkDialog) - enum { IDD = IDD_AUTOCAULK_DIALOG }; - CProgressCtrl m_prog2; - CProgressCtrl m_prog1; - //}}AFX_DATA +//{{AFX_DATA(CAutoCaulkDialog) +enum { IDD = IDD_AUTOCAULK_DIALOG }; +CProgressCtrl m_prog2; +CProgressCtrl m_prog1; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAutoCaulkDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CAutoCaulkDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CAutoCaulkDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CAutoCaulkDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp index 857df71a..f59dfd33 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp +++ b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // AutoCaulkStartDialog.cpp : implementation file // @@ -34,32 +34,30 @@ static char THIS_FILE[] = __FILE__; // CAutoCaulkStartDialog dialog -CAutoCaulkStartDialog::CAutoCaulkStartDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAutoCaulkStartDialog::IDD, pParent) -{ +CAutoCaulkStartDialog::CAutoCaulkStartDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CAutoCaulkStartDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CAutoCaulkStartDialog) m_bAllowDestruction = FALSE; - m_Warning1 = _T(""); + m_Warning1 = _T( "" ); m_nMode = 0; //}}AFX_DATA_INIT } -void CAutoCaulkStartDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CAutoCaulkStartDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CAutoCaulkStartDialog) - DDX_Check(pDX, IDC_KILLBRUSHES_CHECK, m_bAllowDestruction); - DDX_Text(pDX, IDC_WARNING1_STATIC, m_Warning1); - DDX_Radio(pDX, IDC_AC_NORMAL_RADIO, m_nMode); + DDX_Check( pDX, IDC_KILLBRUSHES_CHECK, m_bAllowDestruction ); + DDX_Text( pDX, IDC_WARNING1_STATIC, m_Warning1 ); + DDX_Radio( pDX, IDC_AC_NORMAL_RADIO, m_nMode ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CAutoCaulkStartDialog, CDialog) - //{{AFX_MSG_MAP(CAutoCaulkStartDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CAutoCaulkStartDialog, CDialog ) +//{{AFX_MSG_MAP(CAutoCaulkStartDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h index 9311c51c..5c2f4297 100644 --- a/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h +++ b/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -26,9 +26,9 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // AutoCaulkStartDialog.h : header file // -#define MODE_AC_NORMAL 0 -#define MODE_AC_BUILD_MINI_PRT 1 -#define MODE_AC_SUPER 2 +#define MODE_AC_NORMAL 0 +#define MODE_AC_BUILD_MINI_PRT 1 +#define MODE_AC_SUPER 2 ///////////////////////////////////////////////////////////////////////////// // CAutoCaulkStartDialog dialog @@ -37,32 +37,32 @@ class CAutoCaulkStartDialog : public CDialog { // Construction public: - CAutoCaulkStartDialog(CWnd* pParent = NULL); // standard constructor +CAutoCaulkStartDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CAutoCaulkStartDialog) - enum { IDD = IDD_AUTOCAULKSTART_DIALOG }; - BOOL m_bAllowDestruction; - CString m_Warning1; - int m_nMode; - //}}AFX_DATA +//{{AFX_DATA(CAutoCaulkStartDialog) +enum { IDD = IDD_AUTOCAULKSTART_DIALOG }; +BOOL m_bAllowDestruction; +CString m_Warning1; +int m_nMode; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAutoCaulkStartDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CAutoCaulkStartDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CAutoCaulkStartDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CAutoCaulkStartDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/BrushCheckDialog.h b/contrib/bobtoolz/dialogs/BrushCheckDialog.h index 2ccf8e8f..c232657b 100644 --- a/contrib/bobtoolz/dialogs/BrushCheckDialog.h +++ b/contrib/bobtoolz/dialogs/BrushCheckDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_) +#if !defined( AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_ ) #define AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,30 +33,30 @@ class CBrushCheckDialog : public CDialog { // Construction public: - CBrushCheckDialog(CWnd* pParent = NULL); // standard constructor +CBrushCheckDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CBrushCheckDialog) - enum { IDD = IDD_BRUSHCHECKER_DIALOG }; - CProgressCtrl m_prog1; - //}}AFX_DATA +//{{AFX_DATA(CBrushCheckDialog) +enum { IDD = IDD_BRUSHCHECKER_DIALOG }; +CProgressCtrl m_prog1; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CBrushCheckDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CBrushCheckDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CBrushCheckDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CBrushCheckDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/DoorDialog.cpp b/contrib/bobtoolz/dialogs/DoorDialog.cpp index 2a1829d5..ce0d6213 100644 --- a/contrib/bobtoolz/dialogs/DoorDialog.cpp +++ b/contrib/bobtoolz/dialogs/DoorDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // DoorDialog.cpp : implementation file // @@ -33,60 +33,56 @@ static char THIS_FILE[] = __FILE__; // CDoorDialog dialog -CDoorDialog::CDoorDialog(CWnd* pParent /*=NULL*/) - : CDialog(CDoorDialog::IDD, pParent) -{ +CDoorDialog::CDoorDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CDoorDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CDoorDialog) - m_fbTextureName = _T(""); + m_fbTextureName = _T( "" ); m_bSclMainHor = TRUE; m_bSclMainVert = TRUE; m_bSclTrimHor = TRUE; m_bSclTrimVert = FALSE; - m_trimTextureName = _T(""); - m_trimTexSetBox = _T(""); - m_mainTexSetBox = _T(""); + m_trimTextureName = _T( "" ); + m_trimTexSetBox = _T( "" ); + m_mainTexSetBox = _T( "" ); m_doorDirection = -1; //}}AFX_DATA_INIT } -void CDoorDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CDoorDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CDoorDialog) - DDX_Text(pDX, IDC_FBTEXTURE_EDIT, m_fbTextureName); - DDX_Check(pDX, IDC_TEXSCALE1_CHECK, m_bSclMainHor); - DDX_Check(pDX, IDC_TEXSCALE2_CHECK, m_bSclMainVert); - DDX_Check(pDX, IDC_TEXSCALE3_CHECK, m_bSclTrimHor); - DDX_Check(pDX, IDC_TEXSCALE4_CHECK, m_bSclTrimVert); - DDX_Text(pDX, IDC_TRIMTEXTURE_EDIT, m_trimTextureName); - DDX_CBString(pDX, IDC_TRIMTEX_COMBO, m_trimTexSetBox); - DDX_CBString(pDX, IDC_MAINTEX_COMBO, m_mainTexSetBox); - DDX_Radio(pDX, IDC_DIR_NS_RADIO, m_doorDirection); + DDX_Text( pDX, IDC_FBTEXTURE_EDIT, m_fbTextureName ); + DDX_Check( pDX, IDC_TEXSCALE1_CHECK, m_bSclMainHor ); + DDX_Check( pDX, IDC_TEXSCALE2_CHECK, m_bSclMainVert ); + DDX_Check( pDX, IDC_TEXSCALE3_CHECK, m_bSclTrimHor ); + DDX_Check( pDX, IDC_TEXSCALE4_CHECK, m_bSclTrimVert ); + DDX_Text( pDX, IDC_TRIMTEXTURE_EDIT, m_trimTextureName ); + DDX_CBString( pDX, IDC_TRIMTEX_COMBO, m_trimTexSetBox ); + DDX_CBString( pDX, IDC_MAINTEX_COMBO, m_mainTexSetBox ); + DDX_Radio( pDX, IDC_DIR_NS_RADIO, m_doorDirection ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CDoorDialog, CDialog) - //{{AFX_MSG_MAP(CDoorDialog) - ON_BN_CLICKED(IDC_SET_MAINTEX_BTN, OnSetMaintexBtn) - ON_BN_CLICKED(IDC_SET_TRIMTEX_BTN, OnSetTrimtexBtn) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CDoorDialog, CDialog ) +//{{AFX_MSG_MAP(CDoorDialog) +ON_BN_CLICKED( IDC_SET_MAINTEX_BTN, OnSetMaintexBtn ) +ON_BN_CLICKED( IDC_SET_TRIMTEX_BTN, OnSetTrimtexBtn ) +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDoorDialog message handlers -void CDoorDialog::OnSetMaintexBtn() -{ - UpdateData(TRUE); +void CDoorDialog::OnSetMaintexBtn(){ + UpdateData( TRUE ); m_fbTextureName = m_mainTexSetBox; - UpdateData(FALSE); + UpdateData( FALSE ); } -void CDoorDialog::OnSetTrimtexBtn() -{ - UpdateData(TRUE); +void CDoorDialog::OnSetTrimtexBtn(){ + UpdateData( TRUE ); m_trimTextureName = m_trimTexSetBox; - UpdateData(FALSE); + UpdateData( FALSE ); } diff --git a/contrib/bobtoolz/dialogs/DoorDialog.h b/contrib/bobtoolz/dialogs/DoorDialog.h index 4d312cb9..94242aff 100644 --- a/contrib/bobtoolz/dialogs/DoorDialog.h +++ b/contrib/bobtoolz/dialogs/DoorDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_) +#if !defined( AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_ ) #define AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,39 +33,39 @@ class CDoorDialog : public CDialog { // Construction public: - CDoorDialog(CWnd* pParent = NULL); // standard constructor +CDoorDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CDoorDialog) - enum { IDD = IDD_DOOR_DIALOG }; - CString m_fbTextureName; - BOOL m_bSclMainHor; - BOOL m_bSclMainVert; - BOOL m_bSclTrimHor; - BOOL m_bSclTrimVert; - CString m_trimTextureName; - CString m_trimTexSetBox; - CString m_mainTexSetBox; - int m_doorDirection; - //}}AFX_DATA +//{{AFX_DATA(CDoorDialog) +enum { IDD = IDD_DOOR_DIALOG }; +CString m_fbTextureName; +BOOL m_bSclMainHor; +BOOL m_bSclMainVert; +BOOL m_bSclTrimHor; +BOOL m_bSclTrimVert; +CString m_trimTextureName; +CString m_trimTexSetBox; +CString m_mainTexSetBox; +int m_doorDirection; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CDoorDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CDoorDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CDoorDialog) - afx_msg void OnSetMaintexBtn(); - afx_msg void OnSetTrimtexBtn(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CDoorDialog) +afx_msg void OnSetMaintexBtn(); +afx_msg void OnSetTrimtexBtn(); +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/IntersectDialog.cpp b/contrib/bobtoolz/dialogs/IntersectDialog.cpp index 63a42d02..4bcc8373 100644 --- a/contrib/bobtoolz/dialogs/IntersectDialog.cpp +++ b/contrib/bobtoolz/dialogs/IntersectDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // IntersectDialog.cpp : implementation file // @@ -33,9 +33,8 @@ static char THIS_FILE[] = __FILE__; // CIntersectDialog dialog -CIntersectDialog::CIntersectDialog(CWnd* pParent /*=NULL*/) - : CDialog(CIntersectDialog::IDD, pParent) -{ +CIntersectDialog::CIntersectDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CIntersectDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CIntersectDialog) m_nBrushOptions = 1; m_bUseDetail = FALSE; @@ -44,21 +43,20 @@ CIntersectDialog::CIntersectDialog(CWnd* pParent /*=NULL*/) } -void CIntersectDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CIntersectDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CIntersectDialog) - DDX_Radio(pDX, IDC_WHOLEMAP_RADIO, m_nBrushOptions); - DDX_Check(pDX, IDC_DETAIL_INCLUDE_CHECK, m_bUseDetail); - DDX_Check(pDX, IDC_DUPLICATEONLY_CHECK, m_bDuplicateOnly); + DDX_Radio( pDX, IDC_WHOLEMAP_RADIO, m_nBrushOptions ); + DDX_Check( pDX, IDC_DETAIL_INCLUDE_CHECK, m_bUseDetail ); + DDX_Check( pDX, IDC_DUPLICATEONLY_CHECK, m_bDuplicateOnly ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CIntersectDialog, CDialog) - //{{AFX_MSG_MAP(CIntersectDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CIntersectDialog, CDialog ) +//{{AFX_MSG_MAP(CIntersectDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/IntersectDialog.h b/contrib/bobtoolz/dialogs/IntersectDialog.h index d1190a6f..d8d64c3e 100644 --- a/contrib/bobtoolz/dialogs/IntersectDialog.h +++ b/contrib/bobtoolz/dialogs/IntersectDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_) +#if !defined( AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_ ) #define AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -26,8 +26,8 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // IntersectDialog.h : header file // -#define BRUSH_OPT_WHOLE_MAP 0 -#define BRUSH_OPT_SELECTED 1 +#define BRUSH_OPT_WHOLE_MAP 0 +#define BRUSH_OPT_SELECTED 1 ///////////////////////////////////////////////////////////////////////////// // CIntersectDialog dialog @@ -36,32 +36,32 @@ class CIntersectDialog : public CDialog { // Construction public: - CIntersectDialog(CWnd* pParent = NULL); // standard constructor +CIntersectDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CIntersectDialog) - enum { IDD = IDD_INTERSECT_DIALOG }; - int m_nBrushOptions; - BOOL m_bUseDetail; - BOOL m_bDuplicateOnly; - //}}AFX_DATA +//{{AFX_DATA(CIntersectDialog) +enum { IDD = IDD_INTERSECT_DIALOG }; +int m_nBrushOptions; +BOOL m_bUseDetail; +BOOL m_bDuplicateOnly; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CIntersectDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CIntersectDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CIntersectDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CIntersectDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp b/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp index f7684a9e..c74a635e 100644 --- a/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp +++ b/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // IntersectInfoDialog.cpp : implementation file // @@ -34,27 +34,25 @@ static char THIS_FILE[] = __FILE__; // CIntersectInfoDialog dialog -CIntersectInfoDialog::CIntersectInfoDialog(CWnd* pParent /*=NULL*/) - : CDialog(CIntersectInfoDialog::IDD, pParent) -{ +CIntersectInfoDialog::CIntersectInfoDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CIntersectInfoDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CIntersectInfoDialog) //}}AFX_DATA_INIT } -void CIntersectInfoDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CIntersectInfoDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CIntersectInfoDialog) - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); + DDX_Control( pDX, IDC_PROGRESS1, m_prog1 ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CIntersectInfoDialog, CDialog) - //{{AFX_MSG_MAP(CIntersectInfoDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CIntersectInfoDialog, CDialog ) +//{{AFX_MSG_MAP(CIntersectInfoDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/IntersectInfoDialog.h b/contrib/bobtoolz/dialogs/IntersectInfoDialog.h index 51a4bf75..58553d1e 100644 --- a/contrib/bobtoolz/dialogs/IntersectInfoDialog.h +++ b/contrib/bobtoolz/dialogs/IntersectInfoDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_) +#if !defined( AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_ ) #define AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,30 +33,30 @@ class CIntersectInfoDialog : public CDialog { // Construction public: - CIntersectInfoDialog(CWnd* pParent = NULL); // standard constructor +CIntersectInfoDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CIntersectInfoDialog) - enum { IDD = IDD_INTERSECT_INFO_DIALOG }; - CProgressCtrl m_prog1; - //}}AFX_DATA +//{{AFX_DATA(CIntersectInfoDialog) +enum { IDD = IDD_INTERSECT_INFO_DIALOG }; +CProgressCtrl m_prog1; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CIntersectInfoDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CIntersectInfoDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CIntersectInfoDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CIntersectInfoDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/PolygonDialog.cpp b/contrib/bobtoolz/dialogs/PolygonDialog.cpp index f0a38d6e..652d9cb0 100644 --- a/contrib/bobtoolz/dialogs/PolygonDialog.cpp +++ b/contrib/bobtoolz/dialogs/PolygonDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // PolygonDialog.cpp : implementation file // @@ -34,9 +34,8 @@ static char THIS_FILE[] = __FILE__; // CPolygonDialog dialog -CPolygonDialog::CPolygonDialog(CWnd* pParent /*=NULL*/) - : CDialog(CPolygonDialog::IDD, pParent) -{ +CPolygonDialog::CPolygonDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CPolygonDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CPolygonDialog) m_nSideCount = 3; m_bInverse = FALSE; @@ -46,71 +45,67 @@ CPolygonDialog::CPolygonDialog(CWnd* pParent /*=NULL*/) //}}AFX_DATA_INIT } -void CPolygonDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CPolygonDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CPolygonDialog) - DDX_Text(pDX, IDC_EDIT1, m_nSideCount); - DDV_MinMaxUInt(pDX, m_nSideCount, 3, MAX_POLYGON_FACES); - DDX_Check(pDX, IDC_INVERSE_CHK, m_bInverse); - DDX_Check(pDX, IDC_BORDER_CHK, m_bBorder); - DDX_Text(pDX, IDC_BORDER_EDIT, m_nBorderSize); - DDV_MinMaxUInt(pDX, m_nBorderSize, 1, 1024); - DDX_Check(pDX, IDC_ALIGN_CHK, m_bAlignTop); + DDX_Text( pDX, IDC_EDIT1, m_nSideCount ); + DDV_MinMaxUInt( pDX, m_nSideCount, 3, MAX_POLYGON_FACES ); + DDX_Check( pDX, IDC_INVERSE_CHK, m_bInverse ); + DDX_Check( pDX, IDC_BORDER_CHK, m_bBorder ); + DDX_Text( pDX, IDC_BORDER_EDIT, m_nBorderSize ); + DDV_MinMaxUInt( pDX, m_nBorderSize, 1, 1024 ); + DDX_Check( pDX, IDC_ALIGN_CHK, m_bAlignTop ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CPolygonDialog, CDialog) - //{{AFX_MSG_MAP(CPolygonDialog) - ON_BN_CLICKED(IDC_BORDER_CHK, OnBorderChkClicked) - ON_BN_CLICKED(IDC_INVERSE_CHK, OnInverseChkClickrd) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CPolygonDialog, CDialog ) +//{{AFX_MSG_MAP(CPolygonDialog) +ON_BN_CLICKED( IDC_BORDER_CHK, OnBorderChkClicked ) +ON_BN_CLICKED( IDC_INVERSE_CHK, OnInverseChkClickrd ) +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPolygonDialog message handlers -BOOL CPolygonDialog::OnInitDialog() -{ +BOOL CPolygonDialog::OnInitDialog(){ CDialog::OnInitDialog(); - - EnableBordered(!GetChkBool(IDC_INVERSE_CHK)); - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); - + + EnableBordered( !GetChkBool( IDC_INVERSE_CHK ) ); + EnableBorderEdit( !GetChkBool( IDC_INVERSE_CHK ) && GetChkBool( IDC_BORDER_CHK ) ); + return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } -void CPolygonDialog::EnableBordered(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_BORDER_CHK); - if(dtlChk) - dtlChk->EnableWindow(bEnable); +void CPolygonDialog::EnableBordered( BOOL bEnable ){ + CWnd* dtlChk = GetDlgItem( IDC_BORDER_CHK ); + if ( dtlChk ) { + dtlChk->EnableWindow( bEnable ); + } } -void CPolygonDialog::EnableBorderEdit(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_BORDER_EDIT); - if(dtlChk) - dtlChk->EnableWindow(bEnable); +void CPolygonDialog::EnableBorderEdit( BOOL bEnable ){ + CWnd* dtlChk = GetDlgItem( IDC_BORDER_EDIT ); + if ( dtlChk ) { + dtlChk->EnableWindow( bEnable ); + } } -void CPolygonDialog::OnBorderChkClicked() -{ - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); +void CPolygonDialog::OnBorderChkClicked(){ + EnableBorderEdit( !GetChkBool( IDC_INVERSE_CHK ) && GetChkBool( IDC_BORDER_CHK ) ); } -void CPolygonDialog::OnInverseChkClickrd() -{ - EnableBordered(!GetChkBool(IDC_INVERSE_CHK)); - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); +void CPolygonDialog::OnInverseChkClickrd(){ + EnableBordered( !GetChkBool( IDC_INVERSE_CHK ) ); + EnableBorderEdit( !GetChkBool( IDC_INVERSE_CHK ) && GetChkBool( IDC_BORDER_CHK ) ); } -BOOL CPolygonDialog::GetChkBool(int nID) -{ - CButton* btn = (CButton*)GetDlgItem(nID); - if(btn) +BOOL CPolygonDialog::GetChkBool( int nID ){ + CButton* btn = (CButton*)GetDlgItem( nID ); + if ( btn ) { return btn->GetCheck(); + } return FALSE; } diff --git a/contrib/bobtoolz/dialogs/PolygonDialog.h b/contrib/bobtoolz/dialogs/PolygonDialog.h index afe5cb87..8774e1f0 100644 --- a/contrib/bobtoolz/dialogs/PolygonDialog.h +++ b/contrib/bobtoolz/dialogs/PolygonDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_) +#if !defined( AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_ ) #define AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,39 +33,39 @@ class CPolygonDialog : public CDialog { // Construction public: - BOOL GetChkBool(int nID); - void EnableBorderEdit(BOOL bEnable); - void EnableBordered(BOOL bEnable); - CPolygonDialog(CWnd* pParent = NULL); // standard constructor +BOOL GetChkBool( int nID ); +void EnableBorderEdit( BOOL bEnable ); +void EnableBordered( BOOL bEnable ); +CPolygonDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CPolygonDialog) - enum { IDD = IDD_POLYGON_DIALOG }; - UINT m_nSideCount; - BOOL m_bInverse; - BOOL m_bBorder; - UINT m_nBorderSize; - BOOL m_bAlignTop; - //}}AFX_DATA +//{{AFX_DATA(CPolygonDialog) +enum { IDD = IDD_POLYGON_DIALOG }; +UINT m_nSideCount; +BOOL m_bInverse; +BOOL m_bBorder; +UINT m_nBorderSize; +BOOL m_bAlignTop; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPolygonDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CPolygonDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CPolygonDialog) - virtual BOOL OnInitDialog(); - afx_msg void OnBorderChkClicked(); - afx_msg void OnInverseChkClickrd(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CPolygonDialog) +virtual BOOL OnInitDialog(); +afx_msg void OnBorderChkClicked(); +afx_msg void OnInverseChkClickrd(); +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/StairDialog.cpp b/contrib/bobtoolz/dialogs/StairDialog.cpp index 4e7feba3..8b94092f 100644 --- a/contrib/bobtoolz/dialogs/StairDialog.cpp +++ b/contrib/bobtoolz/dialogs/StairDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // StairDialog.cpp : implementation file // @@ -33,73 +33,67 @@ static char THIS_FILE[] = __FILE__; // CStairDialog dialog -CStairDialog::CStairDialog(CWnd* pParent /*=NULL*/) - : CDialog(CStairDialog::IDD, pParent) -{ +CStairDialog::CStairDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CStairDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CStairDialog) m_nStairHeight = 8; m_StairDir = 0; m_StairStyle = 0; - m_riserTexture = _T(""); + m_riserTexture = _T( "" ); m_bDetail = TRUE; //}}AFX_DATA_INIT } -void CStairDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CStairDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CStairDialog) - DDX_Text(pDX, IDC_EDIT1, m_nStairHeight); - DDV_MinMaxUInt(pDX, m_nStairHeight, 1, 256); - DDX_Radio(pDX, IDC_DIR_N_RADIO, m_StairDir); - DDX_Radio(pDX, IDC_STYLE_ORIG_RADIO, m_StairStyle); - DDX_Text(pDX, IDC_RISER_EDIT, m_riserTexture); - DDV_MaxChars(pDX, m_riserTexture, 256); - DDX_Check(pDX, IDC_DETAIL_CHK, m_bDetail); + DDX_Text( pDX, IDC_EDIT1, m_nStairHeight ); + DDV_MinMaxUInt( pDX, m_nStairHeight, 1, 256 ); + DDX_Radio( pDX, IDC_DIR_N_RADIO, m_StairDir ); + DDX_Radio( pDX, IDC_STYLE_ORIG_RADIO, m_StairStyle ); + DDX_Text( pDX, IDC_RISER_EDIT, m_riserTexture ); + DDV_MaxChars( pDX, m_riserTexture, 256 ); + DDX_Check( pDX, IDC_DETAIL_CHK, m_bDetail ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CStairDialog, CDialog) - //{{AFX_MSG_MAP(CStairDialog) - ON_BN_CLICKED(IDC_STYLE_BOB_RADIO, OnStyleBobClicked) - ON_BN_CLICKED(IDC_STYLE_ORIG_RADIO, OnStyleOrigClicked) - ON_BN_CLICKED(IDC_STYLE_CORNER_RADIO, OnStyleCornerClicked) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CStairDialog, CDialog ) +//{{AFX_MSG_MAP(CStairDialog) +ON_BN_CLICKED( IDC_STYLE_BOB_RADIO, OnStyleBobClicked ) +ON_BN_CLICKED( IDC_STYLE_ORIG_RADIO, OnStyleOrigClicked ) +ON_BN_CLICKED( IDC_STYLE_CORNER_RADIO, OnStyleCornerClicked ) +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CStairDialog message handlers -void CStairDialog::OnStyleBobClicked() -{ - EnableDetail(TRUE); +void CStairDialog::OnStyleBobClicked(){ + EnableDetail( TRUE ); } -void CStairDialog::OnStyleOrigClicked() -{ - EnableDetail(FALSE); +void CStairDialog::OnStyleOrigClicked(){ + EnableDetail( FALSE ); } -void CStairDialog::EnableDetail(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_DETAIL_CHK); - if(dtlChk) - dtlChk->EnableWindow(bEnable); +void CStairDialog::EnableDetail( BOOL bEnable ){ + CWnd* dtlChk = GetDlgItem( IDC_DETAIL_CHK ); + if ( dtlChk ) { + dtlChk->EnableWindow( bEnable ); + } } -BOOL CStairDialog::OnInitDialog() -{ +BOOL CStairDialog::OnInitDialog(){ CDialog::OnInitDialog(); - - EnableDetail(m_StairStyle == 1); - + + EnableDetail( m_StairStyle == 1 ); + return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } -void CStairDialog::OnStyleCornerClicked() -{ - EnableDetail(FALSE); +void CStairDialog::OnStyleCornerClicked(){ + EnableDetail( FALSE ); } diff --git a/contrib/bobtoolz/dialogs/StairDialog.h b/contrib/bobtoolz/dialogs/StairDialog.h index 0bcdc0ec..0be13e67 100644 --- a/contrib/bobtoolz/dialogs/StairDialog.h +++ b/contrib/bobtoolz/dialogs/StairDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_) +#if !defined( AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_ ) #define AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,39 +33,39 @@ class CStairDialog : public CDialog { // Construction public: - CStairDialog(CWnd* pParent = NULL); // standard constructor +CStairDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CStairDialog) - enum { IDD = IDD_STAIR_DIALOG }; - UINT m_nStairHeight; - int m_StairDir; - int m_StairStyle; - CString m_riserTexture; - BOOL m_bDetail; - //}}AFX_DATA +//{{AFX_DATA(CStairDialog) +enum { IDD = IDD_STAIR_DIALOG }; +UINT m_nStairHeight; +int m_StairDir; +int m_StairStyle; +CString m_riserTexture; +BOOL m_bDetail; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CStairDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CStairDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CStairDialog) - afx_msg void OnStyleBobClicked(); - afx_msg void OnStyleOrigClicked(); - virtual BOOL OnInitDialog(); - afx_msg void OnStyleCornerClicked(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CStairDialog) +afx_msg void OnStyleBobClicked(); +afx_msg void OnStyleOrigClicked(); +virtual BOOL OnInitDialog(); +afx_msg void OnStyleCornerClicked(); +//}}AFX_MSG +DECLARE_MESSAGE_MAP() private: - void EnableDetail(BOOL bEnable); +void EnableDetail( BOOL bEnable ); }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/TextureResetDialog.cpp b/contrib/bobtoolz/dialogs/TextureResetDialog.cpp index 77ebc766..0913f51b 100644 --- a/contrib/bobtoolz/dialogs/TextureResetDialog.cpp +++ b/contrib/bobtoolz/dialogs/TextureResetDialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // TextureResetDialog.cpp : implementation file // @@ -34,47 +34,45 @@ static char THIS_FILE[] = __FILE__; // CTextureResetDialog dialog -CTextureResetDialog::CTextureResetDialog(CWnd* pParent /*=NULL*/) - : CDialog(CTextureResetDialog::IDD, pParent) -{ +CTextureResetDialog::CTextureResetDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CTextureResetDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CTextureResetDialog) m_bAllTextures = FALSE; - m_TextureName = _T(""); + m_TextureName = _T( "" ); m_nRotation = 0; m_fScaleHorizontal = 0.5f; m_fScaleVertical = 0.5f; m_nShiftHorizontal = 0; m_nShiftVertical = 0; m_bOnlyTexture = FALSE; - m_NewTextureName = _T(""); + m_NewTextureName = _T( "" ); //}}AFX_DATA_INIT } -void CTextureResetDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CTextureResetDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CTextureResetDialog) - DDX_Check(pDX, IDC_ALLTEXTURES_CHECK, m_bAllTextures); - DDX_Text(pDX, IDC_RESET_TEXTURE_EDIT, m_TextureName); - DDV_MaxChars(pDX, m_TextureName, 256); - DDX_Text(pDX, IDC_ROTATION_EDIT, m_nRotation); - DDV_MinMaxInt(pDX, m_nRotation, 0, 360); - DDX_Text(pDX, IDC_SCL_HOR_EDIT, m_fScaleHorizontal); - DDX_Text(pDX, IDC_SCL_VERT_EDIT, m_fScaleVertical); - DDX_Text(pDX, IDC_SHFT_HOR_EDIT, m_nShiftHorizontal); - DDX_Text(pDX, IDC_SHFT_VER_EDIT, m_nShiftVertical); - DDX_Check(pDX, IDC_ONLYTEXTURE_CHECK, m_bOnlyTexture); - DDX_Text(pDX, IDC_RESET_NEW_TEXTURE_EDIT, m_NewTextureName); - DDV_MaxChars(pDX, m_NewTextureName, 256); + DDX_Check( pDX, IDC_ALLTEXTURES_CHECK, m_bAllTextures ); + DDX_Text( pDX, IDC_RESET_TEXTURE_EDIT, m_TextureName ); + DDV_MaxChars( pDX, m_TextureName, 256 ); + DDX_Text( pDX, IDC_ROTATION_EDIT, m_nRotation ); + DDV_MinMaxInt( pDX, m_nRotation, 0, 360 ); + DDX_Text( pDX, IDC_SCL_HOR_EDIT, m_fScaleHorizontal ); + DDX_Text( pDX, IDC_SCL_VERT_EDIT, m_fScaleVertical ); + DDX_Text( pDX, IDC_SHFT_HOR_EDIT, m_nShiftHorizontal ); + DDX_Text( pDX, IDC_SHFT_VER_EDIT, m_nShiftVertical ); + DDX_Check( pDX, IDC_ONLYTEXTURE_CHECK, m_bOnlyTexture ); + DDX_Text( pDX, IDC_RESET_NEW_TEXTURE_EDIT, m_NewTextureName ); + DDV_MaxChars( pDX, m_NewTextureName, 256 ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CTextureResetDialog, CDialog) - //{{AFX_MSG_MAP(CTextureResetDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CTextureResetDialog, CDialog ) +//{{AFX_MSG_MAP(CTextureResetDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/TextureResetDialog.h b/contrib/bobtoolz/dialogs/TextureResetDialog.h index 6f041611..40260735 100644 --- a/contrib/bobtoolz/dialogs/TextureResetDialog.h +++ b/contrib/bobtoolz/dialogs/TextureResetDialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,38 +33,38 @@ class CTextureResetDialog : public CDialog { // Construction public: - CTextureResetDialog(CWnd* pParent = NULL); // standard constructor +CTextureResetDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CTextureResetDialog) - enum { IDD = IDD_TEXTURE_RESET_DIALOG }; - BOOL m_bAllTextures; - CString m_TextureName; - int m_nRotation; - float m_fScaleHorizontal; - float m_fScaleVertical; - int m_nShiftHorizontal; - int m_nShiftVertical; - BOOL m_bOnlyTexture; - CString m_NewTextureName; - //}}AFX_DATA +//{{AFX_DATA(CTextureResetDialog) +enum { IDD = IDD_TEXTURE_RESET_DIALOG }; +BOOL m_bAllTextures; +CString m_TextureName; +int m_nRotation; +float m_fScaleHorizontal; +float m_fScaleVertical; +int m_nShiftHorizontal; +int m_nShiftVertical; +BOOL m_bOnlyTexture; +CString m_NewTextureName; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CTextureResetDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CTextureResetDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CTextureResetDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CTextureResetDialog) +// NOTE: the ClassWizard will add member functions here +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/dialogs/brushcheckdialog.cpp b/contrib/bobtoolz/dialogs/brushcheckdialog.cpp index 06fe6c9b..3b3ac607 100644 --- a/contrib/bobtoolz/dialogs/brushcheckdialog.cpp +++ b/contrib/bobtoolz/dialogs/brushcheckdialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // BrushCheckDialog.cpp : implementation file // @@ -34,27 +34,25 @@ static char THIS_FILE[] = __FILE__; // CBrushCheckDialog dialog -CBrushCheckDialog::CBrushCheckDialog(CWnd* pParent /*=NULL*/) - : CDialog(CBrushCheckDialog::IDD, pParent) -{ +CBrushCheckDialog::CBrushCheckDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CBrushCheckDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CBrushCheckDialog) //}}AFX_DATA_INIT } -void CBrushCheckDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CBrushCheckDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CBrushCheckDialog) - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); + DDX_Control( pDX, IDC_PROGRESS1, m_prog1 ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CBrushCheckDialog, CDialog) - //{{AFX_MSG_MAP(CBrushCheckDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CBrushCheckDialog, CDialog ) +//{{AFX_MSG_MAP(CBrushCheckDialog) +// NOTE: the ClassWizard will add message map macros here +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// diff --git a/contrib/bobtoolz/dialogs/dialogs-gtk.cpp b/contrib/bobtoolz/dialogs/dialogs-gtk.cpp index 927c7887..b596f059 100644 --- a/contrib/bobtoolz/dialogs/dialogs-gtk.cpp +++ b/contrib/bobtoolz/dialogs/dialogs-gtk.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "dialogs-gtk.h" #include "../funchandlers.h" @@ -30,17 +30,17 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /*-------------------------------- - Callback Functions ----------------------------------*/ + Callback Functions + ---------------------------------*/ typedef struct { GtkWidget *cbTexChange; GtkWidget *editTexOld, *editTexNew; - GtkWidget *cbScaleHor, *cbScaleVert; + GtkWidget *cbScaleHor, *cbScaleVert; GtkWidget *editScaleHor, *editScaleVert; - GtkWidget *cbShiftHor, *cbShiftVert; + GtkWidget *cbShiftHor, *cbShiftVert; GtkWidget *editShiftHor, *editShiftVert; GtkWidget *cbRotation; @@ -51,84 +51,76 @@ dlg_texReset_t dlgTexReset; void Update_TextureReseter(); -static void dialog_button_callback_texreset_update (GtkWidget *widget, gpointer data) -{ - Update_TextureReseter(); +static void dialog_button_callback_texreset_update( GtkWidget *widget, gpointer data ){ + Update_TextureReseter(); } -void Update_TextureReseter() -{ - gboolean check; +void Update_TextureReseter(){ + gboolean check; - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editTexNew), check); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editTexOld), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editTexNew ), check ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editTexOld ), check ); - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editScaleHor), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editScaleHor ), check ); - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editScaleVert), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editScaleVert ), check ); - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editShiftHor), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editShiftHor ), check ); - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editShiftVert), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editShiftVert ), check ); - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editRotation), check); + check = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation ) ); + gtk_entry_set_editable( GTK_ENTRY( dlgTexReset.editRotation ), check ); } -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ +static void dialog_button_callback( GtkWidget *widget, gpointer data ){ GtkWidget *parent; int *loop; - EMessageBoxReturn *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (EMessageBoxReturn*)g_object_get_data (G_OBJECT (parent), "ret"); - + EMessageBoxReturn *ret; + + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + ret = (EMessageBoxReturn*)g_object_get_data( G_OBJECT( parent ), "ret" ); + *loop = 0; - *ret = (EMessageBoxReturn)gpointer_to_int(data); + *ret = (EMessageBoxReturn)gpointer_to_int( data ); } - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ + +static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); + + gtk_widget_hide( widget ); + loop = (int*)g_object_get_data( G_OBJECT( widget ), "loop" ); *loop = 0; return TRUE; } -static void dialog_button_callback_settex (GtkWidget *widget, gpointer data) -{ +static void dialog_button_callback_settex( GtkWidget *widget, gpointer data ){ TwinWidget* tw = (TwinWidget*)data; GtkEntry* entry = GTK_ENTRY( tw->one ); GtkCombo* combo = GTK_COMBO( tw->two ); - const gchar* tex = gtk_entry_get_text(GTK_ENTRY( combo->entry )); - gtk_entry_set_text( entry, tex); + const gchar* tex = gtk_entry_get_text( GTK_ENTRY( combo->entry ) ); + gtk_entry_set_text( entry, tex ); } /*-------------------------------- - Data validation Routines ----------------------------------*/ + Data validation Routines + ---------------------------------*/ -bool ValidateTextFloat(const char* pData, char* error_title, float* value) -{ - if(pData) - { - float testNum = (float)atof(pData); +bool ValidateTextFloat( const char* pData, char* error_title, float* value ){ + if ( pData ) { + float testNum = (float)atof( pData ); - if((testNum == 0.0f) && strcmp(pData, "0")) - { - DoMessageBox("Please Enter A Floating Point Number", error_title, eMB_OK); + if ( ( testNum == 0.0f ) && strcmp( pData, "0" ) ) { + DoMessageBox( "Please Enter A Floating Point Number", error_title, eMB_OK ); return FALSE; } else @@ -138,22 +130,19 @@ bool ValidateTextFloat(const char* pData, char* error_title, float* value) } } - DoMessageBox("Please Enter A Floating Point Number", error_title, eMB_OK); + DoMessageBox( "Please Enter A Floating Point Number", error_title, eMB_OK ); return FALSE; } -bool ValidateTextFloatRange(const char* pData, float min, float max, char* error_title, float* value) -{ +bool ValidateTextFloatRange( const char* pData, float min, float max, char* error_title, float* value ){ char error_buffer[256]; - sprintf(error_buffer, "Please Enter A Floating Point Number Between %.3f and %.3f", min, max); + sprintf( error_buffer, "Please Enter A Floating Point Number Between %.3f and %.3f", min, max ); - if(pData) - { - float testNum = (float)atof(pData); + if ( pData ) { + float testNum = (float)atof( pData ); - if((testNum < min) || (testNum > max)) - { - DoMessageBox(error_buffer, error_title, eMB_OK); + if ( ( testNum < min ) || ( testNum > max ) ) { + DoMessageBox( error_buffer, error_title, eMB_OK ); return FALSE; } else @@ -163,22 +152,19 @@ bool ValidateTextFloatRange(const char* pData, float min, float max, char* error } } - DoMessageBox(error_buffer, error_title, eMB_OK); + DoMessageBox( error_buffer, error_title, eMB_OK ); return FALSE; } -bool ValidateTextIntRange(const char* pData, int min, int max, char* error_title, int* value) -{ +bool ValidateTextIntRange( const char* pData, int min, int max, char* error_title, int* value ){ char error_buffer[256]; - sprintf(error_buffer, "Please Enter An Integer Between %i and %i", min, max); + sprintf( error_buffer, "Please Enter An Integer Between %i and %i", min, max ); - if(pData) - { - int testNum = atoi(pData); + if ( pData ) { + int testNum = atoi( pData ); - if((testNum < min) || (testNum > max)) - { - DoMessageBox(error_buffer, error_title, eMB_OK); + if ( ( testNum < min ) || ( testNum > max ) ) { + DoMessageBox( error_buffer, error_title, eMB_OK ); return FALSE; } else @@ -188,19 +174,16 @@ bool ValidateTextIntRange(const char* pData, int min, int max, char* error_title } } - DoMessageBox(error_buffer, error_title, eMB_OK); + DoMessageBox( error_buffer, error_title, eMB_OK ); return FALSE; } -bool ValidateTextInt(const char* pData, char* error_title, int* value) -{ - if(pData) - { - int testNum = atoi(pData); +bool ValidateTextInt( const char* pData, char* error_title, int* value ){ + if ( pData ) { + int testNum = atoi( pData ); - if((testNum == 0) && strcmp(pData, "0")) - { - DoMessageBox("Please Enter An Integer", error_title, eMB_OK); + if ( ( testNum == 0 ) && strcmp( pData, "0" ) ) { + DoMessageBox( "Please Enter An Integer", error_title, eMB_OK ); return FALSE; } else @@ -210,396 +193,392 @@ bool ValidateTextInt(const char* pData, char* error_title, int* value) } } - DoMessageBox("Please Enter An Integer", error_title, eMB_OK); + DoMessageBox( "Please Enter An Integer", error_title, eMB_OK ); return FALSE; } /*-------------------------------- - Modal Dialog Boxes ----------------------------------*/ + Modal Dialog Boxes + ---------------------------------*/ /* - Major clean up of variable names etc required, excluding Mars's ones, - which are nicely done :) + Major clean up of variable names etc required, excluding Mars's ones, + which are nicely done :) -*/ + */ -EMessageBoxReturn DoMessageBox (const char* lpText, const char* lpCaption, EMessageBoxType type) -{ +EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMessageBoxType type ){ GtkWidget *window, *w, *vbox, *hbox; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_signal_connect (GTK_OBJECT (window), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_title (GTK_WINDOW (window), lpCaption); - gtk_container_border_width (GTK_CONTAINER (window), 10); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - w = gtk_label_new (lpText); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - if (type == eMB_OK) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_title( GTK_WINDOW( window ), lpCaption ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + gtk_widget_realize( window ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + + w = gtk_label_new( lpText ); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + if ( type == eMB_OK ) { + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); ret = eIDOK; } - else if (type == eMB_OKCANCEL) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + else if ( type == eMB_OKCANCEL ) { + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; } - else if (type == eMB_YESNOCANCEL) - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDNO)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + else if ( type == eMB_YESNOCANCEL ) { + w = gtk_button_new_with_label( "Yes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "No" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; } else /* if (mode == MB_YESNO) */ { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDNO)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Yes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "No" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); + gtk_widget_show( w ); ret = eIDNO; } - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - + + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); + return ret; } -EMessageBoxReturn DoIntersectBox (IntersectRS* rs) -{ +EMessageBoxReturn DoIntersectBox( IntersectRS* rs ){ GtkWidget *window, *w, *vbox, *hbox; GtkWidget *radio1, *radio2; GtkWidget *check1, *check2; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Intersect"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + + gtk_window_set_title( GTK_WINDOW( window ), "Intersect" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + // ---- vbox ---- - - radio1 = gtk_radio_button_new_with_label(NULL, "Use Whole Map"); - gtk_box_pack_start (GTK_BOX (vbox), radio1, FALSE, FALSE, 2); - gtk_widget_show (radio1); - - radio2 = gtk_radio_button_new_with_label(((GtkRadioButton*)radio1)->group, "Use Selected Brushes"); - gtk_box_pack_start (GTK_BOX (vbox), radio2, FALSE, FALSE, 2); - gtk_widget_show (radio2); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - check1 = gtk_check_button_new_with_label("Include Detail Brushes"); - gtk_box_pack_start (GTK_BOX (vbox), check1, FALSE, FALSE, 0); - gtk_widget_show (check1); - - check2 = gtk_check_button_new_with_label("Select Duplicate Brushes Only"); - gtk_box_pack_start (GTK_BOX (vbox), check2, FALSE, FALSE, 0); - gtk_widget_show (check2); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- ok/cancel buttons - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - // ---- /hbox ---- - + radio1 = gtk_radio_button_new_with_label( NULL, "Use Whole Map" ); + gtk_box_pack_start( GTK_BOX( vbox ), radio1, FALSE, FALSE, 2 ); + gtk_widget_show( radio1 ); + + radio2 = gtk_radio_button_new_with_label( ( (GtkRadioButton*)radio1 )->group, "Use Selected Brushes" ); + gtk_box_pack_start( GTK_BOX( vbox ), radio2, FALSE, FALSE, 2 ); + gtk_widget_show( radio2 ); + + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); + + check1 = gtk_check_button_new_with_label( "Include Detail Brushes" ); + gtk_box_pack_start( GTK_BOX( vbox ), check1, FALSE, FALSE, 0 ); + gtk_widget_show( check1 ); + + check2 = gtk_check_button_new_with_label( "Select Duplicate Brushes Only" ); + gtk_box_pack_start( GTK_BOX( vbox ), check2, FALSE, FALSE, 0 ); + gtk_widget_show( check2 ); + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- ok/cancel buttons + + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + ret = eIDCANCEL; + + // ---- /hbox ---- + // ---- /vbox ---- - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + + while ( loop ) + gtk_main_iteration(); - if(gtk_toggle_button_get_active((GtkToggleButton*)radio1)) + if ( gtk_toggle_button_get_active( (GtkToggleButton*)radio1 ) ) { rs->nBrushOptions = BRUSH_OPT_WHOLE_MAP; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radio2)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radio2 ) ) { rs->nBrushOptions = BRUSH_OPT_SELECTED; + } - rs->bUseDetail = gtk_toggle_button_get_active((GtkToggleButton*)check1) ? true : false; - rs->bDuplicateOnly = gtk_toggle_button_get_active((GtkToggleButton*)check2) ? true : false; - - gtk_grab_remove (window); - gtk_widget_destroy (window); + rs->bUseDetail = gtk_toggle_button_get_active( (GtkToggleButton*)check1 ) ? true : false; + rs->bDuplicateOnly = gtk_toggle_button_get_active( (GtkToggleButton*)check2 ) ? true : false; + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } -EMessageBoxReturn DoPolygonBox (PolygonRS* rs) -{ +EMessageBoxReturn DoPolygonBox( PolygonRS* rs ){ GtkWidget *window, *w, *vbox, *hbox, *vbox2, *hbox2; GtkWidget *check1, *check2, *check3; GtkWidget *text1, *text2; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Polygon Builder"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + + gtk_window_set_title( GTK_WINDOW( window ), "Polygon Builder" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + // ---- vbox ---- - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - - vbox2 = gtk_vbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (hbox), vbox2, FALSE, FALSE, 2); - gtk_widget_show (vbox2); - - // ---- vbox2 ---- - - hbox2 = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox2), hbox2, FALSE, FALSE, 2); - gtk_widget_show (hbox2); - - // ---- hbox2 ---- - - text1 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text1, "3"); - gtk_box_pack_start (GTK_BOX (hbox2), text1, FALSE, FALSE, 2); - gtk_widget_show (text1); - - w = gtk_label_new ("Number Of Sides"); - gtk_box_pack_start (GTK_BOX (hbox2), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox2 ---- - - hbox2 = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox2), hbox2, FALSE, FALSE, 2); - gtk_widget_show (hbox2); - - // ---- hbox2 ---- - - text2 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text2, "8"); - gtk_box_pack_start (GTK_BOX (hbox2), text2, FALSE, FALSE, 2); - gtk_widget_show (text2); - - w = gtk_label_new ("Border Width"); - gtk_box_pack_start (GTK_BOX (hbox2), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox2 ---- - - // ---- /vbox2 ---- - - - - vbox2 = gtk_vbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (hbox), vbox2, FALSE, FALSE, 2); - gtk_widget_show (vbox2); - - // ---- vbox2 ---- - - check1 = gtk_check_button_new_with_label("Use Border"); - gtk_box_pack_start (GTK_BOX (vbox2), check1, FALSE, FALSE, 0); - gtk_widget_show (check1); - - - check2 = gtk_check_button_new_with_label("Inverse Polygon"); - gtk_box_pack_start (GTK_BOX (vbox2), check2, FALSE, FALSE, 0); - gtk_widget_show (check2); - - - check3 = gtk_check_button_new_with_label("Align Top Edge"); - gtk_box_pack_start (GTK_BOX (vbox2), check3, FALSE, FALSE, 0); - gtk_widget_show (check3); - - // ---- /vbox2 ---- - - // ---- /hbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + + vbox2 = gtk_vbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( hbox ), vbox2, FALSE, FALSE, 2 ); + gtk_widget_show( vbox2 ); + + // ---- vbox2 ---- + + hbox2 = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox2, FALSE, FALSE, 2 ); + gtk_widget_show( hbox2 ); + + // ---- hbox2 ---- + + text1 = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( (GtkEntry*)text1, "3" ); + gtk_box_pack_start( GTK_BOX( hbox2 ), text1, FALSE, FALSE, 2 ); + gtk_widget_show( text1 ); + + w = gtk_label_new( "Number Of Sides" ); + gtk_box_pack_start( GTK_BOX( hbox2 ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + // ---- /hbox2 ---- + + hbox2 = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox2, FALSE, FALSE, 2 ); + gtk_widget_show( hbox2 ); + + // ---- hbox2 ---- + + text2 = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( (GtkEntry*)text2, "8" ); + gtk_box_pack_start( GTK_BOX( hbox2 ), text2, FALSE, FALSE, 2 ); + gtk_widget_show( text2 ); + + w = gtk_label_new( "Border Width" ); + gtk_box_pack_start( GTK_BOX( hbox2 ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + // ---- /hbox2 ---- + + // ---- /vbox2 ---- + + + + vbox2 = gtk_vbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( hbox ), vbox2, FALSE, FALSE, 2 ); + gtk_widget_show( vbox2 ); + + // ---- vbox2 ---- + + check1 = gtk_check_button_new_with_label( "Use Border" ); + gtk_box_pack_start( GTK_BOX( vbox2 ), check1, FALSE, FALSE, 0 ); + gtk_widget_show( check1 ); + + + check2 = gtk_check_button_new_with_label( "Inverse Polygon" ); + gtk_box_pack_start( GTK_BOX( vbox2 ), check2, FALSE, FALSE, 0 ); + gtk_widget_show( check2 ); + + + check3 = gtk_check_button_new_with_label( "Align Top Edge" ); + gtk_box_pack_start( GTK_BOX( vbox2 ), check3, FALSE, FALSE, 0 ); + gtk_widget_show( check3 ); + + // ---- /vbox2 ---- + + // ---- /hbox ---- + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + ret = eIDCANCEL; + + // ---- /hbox ---- + // ---- /vbox ---- - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if(ret == eIDOK) - { - rs->bUseBorder = gtk_toggle_button_get_active((GtkToggleButton*)check1) ? true : false; - rs->bInverse = gtk_toggle_button_get_active((GtkToggleButton*)check2) ? true : false; - rs->bAlignTop = gtk_toggle_button_get_active((GtkToggleButton*)check3) ? true : false; + if ( ret == eIDOK ) { + rs->bUseBorder = gtk_toggle_button_get_active( (GtkToggleButton*)check1 ) ? true : false; + rs->bInverse = gtk_toggle_button_get_active( (GtkToggleButton*)check2 ) ? true : false; + rs->bAlignTop = gtk_toggle_button_get_active( (GtkToggleButton*)check3 ) ? true : false; - if(!ValidateTextIntRange(gtk_entry_get_text((GtkEntry*)text1), 3, 32, "Number Of Sides", &rs->nSides)) + if ( !ValidateTextIntRange( gtk_entry_get_text( (GtkEntry*)text1 ), 3, 32, "Number Of Sides", &rs->nSides ) ) { dialogError = TRUE; + } - if(rs->bUseBorder) - { - if(!ValidateTextIntRange(gtk_entry_get_text((GtkEntry*)text2), 8, 256, "Border Width", &rs->nBorderWidth)) + if ( rs->bUseBorder ) { + if ( !ValidateTextIntRange( gtk_entry_get_text( (GtkEntry*)text2 ), 8, 256, "Border Width", &rs->nBorderWidth ) ) { dialogError = TRUE; + } } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } @@ -607,35 +586,34 @@ EMessageBoxReturn DoPolygonBox (PolygonRS* rs) // mars // for stair builder stuck as close as i could to the MFC version // obviously feel free to change it at will :) -EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) -{ - // i made widgets for just about everything ... i think that's what i need to do dunno tho - GtkWidget *window, *w, *vbox, *hbox; - GtkWidget *textStairHeight, *textRiserTex, *textMainTex; - GtkWidget *radioNorth, *radioSouth, *radioEast, *radioWest; // i'm guessing we can't just abuse 'w' for these if we're getting a value - GtkWidget *radioOldStyle, *radioBobStyle, *radioCornerStyle; - GtkWidget *checkUseDetail; - GSList *radioDirection, *radioStyle; +EMessageBoxReturn DoBuildStairsBox( BuildStairsRS* rs ){ + // i made widgets for just about everything ... i think that's what i need to do dunno tho + GtkWidget *window, *w, *vbox, *hbox; + GtkWidget *textStairHeight, *textRiserTex, *textMainTex; + GtkWidget *radioNorth, *radioSouth, *radioEast, *radioWest; // i'm guessing we can't just abuse 'w' for these if we're getting a value + GtkWidget *radioOldStyle, *radioBobStyle, *radioCornerStyle; + GtkWidget *checkUseDetail; + GSList *radioDirection, *radioStyle; EMessageBoxReturn ret; - int loop = 1; + int loop = 1; - char *text = "Please set a value in the boxes below and press 'OK' to build the stairs"; + char *text = "Please set a value in the boxes below and press 'OK' to build the stairs"; window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), "Stair Builder" ); - + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize (window); + gtk_widget_realize( window ); - // new vbox + // new vbox vbox = gtk_vbox_new( FALSE, 10 ); gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); @@ -643,7 +621,7 @@ EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) hbox = gtk_hbox_new( FALSE, 10 ); gtk_container_add( GTK_CONTAINER( vbox ), hbox ); gtk_widget_show( hbox ); - + // dunno if you want this text or not ... w = gtk_label_new( text ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); // not entirely sure on all the parameters / what they do ... @@ -652,21 +630,21 @@ EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) w = gtk_hseparator_new(); gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - + // ------------------------- // indenting == good way of keeping track of lines :) - // new hbox - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textStairHeight = gtk_entry_new_with_max_length( 256 ); - gtk_box_pack_start( GTK_BOX( hbox ), textStairHeight, FALSE, FALSE, 1 ); - gtk_widget_show( textStairHeight ); - - w = gtk_label_new( "Stair Height" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); + // new hbox + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); + + textStairHeight = gtk_entry_new_with_max_length( 256 ); + gtk_box_pack_start( GTK_BOX( hbox ), textStairHeight, FALSE, FALSE, 1 ); + gtk_widget_show( textStairHeight ); + + w = gtk_label_new( "Stair Height" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); + gtk_widget_show( w ); // ------------------------- // @@ -680,37 +658,37 @@ EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) // -------------------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - // radio buttons confuse me ... - // but this _looks_ right + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); + + // radio buttons confuse me ... + // but this _looks_ right + + // djbob: actually it looks very nice :), slightly better than the way i did it + // edit: actually it doesn't work :P, you must pass the last radio item each time, ugh - // djbob: actually it looks very nice :), slightly better than the way i did it - // edit: actually it doesn't work :P, you must pass the last radio item each time, ugh + radioNorth = gtk_radio_button_new_with_label( NULL, "North" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioNorth, FALSE, FALSE, 3 ); + gtk_widget_show( radioNorth ); - radioNorth = gtk_radio_button_new_with_label( NULL, "North" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioNorth, FALSE, FALSE, 3 ); - gtk_widget_show( radioNorth ); + radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNorth ) ); - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNorth ) ); - - radioSouth = gtk_radio_button_new_with_label( radioDirection, "South" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioSouth, FALSE, FALSE, 2 ); - gtk_widget_show( radioSouth ); + radioSouth = gtk_radio_button_new_with_label( radioDirection, "South" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioSouth, FALSE, FALSE, 2 ); + gtk_widget_show( radioSouth ); - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioSouth ) ); + radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioSouth ) ); - radioEast = gtk_radio_button_new_with_label( radioDirection, "East" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioEast, FALSE, FALSE, 1 ); - gtk_widget_show( radioEast ); + radioEast = gtk_radio_button_new_with_label( radioDirection, "East" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioEast, FALSE, FALSE, 1 ); + gtk_widget_show( radioEast ); - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioEast ) ); + radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioEast ) ); - radioWest = gtk_radio_button_new_with_label( radioDirection, "West" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioWest, FALSE, FALSE, 0 ); - gtk_widget_show( radioWest ); + radioWest = gtk_radio_button_new_with_label( radioDirection, "West" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioWest, FALSE, FALSE, 0 ); + gtk_widget_show( radioWest ); // --------------------------- // @@ -724,45 +702,45 @@ EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) // --------------------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - radioOldStyle = gtk_radio_button_new_with_label( NULL, "Original" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioOldStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioOldStyle ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); + + radioOldStyle = gtk_radio_button_new_with_label( NULL, "Original" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioOldStyle, FALSE, FALSE, 0 ); + gtk_widget_show( radioOldStyle ); - radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioOldStyle ) ); + radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioOldStyle ) ); - radioBobStyle = gtk_radio_button_new_with_label( radioStyle, "Bob's Style" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioBobStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioBobStyle ); - - radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioBobStyle ) ); + radioBobStyle = gtk_radio_button_new_with_label( radioStyle, "Bob's Style" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioBobStyle, FALSE, FALSE, 0 ); + gtk_widget_show( radioBobStyle ); - radioCornerStyle = gtk_radio_button_new_with_label( radioStyle, "Corner Style" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioCornerStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioCornerStyle ); - - // err, the q3r has an if or something so you need bob style checked before this - // is "ungreyed out" but you'll need to do that, as i suck :) + radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioBobStyle ) ); - // djbob: er.... yeah um, im not at all sure how i'm gonna sort this - // djbob: think we need some button callback functions or smuffin - // FIXME: actually get around to doing what i suggested!!!! + radioCornerStyle = gtk_radio_button_new_with_label( radioStyle, "Corner Style" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioCornerStyle, FALSE, FALSE, 0 ); + gtk_widget_show( radioCornerStyle ); - checkUseDetail = gtk_check_button_new_with_label( "Use Detail Brushes" ); - gtk_box_pack_start( GTK_BOX( hbox ), checkUseDetail, FALSE, FALSE, 0 ); - gtk_widget_show( checkUseDetail ); + // err, the q3r has an if or something so you need bob style checked before this + // is "ungreyed out" but you'll need to do that, as i suck :) - // --------------------------- // + // djbob: er.... yeah um, im not at all sure how i'm gonna sort this + // djbob: think we need some button callback functions or smuffin + // FIXME: actually get around to doing what i suggested!!!! + + checkUseDetail = gtk_check_button_new_with_label( "Use Detail Brushes" ); + gtk_box_pack_start( GTK_BOX( hbox ), checkUseDetail, FALSE, FALSE, 0 ); + gtk_widget_show( checkUseDetail ); + + // --------------------------- // hbox = gtk_hbox_new( FALSE, 10 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); textMainTex = gtk_entry_new_with_max_length( 512 ); - gtk_entry_set_text(GTK_ENTRY(textMainTex), rs->mainTexture); + gtk_entry_set_text( GTK_ENTRY( textMainTex ), rs->mainTexture ); gtk_box_pack_start( GTK_BOX( hbox ), textMainTex, FALSE, FALSE, 0 ); gtk_widget_show( textMainTex ); @@ -794,856 +772,870 @@ EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) gtk_widget_show( hbox ); w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); gtk_widget_show( w ); - + w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); gtk_widget_show( w ); - + ret = eIDCANCEL; // +djbob: need our "little" modal loop mars :P - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if(ret == eIDOK) - { - rs->bUseDetail = gtk_toggle_button_get_active((GtkToggleButton*)checkUseDetail) ? true : false; + if ( ret == eIDOK ) { + rs->bUseDetail = gtk_toggle_button_get_active( (GtkToggleButton*)checkUseDetail ) ? true : false; - strcpy(rs->riserTexture, gtk_entry_get_text((GtkEntry*)textRiserTex)); - strcpy(rs->mainTexture, gtk_entry_get_text((GtkEntry*)textMainTex)); + strcpy( rs->riserTexture, gtk_entry_get_text( (GtkEntry*)textRiserTex ) ); + strcpy( rs->mainTexture, gtk_entry_get_text( (GtkEntry*)textMainTex ) ); - if(gtk_toggle_button_get_active((GtkToggleButton*)radioNorth)) + if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioNorth ) ) { rs->direction = MOVE_NORTH; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioSouth)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioSouth ) ) { rs->direction = MOVE_SOUTH; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioEast)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioEast ) ) { rs->direction = MOVE_EAST; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioWest)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioWest ) ) { rs->direction = MOVE_WEST; + } - if(!ValidateTextInt(gtk_entry_get_text((GtkEntry*)textStairHeight), "Stair Height", &rs->stairHeight)) + if ( !ValidateTextInt( gtk_entry_get_text( (GtkEntry*)textStairHeight ), "Stair Height", &rs->stairHeight ) ) { dialogError = TRUE; + } - if(gtk_toggle_button_get_active((GtkToggleButton*)radioOldStyle)) + if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioOldStyle ) ) { rs->style = STYLE_ORIGINAL; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioBobStyle)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioBobStyle ) ) { rs->style = STYLE_BOB; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioCornerStyle)) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)radioCornerStyle ) ) { rs->style = STYLE_CORNER; + } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; // -djbob - + // there we go, all done ... on my end at least, not bad for a night's work } -EMessageBoxReturn DoDoorsBox(DoorRS* rs) -{ - GtkWidget *window, *hbox, *vbox, *w; - GtkWidget *textFrontBackTex, *textTrimTex; - GtkWidget *checkScaleMainH, *checkScaleMainV, *checkScaleTrimH, *checkScaleTrimV; - GtkWidget *comboMain, *comboTrim; - GtkWidget *buttonSetMain, *buttonSetTrim; - GtkWidget *radioNS, *radioEW; - GSList *radioOrientation; - TwinWidget tw1, tw2; +EMessageBoxReturn DoDoorsBox( DoorRS* rs ){ + GtkWidget *window, *hbox, *vbox, *w; + GtkWidget *textFrontBackTex, *textTrimTex; + GtkWidget *checkScaleMainH, *checkScaleMainV, *checkScaleTrimH, *checkScaleTrimV; + GtkWidget *comboMain, *comboTrim; + GtkWidget *buttonSetMain, *buttonSetTrim; + GtkWidget *radioNS, *radioEW; + GSList *radioOrientation; + TwinWidget tw1, tw2; EMessageBoxReturn ret; - int loop = 1; - + int loop = 1; + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), "Door Builder" ); - + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); g_object_set_data( G_OBJECT( window ), "loop", &loop ); g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize (window); - + gtk_widget_realize( window ); + char buffer[256]; - GList *listMainTextures = NULL; - GList *listTrimTextures = NULL; - LoadGList(GetFilename(buffer, "plugins/bt/door-tex.txt"), &listMainTextures); - LoadGList(GetFilename(buffer, "plugins/bt/door-tex-trim.txt"), &listTrimTextures); - + GList *listMainTextures = NULL; + GList *listTrimTextures = NULL; + LoadGList( GetFilename( buffer, "plugins/bt/door-tex.txt" ), &listMainTextures ); + LoadGList( GetFilename( buffer, "plugins/bt/door-tex-trim.txt" ), &listTrimTextures ); + vbox = gtk_vbox_new( FALSE, 10 ); gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); // -------------------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - textFrontBackTex = gtk_entry_new_with_max_length( 512 ); - gtk_entry_set_text( GTK_ENTRY( textFrontBackTex ), rs->mainTexture); - gtk_box_pack_start( GTK_BOX( hbox ), textFrontBackTex, FALSE, FALSE, 0 ); - gtk_widget_show( textFrontBackTex ); + textFrontBackTex = gtk_entry_new_with_max_length( 512 ); + gtk_entry_set_text( GTK_ENTRY( textFrontBackTex ), rs->mainTexture ); + gtk_box_pack_start( GTK_BOX( hbox ), textFrontBackTex, FALSE, FALSE, 0 ); + gtk_widget_show( textFrontBackTex ); - w = gtk_label_new( "Door Front/Back Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "Door Front/Back Texture" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); // ------------------------ // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - textTrimTex = gtk_entry_new_with_max_length( 512 ); - gtk_box_pack_start( GTK_BOX( hbox ), textTrimTex, FALSE, FALSE, 0 ); - gtk_widget_show( textTrimTex ); + textTrimTex = gtk_entry_new_with_max_length( 512 ); + gtk_box_pack_start( GTK_BOX( hbox ), textTrimTex, FALSE, FALSE, 0 ); + gtk_widget_show( textTrimTex ); - w = gtk_label_new( "Door Trim Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "Door Trim Texture" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); // ----------------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - // sp: horizontally ???? - // djbob: yes mars, u can spell :] - checkScaleMainH = gtk_check_button_new_with_label( "Scale Main Texture Horizontally" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleMainH ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainH, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleMainH ); + // sp: horizontally ???? + // djbob: yes mars, u can spell :] + checkScaleMainH = gtk_check_button_new_with_label( "Scale Main Texture Horizontally" ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( checkScaleMainH ), TRUE ); + gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainH, FALSE, FALSE, 0 ); + gtk_widget_show( checkScaleMainH ); - checkScaleTrimH = gtk_check_button_new_with_label( "Scale Trim Texture Horizontally" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleTrimH ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimH, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleTrimH ); + checkScaleTrimH = gtk_check_button_new_with_label( "Scale Trim Texture Horizontally" ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( checkScaleTrimH ), TRUE ); + gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimH, FALSE, FALSE, 0 ); + gtk_widget_show( checkScaleTrimH ); // ---------------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - checkScaleMainV = gtk_check_button_new_with_label( "Scale Main Texture Vertically" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleMainV ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainV, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleMainV ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - checkScaleTrimV = gtk_check_button_new_with_label( "Scale Trim Texture Vertically" ); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimV, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleTrimV ); - - // --------------------- // + checkScaleMainV = gtk_check_button_new_with_label( "Scale Main Texture Vertically" ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( checkScaleMainV ), TRUE ); + gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainV, FALSE, FALSE, 0 ); + gtk_widget_show( checkScaleMainV ); - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + checkScaleTrimV = gtk_check_button_new_with_label( "Scale Trim Texture Vertically" ); + gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimV, FALSE, FALSE, 0 ); + gtk_widget_show( checkScaleTrimV ); - // djbob: lists added + // --------------------- // - comboMain = gtk_combo_new(); - gtk_box_pack_start( GTK_BOX( hbox ), comboMain, FALSE, FALSE, 0 ); - gtk_combo_set_popdown_strings( GTK_COMBO( comboMain ), listMainTextures ); - gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); - gtk_widget_show( comboMain ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - tw1.one = textFrontBackTex; - tw1.two = comboMain; + // djbob: lists added - buttonSetMain = gtk_button_new_with_label( "Set As Main Texture" ); - gtk_signal_connect( GTK_OBJECT( buttonSetMain ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw1 ); - gtk_box_pack_start( GTK_BOX( hbox ), buttonSetMain, FALSE, FALSE, 0 ); - gtk_widget_show( buttonSetMain ); + comboMain = gtk_combo_new(); + gtk_box_pack_start( GTK_BOX( hbox ), comboMain, FALSE, FALSE, 0 ); + gtk_combo_set_popdown_strings( GTK_COMBO( comboMain ), listMainTextures ); + gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); + gtk_widget_show( comboMain ); + + tw1.one = textFrontBackTex; + tw1.two = comboMain; + + buttonSetMain = gtk_button_new_with_label( "Set As Main Texture" ); + gtk_signal_connect( GTK_OBJECT( buttonSetMain ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw1 ); + gtk_box_pack_start( GTK_BOX( hbox ), buttonSetMain, FALSE, FALSE, 0 ); + gtk_widget_show( buttonSetMain ); // ------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - comboTrim = gtk_combo_new(); - gtk_box_pack_start( GTK_BOX( hbox ), comboTrim, FALSE, FALSE, 0 ); - gtk_combo_set_popdown_strings( GTK_COMBO( comboTrim ), listTrimTextures ); - gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); - gtk_widget_show( comboTrim ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - tw2.one = textTrimTex; - tw2.two = comboTrim; + comboTrim = gtk_combo_new(); + gtk_box_pack_start( GTK_BOX( hbox ), comboTrim, FALSE, FALSE, 0 ); + gtk_combo_set_popdown_strings( GTK_COMBO( comboTrim ), listTrimTextures ); + gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); + gtk_widget_show( comboTrim ); - buttonSetTrim = gtk_button_new_with_label( "Set As Trim Texture" ); - gtk_signal_connect( GTK_OBJECT( buttonSetTrim ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw2 ); - gtk_box_pack_start( GTK_BOX( hbox ), buttonSetTrim, FALSE, FALSE, 0 ); - gtk_widget_show( buttonSetTrim ); + tw2.one = textTrimTex; + tw2.two = comboTrim; + + buttonSetTrim = gtk_button_new_with_label( "Set As Trim Texture" ); + gtk_signal_connect( GTK_OBJECT( buttonSetTrim ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw2 ); + gtk_box_pack_start( GTK_BOX( hbox ), buttonSetTrim, FALSE, FALSE, 0 ); + gtk_widget_show( buttonSetTrim ); // ------------------ // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - w = gtk_label_new( "Orientation" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "Orientation" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); - // argh more radio buttons! - radioNS = gtk_radio_button_new_with_label( NULL, "North - South" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioNS, FALSE, FALSE, 0 ); - gtk_widget_show( radioNS ); + // argh more radio buttons! + radioNS = gtk_radio_button_new_with_label( NULL, "North - South" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioNS, FALSE, FALSE, 0 ); + gtk_widget_show( radioNS ); - radioOrientation = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNS ) ); + radioOrientation = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNS ) ); - radioEW = gtk_radio_button_new_with_label( radioOrientation, "East - West" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioEW, FALSE, FALSE, 0 ); - gtk_widget_show( radioEW ); + radioEW = gtk_radio_button_new_with_label( radioOrientation, "East - West" ); + gtk_box_pack_start( GTK_BOX( hbox ), radioEW, FALSE, FALSE, 0 ); + gtk_widget_show( radioEW ); // ----------------- // - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); // ----------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - ret = eIDCANCEL; + w = gtk_button_new_with_label( "OK" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + ret = eIDCANCEL; // ----------------- // //+djbob - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - strcpy(rs->mainTexture, gtk_entry_get_text( GTK_ENTRY( textFrontBackTex ) )); - strcpy(rs->trimTexture, gtk_entry_get_text( GTK_ENTRY( textTrimTex ) )); - - rs->bScaleMainH = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleMainH)) ? true : false; - rs->bScaleMainV = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleMainV)) ? true : false; - rs->bScaleTrimH = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleTrimH)) ? true : false; - rs->bScaleTrimV = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleTrimV)) ? true : false; - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioNS))) + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + + while ( loop ) + gtk_main_iteration(); + + strcpy( rs->mainTexture, gtk_entry_get_text( GTK_ENTRY( textFrontBackTex ) ) ); + strcpy( rs->trimTexture, gtk_entry_get_text( GTK_ENTRY( textTrimTex ) ) ); + + rs->bScaleMainH = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( checkScaleMainH ) ) ? true : false; + rs->bScaleMainV = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( checkScaleMainV ) ) ? true : false; + rs->bScaleTrimH = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( checkScaleTrimH ) ) ? true : false; + rs->bScaleTrimV = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( checkScaleTrimV ) ) ? true : false; + + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radioNS ) ) ) { rs->nOrientation = DIRECTION_NS; - else if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioEW))) + } + else if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radioEW ) ) ) { rs->nOrientation = DIRECTION_EW; - - gtk_grab_remove (window); - gtk_widget_destroy (window); + } + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; //-djbob } -EMessageBoxReturn DoPathPlotterBox(PathPlotterRS* rs) -{ +EMessageBoxReturn DoPathPlotterBox( PathPlotterRS* rs ){ GtkWidget *window, *w, *vbox, *hbox; GtkWidget *text1, *text2, *text3; GtkWidget *check1, *check2; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Texture Reset"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + + gtk_window_set_title( GTK_WINDOW( window ), "Texture Reset" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + // ---- vbox ---- - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text1 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text1, "25"); - gtk_box_pack_start (GTK_BOX (hbox), text1, FALSE, FALSE, 2); - gtk_widget_show (text1); - - w = gtk_label_new ("Number Of Points"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text2 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text2, "3"); - gtk_box_pack_start (GTK_BOX (hbox), text2, FALSE, FALSE, 2); - gtk_widget_show (text2); - - w = gtk_label_new ("Multipler"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - w = gtk_label_new ("Path Distance = dist(start -> apex) * multiplier"); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 0); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text3 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text3, "-800"); - gtk_box_pack_start (GTK_BOX (hbox), text3, FALSE, FALSE, 2); - gtk_widget_show (text3); - - w = gtk_label_new ("Gravity"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + text1 = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( (GtkEntry*)text1, "25" ); + gtk_box_pack_start( GTK_BOX( hbox ), text1, FALSE, FALSE, 2 ); + gtk_widget_show( text1 ); + + w = gtk_label_new( "Number Of Points" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + // ---- /hbox ---- + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + text2 = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( (GtkEntry*)text2, "3" ); + gtk_box_pack_start( GTK_BOX( hbox ), text2, FALSE, FALSE, 2 ); + gtk_widget_show( text2 ); - check1 = gtk_check_button_new_with_label( "No Dynamic Update" ); - gtk_box_pack_start( GTK_BOX( vbox ), check1, FALSE, FALSE, 0 ); - gtk_widget_show( check1 ); + w = gtk_label_new( "Multipler" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + // ---- /hbox ---- + + w = gtk_label_new( "Path Distance = dist(start -> apex) * multiplier" ); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + text3 = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( (GtkEntry*)text3, "-800" ); + gtk_box_pack_start( GTK_BOX( hbox ), text3, FALSE, FALSE, 2 ); + gtk_widget_show( text3 ); + + w = gtk_label_new( "Gravity" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + // ---- /hbox ---- + + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); + + check1 = gtk_check_button_new_with_label( "No Dynamic Update" ); + gtk_box_pack_start( GTK_BOX( vbox ), check1, FALSE, FALSE, 0 ); + gtk_widget_show( check1 ); - check2 = gtk_check_button_new_with_label( "Show Bounding Lines" ); - gtk_box_pack_start( GTK_BOX( vbox ), check2, FALSE, FALSE, 0 ); - gtk_widget_show( check2 ); + check2 = gtk_check_button_new_with_label( "Show Bounding Lines" ); + gtk_box_pack_start( GTK_BOX( vbox ), check2, FALSE, FALSE, 0 ); + gtk_widget_show( check2 ); // ---- /vbox ---- // ----------------- // - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); // ----------------- // - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_widget_show( hbox ); - w = gtk_button_new_with_label( "Enable" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); - gtk_widget_show( w ); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); + w = gtk_button_new_with_label( "Enable" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + gtk_widget_show( w ); - w = gtk_button_new_with_label( "Disable" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - - ret = eIDCANCEL; + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + + w = gtk_button_new_with_label( "Disable" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + + ret = eIDCANCEL; // ----------------- // - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if(ret == eIDYES) - { - if(!ValidateTextIntRange(gtk_entry_get_text(GTK_ENTRY(text1)), 1, 200, "Number Of Points", &rs->nPoints)) + if ( ret == eIDYES ) { + if ( !ValidateTextIntRange( gtk_entry_get_text( GTK_ENTRY( text1 ) ), 1, 200, "Number Of Points", &rs->nPoints ) ) { dialogError = TRUE; + } - if(!ValidateTextFloatRange(gtk_entry_get_text(GTK_ENTRY(text2)), 1.0f, 10.0f, "Multiplier", &rs->fMultiplier)) + if ( !ValidateTextFloatRange( gtk_entry_get_text( GTK_ENTRY( text2 ) ), 1.0f, 10.0f, "Multiplier", &rs->fMultiplier ) ) { dialogError = TRUE; + } - if(!ValidateTextFloatRange(gtk_entry_get_text(GTK_ENTRY(text3)), -10000.0f, -1.0f, "Gravity", &rs->fGravity)) + if ( !ValidateTextFloatRange( gtk_entry_get_text( GTK_ENTRY( text3 ) ), -10000.0f, -1.0f, "Gravity", &rs->fGravity ) ) { dialogError = TRUE; + } - rs->bNoUpdate = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check1)) ? true : false; - rs->bShowExtra = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check2)) ? true : false; + rs->bNoUpdate = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( check1 ) ) ? true : false; + rs->bShowExtra = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( check2 ) ) ? true : false; } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } -EMessageBoxReturn DoCTFColourChangeBox () -{ +EMessageBoxReturn DoCTFColourChangeBox(){ GtkWidget *window, *w, *vbox, *hbox; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "CTF Colour Changer"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + + gtk_window_set_title( GTK_WINDOW( window ), "CTF Colour Changer" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + // ---- vbox ---- - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); - gtk_widget_show( hbox ); - - // ---- hbox ---- ok/cancel buttons - - w = gtk_button_new_with_label ("Red->Blue"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Blue->Red"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- ok/cancel buttons + + w = gtk_button_new_with_label( "Red->Blue" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Blue->Red" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + ret = eIDCANCEL; + + // ---- /hbox ---- - // ---- /hbox ---- - // ---- /vbox ---- - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); - gtk_grab_remove (window); - gtk_widget_destroy (window); + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } -EMessageBoxReturn DoResetTextureBox (ResetTextureRS* rs) -{ +EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ){ Str texSelected; GtkWidget *window, *w, *vbox, *hbox, *frame, *table; EMessageBoxReturn ret; - int loop = 1; + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); + gtk_window_set_title( GTK_WINDOW( window ), "Texture Reset" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - gtk_window_set_title (GTK_WINDOW (window), "Texture Reset"); - gtk_container_border_width (GTK_CONTAINER (window), 10); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + gtk_widget_realize( window ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - // ---- vbox ---- - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + // ---- hbox ---- texSelected = "Currently Selected Texture: "; - texSelected += GetCurrentTexture(); + texSelected += GetCurrentTexture(); - w = gtk_label_new (texSelected); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); + w = gtk_label_new( texSelected ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); // ---- /hbox ---- - frame = gtk_frame_new ("Reset Texture Names"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Reset Texture Names" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - dlgTexReset.cbTexChange = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbTexChange), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbTexChange); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbTexChange, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("Old Name: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editTexOld = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editTexOld), rs->textureName); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editTexOld, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editTexOld); - - w = gtk_label_new ("New Name: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editTexNew = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editTexNew), rs->textureName); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editTexNew, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editTexNew); + dlgTexReset.cbTexChange = gtk_check_button_new_with_label( "Enabled" ); + gtk_signal_connect( GTK_OBJECT( dlgTexReset.cbTexChange ), "toggled", GTK_SIGNAL_FUNC( dialog_button_callback_texreset_update ), NULL ); + gtk_widget_show( dlgTexReset.cbTexChange ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbTexChange, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "Old Name: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editTexOld = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editTexOld ), rs->textureName ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editTexOld, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editTexOld ); + + w = gtk_label_new( "New Name: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editTexNew = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editTexNew ), rs->textureName ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editTexNew, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editTexNew ); // ---- /frame ---- - frame = gtk_frame_new ("Reset Scales"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Reset Scales" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - dlgTexReset.cbScaleHor = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbScaleHor), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbScaleHor); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbScaleHor, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Horizontal Scale: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editScaleHor = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editScaleHor), "0.5"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editScaleHor, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editScaleHor); - - - dlgTexReset.cbScaleVert = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbScaleVert), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbScaleVert); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbScaleVert, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Vertical Scale: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editScaleVert = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editScaleVert), "0.5"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editScaleVert, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editScaleVert); + dlgTexReset.cbScaleHor = gtk_check_button_new_with_label( "Enabled" ); + gtk_signal_connect( GTK_OBJECT( dlgTexReset.cbScaleHor ), "toggled", GTK_SIGNAL_FUNC( dialog_button_callback_texreset_update ), NULL ); + gtk_widget_show( dlgTexReset.cbScaleHor ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbScaleHor, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "New Horizontal Scale: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editScaleHor = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editScaleHor ), "0.5" ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editScaleHor, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editScaleHor ); + + + dlgTexReset.cbScaleVert = gtk_check_button_new_with_label( "Enabled" ); + gtk_signal_connect( GTK_OBJECT( dlgTexReset.cbScaleVert ), "toggled", GTK_SIGNAL_FUNC( dialog_button_callback_texreset_update ), NULL ); + gtk_widget_show( dlgTexReset.cbScaleVert ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbScaleVert, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "New Vertical Scale: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editScaleVert = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editScaleVert ), "0.5" ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editScaleVert, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editScaleVert ); // ---- /frame ---- - frame = gtk_frame_new ("Reset Shift"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbShiftHor = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbShiftHor), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbShiftHor); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbShiftHor, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Horizontal Shift: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editShiftHor = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editShiftHor), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editShiftHor, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editShiftHor); - - - dlgTexReset.cbShiftVert = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbShiftVert), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbShiftVert); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbShiftVert, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Vertical Shift: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editShiftVert = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editShiftVert), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editShiftVert, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editShiftVert); + frame = gtk_frame_new( "Reset Shift" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); + + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + + // ---- frame ---- + + dlgTexReset.cbShiftHor = gtk_check_button_new_with_label( "Enabled" ); + gtk_signal_connect( GTK_OBJECT( dlgTexReset.cbShiftHor ), "toggled", GTK_SIGNAL_FUNC( dialog_button_callback_texreset_update ), NULL ); + gtk_widget_show( dlgTexReset.cbShiftHor ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbShiftHor, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "New Horizontal Shift: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editShiftHor = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editShiftHor ), "0" ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editShiftHor, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editShiftHor ); + + + dlgTexReset.cbShiftVert = gtk_check_button_new_with_label( "Enabled" ); + gtk_signal_connect( GTK_OBJECT( dlgTexReset.cbShiftVert ), "toggled", GTK_SIGNAL_FUNC( dialog_button_callback_texreset_update ), NULL ); + gtk_widget_show( dlgTexReset.cbShiftVert ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbShiftVert, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "New Vertical Shift: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editShiftVert = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editShiftVert ), "0" ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editShiftVert, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editShiftVert ); // ---- /frame ---- - frame = gtk_frame_new ("Reset Rotation"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (1, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbRotation = gtk_check_button_new_with_label("Enabled"); - gtk_widget_show (dlgTexReset.cbRotation); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbRotation, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Rotation Value: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editRotation = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editRotation), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editRotation, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editRotation); + frame = gtk_frame_new( "Reset Rotation" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); + + table = gtk_table_new( 1, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + + // ---- frame ---- + + dlgTexReset.cbRotation = gtk_check_button_new_with_label( "Enabled" ); + gtk_widget_show( dlgTexReset.cbRotation ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.cbRotation, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + + w = gtk_label_new( "New Rotation Value: " ); + gtk_table_attach( GTK_TABLE( table ), w, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + dlgTexReset.editRotation = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( dlgTexReset.editRotation ), "0" ); + gtk_table_attach( GTK_TABLE( table ), dlgTexReset.editRotation, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( dlgTexReset.editRotation ); // ---- /frame ---- - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + // ---- hbox ---- - w = gtk_button_new_with_label ("Use Selected Brushes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Use All Brushes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Use Selected Brushes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Use All Brushes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; // ---- /hbox ---- - + // ---- /vbox ---- - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + Update_TextureReseter(); bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if(ret != eIDCANCEL) - { - rs->bResetRotation = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation )); - if(rs->bResetRotation) - if(!ValidateTextInt(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editRotation)), "Rotation", &rs->rotation)) + if ( ret != eIDCANCEL ) { + rs->bResetRotation = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation ) ); + if ( rs->bResetRotation ) { + if ( !ValidateTextInt( gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editRotation ) ), "Rotation", &rs->rotation ) ) { dialogError = TRUE; + } + } - rs->bResetScale[0] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor )); - if(rs->bResetScale[0]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editScaleHor)), "Horizontal Scale", &rs->fScale[0])) + rs->bResetScale[0] = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor ) ); + if ( rs->bResetScale[0] ) { + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editScaleHor ) ), "Horizontal Scale", &rs->fScale[0] ) ) { dialogError = TRUE; + } + } - rs->bResetScale[1] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert )); - if(rs->bResetScale[1]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editScaleVert)), "Vertical Scale", &rs->fScale[1])) + rs->bResetScale[1] = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert ) ); + if ( rs->bResetScale[1] ) { + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editScaleVert ) ), "Vertical Scale", &rs->fScale[1] ) ) { dialogError = TRUE; + } + } - rs->bResetShift[0] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor )); - if(rs->bResetShift[0]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editShiftHor)), "Horizontal Shift", &rs->fShift[0])) + rs->bResetShift[0] = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor ) ); + if ( rs->bResetShift[0] ) { + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editShiftHor ) ), "Horizontal Shift", &rs->fShift[0] ) ) { dialogError = TRUE; + } + } - rs->bResetShift[1] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert )); - if(rs->bResetShift[1]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editShiftVert)), "Vertical Shift", &rs->fShift[1])) + rs->bResetShift[1] = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert ) ); + if ( rs->bResetShift[1] ) { + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editShiftVert ) ), "Vertical Shift", &rs->fShift[1] ) ) { dialogError = TRUE; + } + } - rs->bResetTextureName = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange )); - if(rs->bResetTextureName) - { - strcpy(rs->textureName, gtk_entry_get_text(GTK_ENTRY( dlgTexReset.editTexOld ))); - strcpy(rs->newTextureName, gtk_entry_get_text(GTK_ENTRY( dlgTexReset.editTexNew ))); + rs->bResetTextureName = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange ) ); + if ( rs->bResetTextureName ) { + strcpy( rs->textureName, gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editTexOld ) ) ); + strcpy( rs->newTextureName, gtk_entry_get_text( GTK_ENTRY( dlgTexReset.editTexNew ) ) ); } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } -EMessageBoxReturn DoTrainThingBox (TrainThingRS* rs) -{ +EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ){ Str texSelected; GtkWidget *window, *w, *vbox, *hbox, *frame, *table; @@ -1654,365 +1646,370 @@ EMessageBoxReturn DoTrainThingBox (TrainThingRS* rs) GtkWidget *numPoints; EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Train Thing"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - gtk_object_set_data (GTK_OBJECT (window), "loop", &loop); - gtk_object_set_data (GTK_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - + int loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + + gtk_window_set_title( GTK_WINDOW( window ), "Train Thing" ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + + gtk_object_set_data( GTK_OBJECT( window ), "loop", &loop ); + gtk_object_set_data( GTK_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + // ---- vbox ---- - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); // ---- /hbox ---- - frame = gtk_frame_new ("Radii"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Radii" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - w = gtk_label_new ("X: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "X: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - radiusX = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(radiusX), "100"); - gtk_table_attach (GTK_TABLE (table), radiusX, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (radiusX); + radiusX = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( radiusX ), "100" ); + gtk_table_attach( GTK_TABLE( table ), radiusX, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( radiusX ); - w = gtk_label_new ("Y: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "Y: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - radiusY = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(radiusY), "100"); - gtk_table_attach (GTK_TABLE (table), radiusY, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (radiusY); + radiusY = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( radiusY ), "100" ); + gtk_table_attach( GTK_TABLE( table ), radiusY, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( radiusY ); - frame = gtk_frame_new ("Angles"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Angles" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - w = gtk_label_new ("Start: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "Start: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - angleStart = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(angleStart), "0"); - gtk_table_attach (GTK_TABLE (table), angleStart, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (angleStart); + angleStart = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( angleStart ), "0" ); + gtk_table_attach( GTK_TABLE( table ), angleStart, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( angleStart ); - w = gtk_label_new ("End: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "End: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - angleEnd = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(angleEnd), "90"); - gtk_table_attach (GTK_TABLE (table), angleEnd, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (angleEnd); + angleEnd = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( angleEnd ), "90" ); + gtk_table_attach( GTK_TABLE( table ), angleEnd, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( angleEnd ); - frame = gtk_frame_new ("Height"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Height" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - w = gtk_label_new ("Start: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "Start: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - heightStart = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(heightStart), "0"); - gtk_table_attach (GTK_TABLE (table), heightStart, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (heightStart); + heightStart = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( heightStart ), "0" ); + gtk_table_attach( GTK_TABLE( table ), heightStart, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( heightStart ); - w = gtk_label_new ("End: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); + w = gtk_label_new( "End: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); - heightEnd = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(heightEnd), "0"); - gtk_table_attach (GTK_TABLE (table), heightEnd, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (heightEnd); + heightEnd = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( heightEnd ), "0" ); + gtk_table_attach( GTK_TABLE( table ), heightEnd, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( heightEnd ); - frame = gtk_frame_new ("Points"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); + frame = gtk_frame_new( "Points" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); + table = gtk_table_new( 2, 3, TRUE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); // ---- frame ---- - w = gtk_label_new ("Number: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - numPoints = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(numPoints), "0"); - gtk_table_attach (GTK_TABLE (table), numPoints, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (numPoints); - - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + w = gtk_label_new( "Number: " ); + gtk_table_attach( GTK_TABLE( table ), w, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( w ); + + numPoints = gtk_entry_new_with_max_length( 256 ); + gtk_entry_set_text( GTK_ENTRY( numPoints ), "0" ); + gtk_table_attach( GTK_TABLE( table ), numPoints, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_widget_show( numPoints ); + + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + // ---- hbox ---- + + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); + ret = eIDCANCEL; + + // ---- /hbox ---- + + + + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if(ret != eIDCANCEL) - { - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(radiusX)), "Radius (X)", &rs->fRadiusX)) + if ( ret != eIDCANCEL ) { + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( radiusX ) ), "Radius (X)", &rs->fRadiusX ) ) { dialogError = TRUE; + } - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(radiusY)), "Radius (Y)", &rs->fRadiusY)) + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( radiusY ) ), "Radius (Y)", &rs->fRadiusY ) ) { dialogError = TRUE; + } - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(angleStart)), "Angle (Start)", &rs->fStartAngle)) + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( angleStart ) ), "Angle (Start)", &rs->fStartAngle ) ) { dialogError = TRUE; + } - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(angleEnd)), "Angle (End)", &rs->fEndAngle)) + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( angleEnd ) ), "Angle (End)", &rs->fEndAngle ) ) { dialogError = TRUE; + } - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(heightStart)), "Height (Start)", &rs->fStartHeight)) + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( heightStart ) ), "Height (Start)", &rs->fStartHeight ) ) { dialogError = TRUE; + } - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(heightEnd)), "Height (End)", &rs->fEndHeight)) + if ( !ValidateTextFloat( gtk_entry_get_text( GTK_ENTRY( heightEnd ) ), "Height (End)", &rs->fEndHeight ) ) { dialogError = TRUE; + } - if(!ValidateTextInt(gtk_entry_get_text(GTK_ENTRY(numPoints)), "Num Points", &rs->iNumPoints)) + if ( !ValidateTextInt( gtk_entry_get_text( GTK_ENTRY( numPoints ) ), "Num Points", &rs->iNumPoints ) ) { dialogError = TRUE; + } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); return ret; } // ailmanki // add a simple input for the MakeChain thing.. -EMessageBoxReturn DoMakeChainBox(MakeChainRS* rs) -{ - GtkWidget *window, *w, *vbox, *hbox; - GtkWidget *textlinkNum, *textlinkName; +EMessageBoxReturn DoMakeChainBox( MakeChainRS* rs ){ + GtkWidget *window, *w, *vbox, *hbox; + GtkWidget *textlinkNum, *textlinkName; EMessageBoxReturn ret; int loop = 1; - - char *text = "Please set a value in the boxes below and press 'OK' to make a chain"; - + + char *text = "Please set a value in the boxes below and press 'OK' to make a chain"; + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - + + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_title( GTK_WINDOW( window ), "Make Chain" ); - + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // new vbox + + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); + + gtk_widget_realize( window ); + + // new vbox vbox = gtk_vbox_new( FALSE, 10 ); gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); - + hbox = gtk_hbox_new( FALSE, 10 ); gtk_container_add( GTK_CONTAINER( vbox ), hbox ); gtk_widget_show( hbox ); - + // dunno if you want this text or not ... w = gtk_label_new( text ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - + w = gtk_hseparator_new(); gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - - // ------------------------- // - + + // ------------------------- // + // new hbox hbox = gtk_hbox_new( FALSE, 10 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - - textlinkNum = gtk_entry_new_with_max_length( 256 ); + + textlinkNum = gtk_entry_new_with_max_length( 256 ); gtk_box_pack_start( GTK_BOX( hbox ), textlinkNum, FALSE, FALSE, 1 ); gtk_widget_show( textlinkNum ); - + w = gtk_label_new( "Number of elements in chain" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); gtk_widget_show( w ); - + // -------------------------- // - + hbox = gtk_hbox_new( FALSE, 10 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - + textlinkName = gtk_entry_new_with_max_length( 256 ); gtk_box_pack_start( GTK_BOX( hbox ), textlinkName, FALSE, FALSE, 0 ); gtk_widget_show( textlinkName ); - + w = gtk_label_new( "Basename for chain's targetnames." ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); gtk_widget_show( w ); - - + + w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); gtk_widget_show( w ); - + w = gtk_button_new_with_label( "Cancel" ); gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); gtk_widget_show( w ); - + ret = eIDCANCEL; - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); + bool dialogError = TRUE; - while (dialogError) + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - - if(ret == eIDOK) - { - strcpy(rs->linkName, gtk_entry_get_text((GtkEntry*)textlinkName)); - if(!ValidateTextInt(gtk_entry_get_text((GtkEntry*)textlinkNum), "Elements", &rs->linkNum)) + + if ( ret == eIDOK ) { + strcpy( rs->linkName, gtk_entry_get_text( (GtkEntry*)textlinkName ) ); + if ( !ValidateTextInt( gtk_entry_get_text( (GtkEntry*)textlinkNum ), "Elements", &rs->linkNum ) ) { dialogError = TRUE; + } } } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); + return ret; } \ No newline at end of file diff --git a/contrib/bobtoolz/dialogs/dialogs-gtk.h b/contrib/bobtoolz/dialogs/dialogs-gtk.h index 0ad1c6b5..ae354904 100644 --- a/contrib/bobtoolz/dialogs/dialogs-gtk.h +++ b/contrib/bobtoolz/dialogs/dialogs-gtk.h @@ -1,28 +1,28 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_DIALOGS_GTK_H) +#if !defined( INCLUDED_DIALOGS_GTK_H ) #define INCLUDED_DIALOGS_GTK_H #include "qerplugin.h" -struct BuildStairsRS{ +struct BuildStairsRS { char mainTexture[256]; char riserTexture[256]; int direction; @@ -53,13 +53,13 @@ struct TrainThingRS { float fStartHeight, fEndHeight; }; -struct IntersectRS{ +struct IntersectRS { int nBrushOptions; bool bUseDetail; bool bDuplicateOnly; }; -struct PolygonRS{ +struct PolygonRS { bool bUseBorder; bool bInverse; bool bAlignTop; @@ -67,7 +67,7 @@ struct PolygonRS{ int nBorderWidth; }; -struct DoorRS{ +struct DoorRS { char mainTexture[256]; char trimTexture[256]; bool bScaleMainH; @@ -77,7 +77,7 @@ struct DoorRS{ int nOrientation; }; -struct PathPlotterRS{ +struct PathPlotterRS { int nPoints; float fMultiplier; float fGravity; @@ -85,28 +85,28 @@ struct PathPlotterRS{ bool bShowExtra; }; -struct MakeChainRS{ +struct MakeChainRS { char linkName[256]; int linkNum; }; typedef struct _GtkWidget GtkWidget; -struct TwinWidget{ +struct TwinWidget { GtkWidget* one; GtkWidget* two; }; -EMessageBoxReturn DoMessageBox(const char* lpText, const char* lpCaption, EMessageBoxType type); -EMessageBoxReturn DoIntersectBox(IntersectRS* rs); -EMessageBoxReturn DoPolygonBox(PolygonRS* rs); -EMessageBoxReturn DoResetTextureBox (ResetTextureRS* rs); -EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs); -EMessageBoxReturn DoDoorsBox(DoorRS* rs); -EMessageBoxReturn DoPathPlotterBox(PathPlotterRS* rs); +EMessageBoxReturn DoMessageBox( const char* lpText, const char* lpCaption, EMessageBoxType type ); +EMessageBoxReturn DoIntersectBox( IntersectRS* rs ); +EMessageBoxReturn DoPolygonBox( PolygonRS* rs ); +EMessageBoxReturn DoResetTextureBox( ResetTextureRS* rs ); +EMessageBoxReturn DoBuildStairsBox( BuildStairsRS* rs ); +EMessageBoxReturn DoDoorsBox( DoorRS* rs ); +EMessageBoxReturn DoPathPlotterBox( PathPlotterRS* rs ); EMessageBoxReturn DoCTFColourChangeBox(); -EMessageBoxReturn DoTrainThingBox (TrainThingRS* rs); -EMessageBoxReturn DoMakeChainBox(MakeChainRS* rs); +EMessageBoxReturn DoTrainThingBox( TrainThingRS* rs ); +EMessageBoxReturn DoMakeChainBox( MakeChainRS* rs ); //GtkWidget* GetProgressWindow(char* title, GtkProgressBar* feedback); #endif diff --git a/contrib/bobtoolz/dialogs/pathplotterdialog.cpp b/contrib/bobtoolz/dialogs/pathplotterdialog.cpp index ae638529..ea64f26e 100644 --- a/contrib/bobtoolz/dialogs/pathplotterdialog.cpp +++ b/contrib/bobtoolz/dialogs/pathplotterdialog.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // PathPlotterDialog.cpp : implementation file // @@ -34,9 +34,8 @@ static char THIS_FILE[] = __FILE__; // CPathPlotterDialog dialog -CPathPlotterDialog::CPathPlotterDialog(CWnd* pParent /*=NULL*/) - : CDialog(CPathPlotterDialog::IDD, pParent) -{ +CPathPlotterDialog::CPathPlotterDialog( CWnd* pParent /*=NULL*/ ) + : CDialog( CPathPlotterDialog::IDD, pParent ){ //{{AFX_DATA_INIT(CPathPlotterDialog) m_fGravity = -800.0f; m_fMultiplier = 3.0f; @@ -47,39 +46,37 @@ CPathPlotterDialog::CPathPlotterDialog(CWnd* pParent /*=NULL*/) } -void CPathPlotterDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); +void CPathPlotterDialog::DoDataExchange( CDataExchange* pDX ){ + CDialog::DoDataExchange( pDX ); //{{AFX_DATA_MAP(CPathPlotterDialog) - DDX_Text(pDX, IDC_GRAVITY_EDIT, m_fGravity); - DDV_MinMaxFloat(pDX, m_fGravity, -10000.f, -1.f); - DDX_Text(pDX, IDC_MULTIPLIER_EDIT, m_fMultiplier); - DDV_MinMaxFloat(pDX, m_fMultiplier, 1.f, 10.f); - DDX_Check(pDX, IDC_NOUPDATE_CHECK, m_bNoUpdate); - DDX_Text(pDX, IDC_POINTCOUNT_EDIT, m_nPoints); - DDV_MinMaxInt(pDX, m_nPoints, 1, 1000); - DDX_Check(pDX, IDC_SHOWEXTRA_CHECK, m_bShowExtra); + DDX_Text( pDX, IDC_GRAVITY_EDIT, m_fGravity ); + DDV_MinMaxFloat( pDX, m_fGravity, -10000.f, -1.f ); + DDX_Text( pDX, IDC_MULTIPLIER_EDIT, m_fMultiplier ); + DDV_MinMaxFloat( pDX, m_fMultiplier, 1.f, 10.f ); + DDX_Check( pDX, IDC_NOUPDATE_CHECK, m_bNoUpdate ); + DDX_Text( pDX, IDC_POINTCOUNT_EDIT, m_nPoints ); + DDV_MinMaxInt( pDX, m_nPoints, 1, 1000 ); + DDX_Check( pDX, IDC_SHOWEXTRA_CHECK, m_bShowExtra ); //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CPathPlotterDialog, CDialog) - //{{AFX_MSG_MAP(CPathPlotterDialog) - ON_BN_CLICKED(IDYES, OnYes) - ON_BN_CLICKED(IDNO, OnNo) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP( CPathPlotterDialog, CDialog ) +//{{AFX_MSG_MAP(CPathPlotterDialog) +ON_BN_CLICKED( IDYES, OnYes ) +ON_BN_CLICKED( IDNO, OnNo ) +//}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPathPlotterDialog message handlers -void CPathPlotterDialog::OnYes() -{ - if(UpdateData()) - EndModalLoop(IDYES); +void CPathPlotterDialog::OnYes(){ + if ( UpdateData() ) { + EndModalLoop( IDYES ); + } } -void CPathPlotterDialog::OnNo() -{ - EndModalLoop(IDNO); +void CPathPlotterDialog::OnNo(){ + EndModalLoop( IDNO ); } diff --git a/contrib/bobtoolz/dialogs/pathplotterdialog.h b/contrib/bobtoolz/dialogs/pathplotterdialog.h index 6edd8987..03e50873 100644 --- a/contrib/bobtoolz/dialogs/pathplotterdialog.h +++ b/contrib/bobtoolz/dialogs/pathplotterdialog.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_) +#if !defined( AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_ ) #define AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_ #if _MSC_VER > 1000 @@ -33,35 +33,35 @@ class CPathPlotterDialog : public CDialog { // Construction public: - CPathPlotterDialog(CWnd* pParent = NULL); // standard constructor +CPathPlotterDialog( CWnd* pParent = NULL ); // standard constructor // Dialog Data - //{{AFX_DATA(CPathPlotterDialog) - enum { IDD = IDD_PATHPLOTTER_DIALOG }; - float m_fGravity; - float m_fMultiplier; - BOOL m_bNoUpdate; - int m_nPoints; - BOOL m_bShowExtra; - //}}AFX_DATA +//{{AFX_DATA(CPathPlotterDialog) +enum { IDD = IDD_PATHPLOTTER_DIALOG }; +float m_fGravity; +float m_fMultiplier; +BOOL m_bNoUpdate; +int m_nPoints; +BOOL m_bShowExtra; +//}}AFX_DATA // Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPathPlotterDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL +// ClassWizard generated virtual function overrides +//{{AFX_VIRTUAL(CPathPlotterDialog) +protected: +virtual void DoDataExchange( CDataExchange* pDX ); // DDX/DDV support +//}}AFX_VIRTUAL // Implementation protected: - // Generated message map functions - //{{AFX_MSG(CPathPlotterDialog) - afx_msg void OnYes(); - afx_msg void OnNo(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() +// Generated message map functions +//{{AFX_MSG(CPathPlotterDialog) +afx_msg void OnYes(); +afx_msg void OnNo(); +//}}AFX_MSG +DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} diff --git a/contrib/bobtoolz/funchandlers-GTK.cpp b/contrib/bobtoolz/funchandlers-GTK.cpp index 8f26d714..aa8e6478 100644 --- a/contrib/bobtoolz/funchandlers-GTK.cpp +++ b/contrib/bobtoolz/funchandlers-GTK.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "funchandlers.h" @@ -57,32 +57,33 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "scenelib.h" // for autocaulk -std::list exclusionList; // whole brush exclusion -std::list exclusionList_Face; // single face exclusion - -bool el1Loaded = false; -bool el2Loaded = false; -bool clrLst1Loaded = false; -bool clrLst2Loaded = false; - -DBobView* g_PathView = NULL; -DVisDrawer* g_VisView = NULL; -DTrainDrawer* g_TrainView = NULL; -DTreePlanter* g_TreePlanter = NULL; +std::list exclusionList; // whole brush exclusion +std::list exclusionList_Face; // single face exclusion + +bool el1Loaded = false; +bool el2Loaded = false; +bool clrLst1Loaded = false; +bool clrLst2Loaded = false; + +DBobView* g_PathView = NULL; +DVisDrawer* g_VisView = NULL; +DTrainDrawer* g_TrainView = NULL; +DTreePlanter* g_TreePlanter = NULL; // ------------- //========================// // Helper Functions // //========================// -void LoadLists() -{ +void LoadLists(){ char buffer[256]; - if(!el1Loaded) - el1Loaded = LoadExclusionList(GetFilename(buffer, "bt/bt-el1.txt"), &exclusionList); - if(!el2Loaded) - el2Loaded = LoadExclusionList(GetFilename(buffer, "bt/bt-el2.txt"), &exclusionList_Face); + if ( !el1Loaded ) { + el1Loaded = LoadExclusionList( GetFilename( buffer, "bt/bt-el1.txt" ), &exclusionList ); + } + if ( !el2Loaded ) { + el2Loaded = LoadExclusionList( GetFilename( buffer, "bt/bt-el2.txt" ), &exclusionList_Face ); + } } @@ -90,100 +91,99 @@ void LoadLists() // Main Functions // //========================// -void DoIntersect() -{ - UndoableCommand undo("bobToolz.intersect"); +void DoIntersect(){ + UndoableCommand undo( "bobToolz.intersect" ); IntersectRS rs; - if(DoIntersectBox(&rs) == eIDCANCEL) + if ( DoIntersectBox( &rs ) == eIDCANCEL ) { return; + } - if(rs.nBrushOptions == BRUSH_OPT_SELECTED) - { - if( GlobalSelectionSystem().countSelected() < 2 ) - { + if ( rs.nBrushOptions == BRUSH_OPT_SELECTED ) { + if ( GlobalSelectionSystem().countSelected() < 2 ) { //DoMessageBox("Invalid number of brushes selected, choose at least 2", "Error", eMB_OK); globalErrorStream() << "bobToolz Intersect: Invalid number of brushes selected, choose at least 2.\n"; - return; + return; } } DEntity world; - switch(rs.nBrushOptions) + switch ( rs.nBrushOptions ) { case BRUSH_OPT_SELECTED: - { - - world.LoadFromEntity(GlobalRadiant().getMapWorldEntity(), false); - world.LoadSelectedBrushes(); - break; - } + { + + world.LoadFromEntity( GlobalRadiant().getMapWorldEntity(), false ); + world.LoadSelectedBrushes(); + break; + } case BRUSH_OPT_WHOLE_MAP: - { - world.LoadFromEntity(GlobalRadiant().getMapWorldEntity(), false); - break; - } + { + world.LoadFromEntity( GlobalRadiant().getMapWorldEntity(), false ); + break; + } } - world.RemoveNonCheckBrushes(&exclusionList, rs.bUseDetail); + world.RemoveNonCheckBrushes( &exclusionList, rs.bUseDetail ); bool* pbSelectList; - if(rs.bDuplicateOnly) + if ( rs.bDuplicateOnly ) { pbSelectList = world.BuildDuplicateList(); - else + } + else{ pbSelectList = world.BuildIntersectList(); + } - world.SelectBrushes(pbSelectList); + world.SelectBrushes( pbSelectList ); int brushCount = GlobalSelectionSystem().countSelected(); globalOutputStream() << "bobToolz Intersect: " << brushCount << " intersecting brushes found.\n"; delete[] pbSelectList; } -void DoPolygonsTB() -{ - DoPolygons(); +void DoPolygonsTB(){ + DoPolygons(); } -void DoPolygons() -{ - UndoableCommand undo("bobToolz.polygons"); +void DoPolygons(){ + UndoableCommand undo( "bobToolz.polygons" ); // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz Polygons: Invalid number of brushes selected, choose 1 only.\n"; - return; + return; } PolygonRS rs; scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - if( !Node_isBrush(instance.path().top()) ) { + if ( !Node_isBrush( instance.path().top() ) ) { //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); globalErrorStream() << "bobToolz Polygons: No brush selected, select ONLY one brush.\n"; - return; + return; } // ask user for type, size, etc.... - if(DoPolygonBox(&rs) == eIDOK) - { + if ( DoPolygonBox( &rs ) == eIDOK ) { DShape poly; - vec3_t vMin, vMax; + vec3_t vMin, vMax; - { + { - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); + VectorSubtract( instance.worldAABB().origin, instance.worldAABB().extents, vMin ); + VectorAdd( instance.worldAABB().origin, instance.worldAABB().extents, vMax ); - Path_deleteTop(instance.path()); - } + Path_deleteTop( instance.path() ); + } - if(rs.bInverse) - poly.BuildInversePrism(vMin, vMax, rs.nSides, rs.bAlignTop); + if ( rs.bInverse ) { + poly.BuildInversePrism( vMin, vMax, rs.nSides, rs.bAlignTop ); + } else { - if(rs.bUseBorder) - poly.BuildBorderedPrism(vMin, vMax, rs.nSides, rs.nBorderWidth, rs.bAlignTop); - else - poly.BuildRegularPrism(vMin, vMax, rs.nSides, rs.bAlignTop); + if ( rs.bUseBorder ) { + poly.BuildBorderedPrism( vMin, vMax, rs.nSides, rs.nBorderWidth, rs.bAlignTop ); + } + else{ + poly.BuildRegularPrism( vMin, vMax, rs.nSides, rs.bAlignTop ); + } } @@ -191,105 +191,98 @@ void DoPolygons() } } -void DoFixBrushes() -{ - UndoableCommand undo("bobToolz.fixBrushes"); +void DoFixBrushes(){ + UndoableCommand undo( "bobToolz.fixBrushes" ); DMap world; world.LoadAll(); int count = world.FixBrushes(); - + globalOutputStream() << "bobToolz FixBrushes: " << count << " invalid/duplicate planes removed.\n"; } -void DoResetTextures() -{ - UndoableCommand undo("bobToolz.resetTextures"); +void DoResetTextures(){ + UndoableCommand undo( "bobToolz.resetTextures" ); static ResetTextureRS rs; - const char* texName; - if(1/*g_SelectedFaceTable.m_pfnGetSelectedFaceCount() != 1*/) - { - texName = NULL; - } - else - { - texName = GetCurrentTexture(); - strcpy(rs.textureName, GetCurrentTexture()); - } - - EMessageBoxReturn ret; - if((ret = DoResetTextureBox(&rs)) == eIDCANCEL) - return; - - if(rs.bResetTextureName) - texName = rs.textureName; - - if(ret == eIDOK) - { - DEntity world; - world.LoadSelectedBrushes(); - world.ResetTextures(texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation, true); - } - else - { - DMap world; - world.LoadAll(true); - world.ResetTextures(texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation); - } + const char* texName; + if ( 1 /*g_SelectedFaceTable.m_pfnGetSelectedFaceCount() != 1*/ ) { + texName = NULL; + } + else + { + texName = GetCurrentTexture(); + strcpy( rs.textureName, GetCurrentTexture() ); + } + + EMessageBoxReturn ret; + if ( ( ret = DoResetTextureBox( &rs ) ) == eIDCANCEL ) { + return; + } + + if ( rs.bResetTextureName ) { + texName = rs.textureName; + } + + if ( ret == eIDOK ) { + DEntity world; + world.LoadSelectedBrushes(); + world.ResetTextures( texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, + rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation, true ); + } + else + { + DMap world; + world.LoadAll( true ); + world.ResetTextures( texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, + rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation ); + } } -void DoBuildStairs() -{ - UndoableCommand undo("bobToolz.buildStairs"); +void DoBuildStairs(){ + UndoableCommand undo( "bobToolz.buildStairs" ); BuildStairsRS rs; - strcpy(rs.mainTexture, GetCurrentTexture()); + strcpy( rs.mainTexture, GetCurrentTexture() ); // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz BuildStairs: Invalid number of brushes selected, choose 1 only.\n"; - return; + return; } // ask user for type, size, etc.... - if(DoBuildStairsBox(&rs) == eIDOK) - { - vec3_t vMin, vMax; + if ( DoBuildStairsBox( &rs ) == eIDOK ) { + vec3_t vMin, vMax; - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - } + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + VectorSubtract( instance.worldAABB().origin, instance.worldAABB().extents, vMin ); + VectorAdd( instance.worldAABB().origin, instance.worldAABB().extents, vMax ); + } // calc brush size vec3_t size; - VectorSubtract(vMax, vMin, size); + VectorSubtract( vMax, vMin, size ); - if(((int)size[2] % rs.stairHeight) != 0) - { + if ( ( (int)size[2] % rs.stairHeight ) != 0 ) { // stairs must fit evenly into brush //DoMessageBox("Invalid stair height\nHeight of block must be divisable by stair height", "Error", eMB_OK); globalErrorStream() << "bobToolz BuildStairs: Invalid stair height. Height of block must be divisable by stair height.\n"; } else { - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - Path_deleteTop(instance.path()); - } - + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + Path_deleteTop( instance.path() ); + } + // Get Step Count int numSteps = (int)size[2] / rs.stairHeight; - - if(rs.style == STYLE_CORNER) - { - BuildCornerStairs(vMin, vMax, numSteps, rs.mainTexture, rs.riserTexture); + + if ( rs.style == STYLE_CORNER ) { + BuildCornerStairs( vMin, vMax, numSteps, rs.mainTexture, rs.riserTexture ); } else { @@ -297,136 +290,135 @@ void DoBuildStairs() // Get Step Dimensions float stairHeight = (float)rs.stairHeight; float stairWidth; - if((rs.direction == MOVE_EAST) || (rs.direction == MOVE_WEST)) - stairWidth = (size[0])/numSteps; - else - stairWidth = (size[1])/numSteps; + if ( ( rs.direction == MOVE_EAST ) || ( rs.direction == MOVE_WEST ) ) { + stairWidth = ( size[0] ) / numSteps; + } + else{ + stairWidth = ( size[1] ) / numSteps; + } // Build Base For Stair (bob's style) - if(rs.style == STYLE_BOB) - Build_Wedge(rs.direction, vMin, vMax, true); + if ( rs.style == STYLE_BOB ) { + Build_Wedge( rs.direction, vMin, vMax, true ); + } // Set First Step Starting Position vMax[2] = vMin[2] + stairHeight; - SetInitialStairPos(rs.direction, vMin, vMax, stairWidth); + SetInitialStairPos( rs.direction, vMin, vMax, stairWidth ); // Build The Steps - for(int i = 0; i < numSteps; i++) + for ( int i = 0; i < numSteps; i++ ) { - if(rs.style == STYLE_BOB) - Build_StairStep_Wedge(rs.direction, vMin, vMax, rs.mainTexture, rs.riserTexture, rs.bUseDetail); - else if(rs.style == STYLE_ORIGINAL) - Build_StairStep(vMin, vMax, rs.mainTexture, rs.riserTexture, rs.direction); + if ( rs.style == STYLE_BOB ) { + Build_StairStep_Wedge( rs.direction, vMin, vMax, rs.mainTexture, rs.riserTexture, rs.bUseDetail ); + } + else if ( rs.style == STYLE_ORIGINAL ) { + Build_StairStep( vMin, vMax, rs.mainTexture, rs.riserTexture, rs.direction ); + } // get step into next position - MoveBlock(rs.direction, vMin, vMax, stairWidth); + MoveBlock( rs.direction, vMin, vMax, stairWidth ); vMax[2] += stairHeight; - if(rs.style == STYLE_BOB) - vMin[2] += stairHeight; // wedge bottom must be raised + if ( rs.style == STYLE_BOB ) { + vMin[2] += stairHeight; // wedge bottom must be raised + } } } } } } -void DoBuildDoors() -{ - UndoableCommand undo("bobToolz.buildDoors"); +void DoBuildDoors(){ + UndoableCommand undo( "bobToolz.buildDoors" ); // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz BuildDoors: Invalid number of brushes selected, choose 1 only.\n"; - return; + return; } - DoorRS rs; - strcpy(rs.mainTexture, GetCurrentTexture()); + DoorRS rs; + strcpy( rs.mainTexture, GetCurrentTexture() ); - if(DoDoorsBox(&rs) == eIDOK) - { - vec3_t vMin, vMax; + if ( DoDoorsBox( &rs ) == eIDOK ) { + vec3_t vMin, vMax; - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - Path_deleteTop(instance.path()); - } + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + VectorSubtract( instance.worldAABB().origin, instance.worldAABB().extents, vMin ); + VectorAdd( instance.worldAABB().origin, instance.worldAABB().extents, vMax ); + Path_deleteTop( instance.path() ); + } - BuildDoorsX2(vMin, vMax, - rs.bScaleMainH, rs.bScaleMainV, - rs.bScaleTrimH, rs.bScaleTrimV, - rs.mainTexture, rs.trimTexture, - rs.nOrientation); // shapes.cpp + BuildDoorsX2( vMin, vMax, + rs.bScaleMainH, rs.bScaleMainV, + rs.bScaleTrimH, rs.bScaleTrimV, + rs.mainTexture, rs.trimTexture, + rs.nOrientation ); // shapes.cpp } } -void DoPathPlotter() -{ - UndoableCommand undo("bobToolz.pathPlotter"); +void DoPathPlotter(){ + UndoableCommand undo( "bobToolz.pathPlotter" ); PathPlotterRS rs; - EMessageBoxReturn ret = DoPathPlotterBox(&rs); - if(ret == eIDCANCEL) + EMessageBoxReturn ret = DoPathPlotterBox( &rs ); + if ( ret == eIDCANCEL ) { return; - if(ret == eIDNO) - { - if(g_PathView) + } + if ( ret == eIDNO ) { + if ( g_PathView ) { delete g_PathView; + } return; } // ensure we have something selected /* - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalOutputStream() << "bobToolz PathPlotter: Invalid number of entities selected, choose 1 trigger_push entity only.\n"; - return; - } + if( GlobalSelectionSystem().countSelected() != 1 ) + { + //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); + globalOutputStream() << "bobToolz PathPlotter: Invalid number of entities selected, choose 1 trigger_push entity only.\n"; + return; + } */ - Entity* entity = Node_getEntity(GlobalSelectionSystem().ultimateSelected().path().top()); - if(entity != 0) - { - DBobView_setEntity(*entity, rs.fMultiplier, rs.nPoints, rs.fGravity, rs.bNoUpdate, rs.bShowExtra); - } - else globalErrorStream() << "bobToolz PathPlotter: No trigger_push entitity selected, select 1 only (Use list to select it).\n"; + Entity* entity = Node_getEntity( GlobalSelectionSystem().ultimateSelected().path().top() ); + if ( entity != 0 ) { + DBobView_setEntity( *entity, rs.fMultiplier, rs.nPoints, rs.fGravity, rs.bNoUpdate, rs.bShowExtra ); + } + else{ globalErrorStream() << "bobToolz PathPlotter: No trigger_push entitity selected, select 1 only (Use list to select it).\n"; } return; } -void DoPitBuilder() -{ - UndoableCommand undo("bobToolz.pitBuilder"); +void DoPitBuilder(){ + UndoableCommand undo( "bobToolz.pitBuilder" ); // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz PitBuilder: Invalid number of brushes selected, choose 1 only.\n"; - return; + return; } vec3_t vMin, vMax; scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); //seems it does this also with a patch with valid dimensions.. but probably better to enforce a brush. - if( !Node_isBrush(instance.path().top()) ) { + if ( !Node_isBrush( instance.path().top() ) ) { //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); globalErrorStream() << "bobToolz PitBuilder: No brush selected, select ONLY 1 brush.\n"; - return; + return; } - - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); + + VectorSubtract( instance.worldAABB().origin, instance.worldAABB().extents, vMin ); + VectorAdd( instance.worldAABB().origin, instance.worldAABB().extents, vMax ); DShape pit; - if(pit.BuildPit(vMin, vMax)) - { + if ( pit.BuildPit( vMin, vMax ) ) { pit.Commit(); - Path_deleteTop(instance.path()); + Path_deleteTop( instance.path() ); } else { @@ -435,65 +427,61 @@ void DoPitBuilder() } } -void DoMergePatches() -{ - UndoableCommand undo("bobToolz.mergePatches"); +void DoMergePatches(){ + UndoableCommand undo( "bobToolz.mergePatches" ); patch_merge_t merge_info; DPatch mrgPatches[2]; int i; // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 2 ) - { + if ( GlobalSelectionSystem().countSelected() != 2 ) { globalErrorStream() << "bobToolz MergePatches: Invalid number of patches selected, choose 2 only.\n"; //DoMessageBox("Invalid number of patches selected, choose 2 only", "Error", eMB_OK); - return; + return; } scene::Instance* patches[2]; patches[0] = &GlobalSelectionSystem().ultimateSelected(); patches[1] = &GlobalSelectionSystem().penultimateSelected(); - for (i = 0; i < 2; i++) + for ( i = 0; i < 2; i++ ) { - if (!Node_isPatch(patches[i]->path().top())) - { + if ( !Node_isPatch( patches[i]->path().top() ) ) { //DoMessageBox("No patches selected, select ONLY patches", "Error", eMB_OK); globalErrorStream() << "bobToolz MergePatches: Invalid number of patches selected, choose ONLY 2 patches.\n"; - return; + return; } - mrgPatches[i].LoadFromPatch(*patches[i]); + mrgPatches[i].LoadFromPatch( *patches[i] ); } - /* mrgPatches[0].Transpose(); - mrgPatches[0].RemoveFromRadiant(); - mrgPatches[0].BuildInRadiant();*/ + /* mrgPatches[0].Transpose(); + mrgPatches[0].RemoveFromRadiant(); + mrgPatches[0].BuildInRadiant();*/ - merge_info = mrgPatches[0].IsMergable(&mrgPatches[1]); + merge_info = mrgPatches[0].IsMergable( &mrgPatches[1] ); - if (merge_info.mergable) - { + if ( merge_info.mergable ) { globalOutputStream() << merge_info.pos1 << " " << merge_info.pos2; //Message removed, No tools give feedback on success. //globalOutputStream() << "bobToolz MergePatches: Patches Mergable.\n"; - DPatch* newPatch = mrgPatches[0].MergePatches(merge_info, &mrgPatches[0], &mrgPatches[1]); - - /* mrgPatches[0].RemoveFromRadiant(); - mrgPatches[0].BuildInRadiant(); - - mrgPatches[1].RemoveFromRadiant(); - mrgPatches[1].BuildInRadiant(); - - - delete newPatch;*/ - - if (!newPatch) - { - } else + DPatch* newPatch = mrgPatches[0].MergePatches( merge_info, &mrgPatches[0], &mrgPatches[1] ); + + /* mrgPatches[0].RemoveFromRadiant(); + mrgPatches[0].BuildInRadiant(); + + mrgPatches[1].RemoveFromRadiant(); + mrgPatches[1].BuildInRadiant(); + + + delete newPatch;*/ + + if ( !newPatch ) { + } + else { - Path_deleteTop(patches[0]->path()); - Path_deleteTop(patches[1]->path()); + Path_deleteTop( patches[0]->path() ); + Path_deleteTop( patches[1]->path() ); newPatch->BuildInRadiant(); delete newPatch; @@ -502,167 +490,158 @@ void DoMergePatches() else { globalErrorStream() << "bobToolz.mergePatch: The selected patches are not mergable.\n"; - + } } void DoSplitPatch() { - UndoableCommand undo("bobToolz.splitPatch"); + UndoableCommand undo( "bobToolz.splitPatch" ); DPatch patch; // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatch: Invalid number of patches selected, choose only 1 patch.\n"; - return; + return; } - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - if( !Node_isPatch(instance.path().top()) ) { + if ( !Node_isPatch( instance.path().top() ) ) { //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatch: No patch selected, select ONLY 1 patch.\n"; - return; + return; } - patch.LoadFromPatch(instance); + patch.LoadFromPatch( instance ); std::list patchList = patch.Split(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); + for ( std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++ ) { + ( *patches ).BuildInRadiant(); } - Path_deleteTop(instance.path()); + Path_deleteTop( instance.path() ); } void DoSplitPatchCols() { - UndoableCommand undo("bobToolz.splitPatchCols"); - + UndoableCommand undo( "bobToolz.splitPatchCols" ); + DPatch patch; - + // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatchCols: Invalid number of patches selected, choose 1 only.\n"; - return; + return; } - + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - - if( !Node_isPatch(instance.path().top()) ) { + + if ( !Node_isPatch( instance.path().top() ) ) { //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatchCols: No patch selected, select ONLY 1 patch.\n"; - return; + return; } - - patch.LoadFromPatch(instance); - + + patch.LoadFromPatch( instance ); + std::list patchList = patch.SplitCols(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); + for ( std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++ ) { + ( *patches ).BuildInRadiant(); } - - Path_deleteTop(instance.path()); + + Path_deleteTop( instance.path() ); } void DoSplitPatchRows() { - UndoableCommand undo("bobToolz.splitPatchRows"); - + UndoableCommand undo( "bobToolz.splitPatchRows" ); + DPatch patch; - + // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatchRows: Invalid number of patches selected, choose 1 only.\n"; - return; + return; } - + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - - if( !Node_isPatch(instance.path().top()) ) { + + if ( !Node_isPatch( instance.path().top() ) ) { //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); globalErrorStream() << "bobToolz SplitPatchRows: No patch selected, select ONLY 1 patch.\n"; - return; + return; } - - patch.LoadFromPatch(instance); - + + patch.LoadFromPatch( instance ); + std::list patchList = patch.SplitRows(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); + for ( std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++ ) { + ( *patches ).BuildInRadiant(); } - - Path_deleteTop(instance.path()); + + Path_deleteTop( instance.path() ); } -void DoVisAnalyse() -{ +void DoVisAnalyse(){ char filename[1024]; - if( GlobalSelectionSystem().countSelected() == 0 ) - { + if ( GlobalSelectionSystem().countSelected() == 0 ) { globalErrorStream() << "bobToolz VisAnalyse: Invalid number of objects selected, choose 1 only.\n"; - if(g_VisView) - { + if ( g_VisView ) { delete g_VisView; return; } } // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { + if ( GlobalSelectionSystem().countSelected() != 1 ) { //DoMessageBox("Invalid number of objects selected, choose 1 only", "Error", eMB_OK); globalErrorStream() << "bobToolz VisAnalyse: Invalid number of objects selected, choose 1 only.\n"; - return; + return; } - + scene::Instance& brush = GlobalSelectionSystem().ultimateSelected(); //ensure we have a brush selected - if( !Node_isBrush(brush.path().top()) ) { + if ( !Node_isBrush( brush.path().top() ) ) { //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); globalErrorStream() << "bobToolz VisAnalyse: No brush selected, select ONLY 1 brush.\n"; - return; + return; } DBrush orgBrush; - orgBrush.LoadFromBrush(brush, false); + orgBrush.LoadFromBrush( brush, false ); orgBrush.BuildBounds(); vec3_t origin; - origin[0] = (orgBrush.bbox_max[0] + orgBrush.bbox_min[0])/2.f; - origin[1] = (orgBrush.bbox_max[1] + orgBrush.bbox_min[1])/2.f; - origin[2] = (orgBrush.bbox_max[2] + orgBrush.bbox_min[2])/2.f; + origin[0] = ( orgBrush.bbox_max[0] + orgBrush.bbox_min[0] ) / 2.f; + origin[1] = ( orgBrush.bbox_max[1] + orgBrush.bbox_min[1] ) / 2.f; + origin[2] = ( orgBrush.bbox_max[2] + orgBrush.bbox_min[2] ) / 2.f; - const char* rad_filename = GlobalRadiant().getMapName(); - if(!rad_filename) - { + const char* rad_filename = GlobalRadiant().getMapName(); + if ( !rad_filename ) { //DoMessageBox("An ERROR occurred while trying\n to get the map filename", "Error", eMB_OK); globalErrorStream() << "bobToolz VisAnalyse: An ERROR occurred while trying to get the map filename.\n"; return; } - strcpy(filename, rad_filename); - - char* ext = strrchr(filename, '.')+1; - strcpy(ext, "bsp");// rename the extension + strcpy( filename, rad_filename ); - std::list *pointList = BuildTrace(filename, origin); + char* ext = strrchr( filename, '.' ) + 1; + strcpy( ext, "bsp" ); // rename the extension - if(!g_VisView) - { + std::list *pointList = BuildTrace( filename, origin ); + + if ( !g_VisView ) { g_VisView = new DVisDrawer; } - - g_VisView->SetList(pointList); + + g_VisView->SetList( pointList ); } void DoTrainPathPlot() { - if(g_TrainView) { + if ( g_TrainView ) { delete g_TrainView; g_TrainView = NULL; } @@ -671,9 +650,9 @@ void DoTrainPathPlot() { } void DoCaulkSelection() { - UndoableCommand undo("bobToolz.caulkSelection"); + UndoableCommand undo( "bobToolz.caulkSelection" ); DEntity world; - + float fScale[2] = { 0.5f, 0.5f }; float fShift[2] = { 0.0f, 0.0f }; @@ -686,8 +665,8 @@ void DoCaulkSelection() { } void DoTreePlanter() { - UndoableCommand undo("bobToolz.treePlanter"); - if(g_TreePlanter) { + UndoableCommand undo( "bobToolz.treePlanter" ); + if ( g_TreePlanter ) { delete g_TreePlanter; g_TreePlanter = NULL; return; @@ -697,23 +676,22 @@ void DoTreePlanter() { } void DoDropEnts() { - UndoableCommand undo("bobToolz.dropEntities"); - if(g_TreePlanter) { + UndoableCommand undo( "bobToolz.dropEntities" ); + if ( g_TreePlanter ) { g_TreePlanter->DropEntsToGround(); } } void DoMakeChain() { MakeChainRS rs; - if(DoMakeChainBox(&rs) == eIDOK) - { + if ( DoMakeChainBox( &rs ) == eIDOK ) { if ( rs.linkNum > 1001 ) { globalErrorStream() << "bobToolz MakeChain: " << rs.linkNum << " to many Elemets, limited to 1000.\n"; return; } - UndoableCommand undo("bobToolz.makeChain"); + UndoableCommand undo( "bobToolz.makeChain" ); DTreePlanter pl; - pl.MakeChain(rs.linkNum,rs.linkName); + pl.MakeChain( rs.linkNum,rs.linkName ); } } @@ -722,36 +700,35 @@ typedef DPoint* pntTripple[3]; bool bFacesNoTop[6] = {true, true, true, true, true, false}; void DoFlipTerrain() { - UndoableCommand undo("bobToolz.flipTerrain"); + UndoableCommand undo( "bobToolz.flipTerrain" ); vec3_t vUp = { 0.f, 0.f, 1.f }; - int i; + int i; // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 2 ) - { + if ( GlobalSelectionSystem().countSelected() != 2 ) { //DoMessageBox("Invalid number of objects selected, choose 2 only", "Error", eMB_OK); globalErrorStream() << "bobToolz FlipTerrain: Invalid number of objects selected, choose 2 only.\n"; - return; + return; } - scene::Instance* brushes[2]; + scene::Instance* brushes[2]; brushes[0] = &GlobalSelectionSystem().ultimateSelected(); brushes[1] = &GlobalSelectionSystem().penultimateSelected(); //ensure we have only Brushes selected. - for (i = 0; i < 2; i++) + for ( i = 0; i < 2; i++ ) { - if( !Node_isBrush(brushes[i]->path().top()) ) { + if ( !Node_isBrush( brushes[i]->path().top() ) ) { //DoMessageBox("No brushes selected, select ONLY brushes", "Error", eMB_OK); globalErrorStream() << "bobToolz FlipTerrain: No brushes selected, select ONLY 2 brushes.\n"; - return; + return; } } DBrush Brushes[2]; DPlane* Planes[2]; pntTripple Points[2]; - for( i = 0; i < 2; i++ ) { + for ( i = 0; i < 2; i++ ) { Brushes[i].LoadFromBrush( *brushes[i], false ); - if(!(Planes[i] = Brushes[i].FindPlaneWithClosestNormal( vUp )) || Brushes[i].FindPointsForPlane( Planes[i], Points[i], 3 ) != 3) { + if ( !( Planes[i] = Brushes[i].FindPlaneWithClosestNormal( vUp ) ) || Brushes[i].FindPointsForPlane( Planes[i], Points[i], 3 ) != 3 ) { //DoMessageBox("Error", "Error", eMB_OK); globalErrorStream() << "bobToolz FlipTerrain: ERROR (FindPlaneWithClosestNormal/FindPointsForPlane).\n"; return; @@ -766,39 +743,39 @@ void DoFlipTerrain() { int dontmatch[2] = { -1, -1 }; bool found = false; - for( i = 0; i < 3; i++ ) { - for( int j = 0; j < 3 && !found; j++ ) { - if(VectorCompare( (Points[0])[i]->_pnt, (Points[1])[j]->_pnt )) { + for ( i = 0; i < 3; i++ ) { + for ( int j = 0; j < 3 && !found; j++ ) { + if ( VectorCompare( ( Points[0] )[i]->_pnt, ( Points[1] )[j]->_pnt ) ) { found = true; break; } } - if(!found) { + if ( !found ) { dontmatch[0] = i; break; } found = false; } - if(dontmatch[0] == -1) { + if ( dontmatch[0] == -1 ) { //DoMessageBox("Error", "Error", eMB_OK); globalErrorStream() << "bobToolz FlipTerrain: ERROR (dontmatch[0]).\n"; return; } - for( i = 0; i < 3; i++ ) { - for( int j = 0; j < 3 && !found; j++ ) { - if(VectorCompare( (Points[1])[i]->_pnt, (Points[0])[j]->_pnt )) { + for ( i = 0; i < 3; i++ ) { + for ( int j = 0; j < 3 && !found; j++ ) { + if ( VectorCompare( ( Points[1] )[i]->_pnt, ( Points[0] )[j]->_pnt ) ) { found = true; break; } } - if(!found) { + if ( !found ) { dontmatch[1] = i; break; } found = false; } - if(dontmatch[1] == -1) { + if ( dontmatch[1] == -1 ) { //DoMessageBox("Error", "Error", eMB_OK); globalErrorStream() << "bobToolz FlipTerrain: ERROR (dontmatch[1]).\n"; return; @@ -808,82 +785,87 @@ void DoFlipTerrain() { vec3_t plnpnts2[3]; vec3_t plnpntsshr[3]; - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpnts1[0] ); - for( i = 0; i < 3; i++ ) { - if( dontmatch[0] != i ) { - VectorCopy( (Points[0])[i]->_pnt, plnpnts1[1] ); + VectorCopy( ( Points[0] )[dontmatch[0]]->_pnt, plnpnts1[0] ); + for ( i = 0; i < 3; i++ ) { + if ( dontmatch[0] != i ) { + VectorCopy( ( Points[0] )[i]->_pnt, plnpnts1[1] ); break; } } - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpnts1[2] ); + VectorCopy( ( Points[1] )[dontmatch[1]]->_pnt, plnpnts1[2] ); - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpnts2[0] ); - for( i = 0; i < 3; i++ ) { - if( dontmatch[1] != i && !VectorCompare( (Points[1])[i]->_pnt, plnpnts1[1] )) { - VectorCopy( (Points[1])[i]->_pnt, plnpnts2[1] ); + VectorCopy( ( Points[1] )[dontmatch[1]]->_pnt, plnpnts2[0] ); + for ( i = 0; i < 3; i++ ) { + if ( dontmatch[1] != i && !VectorCompare( ( Points[1] )[i]->_pnt, plnpnts1[1] ) ) { + VectorCopy( ( Points[1] )[i]->_pnt, plnpnts2[1] ); break; } } - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpnts2[2] ); + VectorCopy( ( Points[0] )[dontmatch[0]]->_pnt, plnpnts2[2] ); - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpntsshr[0] ); - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpntsshr[1] ); - if( (Points[1])[dontmatch[1]]->_pnt[2] < (Points[0])[dontmatch[0]]->_pnt[2] ) { - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpntsshr[2] ); - } else { - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpntsshr[2] ); + VectorCopy( ( Points[0] )[dontmatch[0]]->_pnt, plnpntsshr[0] ); + VectorCopy( ( Points[1] )[dontmatch[1]]->_pnt, plnpntsshr[1] ); + if ( ( Points[1] )[dontmatch[1]]->_pnt[2] < ( Points[0] )[dontmatch[0]]->_pnt[2] ) { + VectorCopy( ( Points[1] )[dontmatch[1]]->_pnt, plnpntsshr[2] ); + } + else { + VectorCopy( ( Points[0] )[dontmatch[0]]->_pnt, plnpntsshr[2] ); } plnpntsshr[2][2] -= 16; - for( i = 0; i < 3; i++ ) { - if( mins2[i] < mins1[i] ) { + for ( i = 0; i < 3; i++ ) { + if ( mins2[i] < mins1[i] ) { mins1[i] = mins2[i]; } - if( maxs2[i] > maxs1[i] ) { + if ( maxs2[i] > maxs1[i] ) { maxs1[i] = maxs2[i]; } } DBrush* newBrushes[2]; - newBrushes[0] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true); - newBrushes[1] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true); + newBrushes[0] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true ); + newBrushes[1] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true ); vec3_t normal; MakeNormal( plnpnts1[0], plnpnts1[1], plnpnts1[2], normal ); - if( normal[2] >= 0 ) { + if ( normal[2] >= 0 ) { newBrushes[0]->AddFace( plnpnts1[0], plnpnts1[1], plnpnts1[2], "textures/common/terrain", true ); - } else { + } + else { newBrushes[0]->AddFace( plnpnts1[2], plnpnts1[1], plnpnts1[0], "textures/common/terrain", true ); } MakeNormal( plnpnts2[0], plnpnts2[1], plnpnts2[2], normal ); - if( normal[2] >= 0 ) { + if ( normal[2] >= 0 ) { newBrushes[1]->AddFace( plnpnts2[0], plnpnts2[1], plnpnts2[2], "textures/common/terrain", true ); - } else { + } + else { newBrushes[1]->AddFace( plnpnts2[2], plnpnts2[1], plnpnts2[0], "textures/common/terrain", true ); } vec3_t vec; - MakeNormal( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], normal ); - + MakeNormal( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], normal ); + VectorSubtract( plnpnts1[2], plnpnts1[1], vec ); - if( DotProduct( vec, normal ) >= 0 ) { + if ( DotProduct( vec, normal ) >= 0 ) { newBrushes[0]->AddFace( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], "textures/common/caulk", true ); - } else { + } + else { newBrushes[0]->AddFace( plnpntsshr[2], plnpntsshr[1], plnpntsshr[0], "textures/common/caulk", true ); } VectorSubtract( plnpnts2[2], plnpnts2[1], vec ); - if( DotProduct( vec, normal ) >= 0 ) { + if ( DotProduct( vec, normal ) >= 0 ) { newBrushes[1]->AddFace( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], "textures/common/caulk", true ); - } else { + } + else { newBrushes[1]->AddFace( plnpntsshr[2], plnpntsshr[1], plnpntsshr[0], "textures/common/caulk", true ); } - for( i = 0; i < 2; i++ ) { + for ( i = 0; i < 2; i++ ) { newBrushes[i]->RemoveRedundantPlanes(); newBrushes[i]->BuildInRadiant( false, NULL, brushes[i]->path().parent().get_pointer() ); - Path_deleteTop(brushes[i]->path()); + Path_deleteTop( brushes[i]->path() ); delete newBrushes[i]; } diff --git a/contrib/bobtoolz/funchandlers-ctf-GTK.cpp b/contrib/bobtoolz/funchandlers-ctf-GTK.cpp index b01fc7cb..637cf5a2 100644 --- a/contrib/bobtoolz/funchandlers-ctf-GTK.cpp +++ b/contrib/bobtoolz/funchandlers-ctf-GTK.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "StdAfx.h" @@ -41,19 +41,16 @@ BOOL clrLst2Loaded = FALSE; // Helper Functions // //========================// -void LoadLists() -{ +void LoadLists(){ char buffer[256]; - if(!clrLst1Loaded) - { - clrLst1Loaded = LoadExclusionList(GetFilename(buffer, "plugins/bt/ctf-blue.txt"), &clrList_Blue); - LoadExclusionList(GetFilename(buffer, "plugins/bt/blue.txt"), &clrList_Blue); + if ( !clrLst1Loaded ) { + clrLst1Loaded = LoadExclusionList( GetFilename( buffer, "plugins/bt/ctf-blue.txt" ), &clrList_Blue ); + LoadExclusionList( GetFilename( buffer, "plugins/bt/blue.txt" ), &clrList_Blue ); } - if(!clrLst2Loaded) - { - clrLst2Loaded = LoadExclusionList(GetFilename(buffer, "plugins/bt/ctf-red.txt"), &clrList_Red); - LoadExclusionList(GetFilename(buffer, "plugins/bt/red.txt"), &clrList_Red); + if ( !clrLst2Loaded ) { + clrLst2Loaded = LoadExclusionList( GetFilename( buffer, "plugins/bt/ctf-red.txt" ), &clrList_Red ); + LoadExclusionList( GetFilename( buffer, "plugins/bt/red.txt" ), &clrList_Red ); } } @@ -62,20 +59,19 @@ void LoadLists() // Main Functions // //========================// -void DoCTFColourChanger() -{ - if(!clrLst1Loaded || !clrLst2Loaded) - { - DoMessageBox("CTF texture lists not found, this function will terminate.", "Error", MB_OK); +void DoCTFColourChanger(){ + if ( !clrLst1Loaded || !clrLst2Loaded ) { + DoMessageBox( "CTF texture lists not found, this function will terminate.", "Error", MB_OK ); return; } int ret = DoCTFColourChangeBox(); - if(ret == IDCANCEL) + if ( ret == IDCANCEL ) { return; + } + + int cnt = Min( clrList_Blue.size(), clrList_Red.size() ); - int cnt = Min(clrList_Blue.size(), clrList_Red.size()); - list::const_iterator Texture_change; list::const_iterator Texture_new; @@ -84,131 +80,132 @@ void DoCTFColourChanger() int eCnt = g_FuncTable.m_pfnGetEntityCount(); DMap world; - world.LoadAll(TRUE); + world.LoadAll( TRUE ); - if(ret == IDYES) - { - Texture_change = clrList_Blue.begin(); - Texture_new = clrList_Red.begin(); + if ( ret == IDYES ) { + Texture_change = clrList_Blue.begin(); + Texture_new = clrList_Red.begin(); } else { - Texture_change = clrList_Red.begin(); - Texture_new = clrList_Blue.begin(); + Texture_change = clrList_Red.begin(); + Texture_new = clrList_Blue.begin(); } - for(int i = 0; i < cnt; i++) + for ( int i = 0; i < cnt; i++ ) { - world.ResetTextures((*Texture_change).c_str(), fDummy, fDummy, 0, (*Texture_new).c_str(), TRUE); + world.ResetTextures( ( *Texture_change ).c_str(), fDummy, fDummy, 0, ( *Texture_new ).c_str(), TRUE ); Texture_change++; Texture_new++; } } -void DoSwapLights() -{ +void DoSwapLights(){ /* DMap world; - world.LoadAll(); - - for(list::const_iterator loopEnt = world.entityList.begin(); loopEnt != world.entityList.end(); loopEnt++) - { - DEntity* e = (*loopEnt); - DEPair* epLightColour = e->FindEPairByKey("_color"); - if(epLightColour) - { - float r, g, b; - sscanf(epLightColour->value, "%f %f %f", &r, &g, &b); - sprintf(epLightColour->value, "%f %f %f", b, g, r); - DMap::RebuildEntity(e); - } - }*/ + world.LoadAll(); + + for(list::const_iterator loopEnt = world.entityList.begin(); loopEnt != world.entityList.end(); loopEnt++) + { + DEntity* e = (*loopEnt); + DEPair* epLightColour = e->FindEPairByKey("_color"); + if(epLightColour) + { + float r, g, b; + sscanf(epLightColour->value, "%f %f %f", &r, &g, &b); + sprintf(epLightColour->value, "%f %f %f", b, g, r); + DMap::RebuildEntity(e); + } + }*/ int cnt = g_FuncTable.m_pfnGetEntityCount(); - for(int i = 0; i < cnt; i++) + for ( int i = 0; i < cnt; i++ ) { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); + void* ent = g_FuncTable.m_pfnGetEntityHandle( i ); - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) + for ( epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList( ent ); epList; epList = epList->next ) { - if(!stricmp("_color", epList->key)) - { + if ( !stricmp( "_color", epList->key ) ) { float r, g, b; - sscanf(epList->value, "%f %f %f", &r, &g, &b); - sprintf(epList->value, "%f %f %f", b, g, r); + sscanf( epList->value, "%f %f %f", &r, &g, &b ); + sprintf( epList->value, "%f %f %f", b, g, r ); } } } } -void DoChangeAngles() -{ +void DoChangeAngles(){ int cnt = g_FuncTable.m_pfnGetEntityCount(); - for(int i = 0; i < cnt; i++) + for ( int i = 0; i < cnt; i++ ) { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); + void* ent = g_FuncTable.m_pfnGetEntityHandle( i ); - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) + for ( epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList( ent ); epList; epList = epList->next ) { - if(!stricmp("angle", epList->key)) - { + if ( !stricmp( "angle", epList->key ) ) { float angle; - sscanf(epList->value, "%f", &angle); + sscanf( epList->value, "%f", &angle ); angle += 180; - while(angle > 360) + while ( angle > 360 ) angle -= 360; - sprintf(epList->value, "%f", angle); + sprintf( epList->value, "%f", angle ); } } } } -void DoSwapSpawns() -{ +void DoSwapSpawns(){ int cnt = g_FuncTable.m_pfnGetEntityCount(); - for(int i = 0; i < cnt; i++) + for ( int i = 0; i < cnt; i++ ) { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); + void* ent = g_FuncTable.m_pfnGetEntityHandle( i ); - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) + for ( epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList( ent ); epList; epList = epList->next ) { - if(!stricmp("classname", epList->key)) - { - if(!strcmp(epList->value, "team_CTF_redplayer")) - sprintf(epList->value, "team_CTF_blueplayer"); - else if(!strcmp(epList->value, "team_CTF_blueplayer")) - sprintf(epList->value, "team_CTF_redplayer"); - - if(!strcmp(epList->value, "team_CTF_redspawn")) - sprintf(epList->value, "team_CTF_bluespawn"); - else if(!strcmp(epList->value, "team_CTF_bluespawn")) - sprintf(epList->value, "team_CTF_redspawn"); - - if(!strcmp(epList->value, "team_CTF_redflag")) - sprintf(epList->value, "team_CTF_blueflag"); - else if(!strcmp(epList->value, "team_CTF_blueflag")) - sprintf(epList->value, "team_CTF_redflag") + if ( !stricmp( "classname", epList->key ) ) { + if ( !strcmp( epList->value, "team_CTF_redplayer" ) ) { + sprintf( epList->value, "team_CTF_blueplayer" ); + } + else if ( !strcmp( epList->value, "team_CTF_blueplayer" ) ) { + sprintf( epList->value, "team_CTF_redplayer" ); + } + + if ( !strcmp( epList->value, "team_CTF_redspawn" ) ) { + sprintf( epList->value, "team_CTF_bluespawn" ); + } + else if ( !strcmp( epList->value, "team_CTF_bluespawn" ) ) { + sprintf( epList->value, "team_CTF_redspawn" ); + } + + if ( !strcmp( epList->value, "team_CTF_redflag" ) ) { + sprintf( epList->value, "team_CTF_blueflag" ); + } + else if ( !strcmp( epList->value, "team_CTF_blueflag" ) ) { + sprintf( epList->value, "team_CTF_redflag" ) ; - if(!strcmp(epList->value, "team_redobelisk")) - sprintf(epList->value, "team_blueobelisk"); - else if(!strcmp(epList->value, "team_blueobelisk")) - sprintf(epList->value, "team_redobelisk"); + } + if ( !strcmp( epList->value, "team_redobelisk" ) ) { + sprintf( epList->value, "team_blueobelisk" ); + } + else if ( !strcmp( epList->value, "team_blueobelisk" ) ) { + sprintf( epList->value, "team_redobelisk" ); + } } } } } /*void test() -{ - DMap world; - world.LoadAll(); - - for(list::const_iterator ents = world.entityList.begin(); ents != world.entityList.end(); ents++) - { - (*ents)->RemoveFromRadiant(); - } -}*/ + { + DMap world; + world.LoadAll(); + + for(list::const_iterator ents = world.entityList.begin(); ents != world.entityList.end(); ents++) + { + (*ents)->RemoveFromRadiant(); + } + }*/ diff --git a/contrib/bobtoolz/funchandlers.cpp b/contrib/bobtoolz/funchandlers.cpp index a429b78d..2a404211 100644 --- a/contrib/bobtoolz/funchandlers.cpp +++ b/contrib/bobtoolz/funchandlers.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "StdAfx.h" @@ -39,72 +39,73 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "DShape.h" // for autocaulk -std::list exclusionList; // whole brush exclusion -std::list exclusionList_Face; // single face exclusion +std::list exclusionList; // whole brush exclusion +std::list exclusionList_Face; // single face exclusion BOOL el1Loaded; BOOL el2Loaded; -DBobView* g_PathView = NULL; +DBobView* g_PathView = NULL; // ------------- /************************ - Global Variables + Global Variables ************************/ -CPolygonDialog polygonDlg; -CIntersectDialog intrDlg; -CStairDialog stairDlg; -CDoorDialog doorDlg; -CAutoCaulkStartDialog autocaulkDlg; -CTextureResetDialog texRstDlg; -CPathPlotterDialog ppDlg; +CPolygonDialog polygonDlg; +CIntersectDialog intrDlg; +CStairDialog stairDlg; +CDoorDialog doorDlg; +CAutoCaulkStartDialog autocaulkDlg; +CTextureResetDialog texRstDlg; +CPathPlotterDialog ppDlg; /************************ - --Main Functions-- + --Main Functions-- ************************/ -void LoadLists() -{ +void LoadLists(){ char buffer[256]; - if(!el1Loaded) - el1Loaded = LoadExclusionList(GetFilename(buffer, "bt\\bt-el1.txt"), &exclusionList); - if(!el2Loaded) - el2Loaded = LoadExclusionList(GetFilename(buffer, "bt\\bt-el2.txt"), &exclusionList); + if ( !el1Loaded ) { + el1Loaded = LoadExclusionList( GetFilename( buffer, "bt\\bt-el1.txt" ), &exclusionList ); + } + if ( !el2Loaded ) { + el2Loaded = LoadExclusionList( GetFilename( buffer, "bt\\bt-el2.txt" ), &exclusionList ); + } } -void PolygonBuilder(vec3_t vMin, vec3_t vMax) -{ +void PolygonBuilder( vec3_t vMin, vec3_t vMax ){ // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; + if ( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) { + MessageBox( NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK ); + return; } // tell Radiant we want to access the selected brushes g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - + // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); + brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); // cant release until we delete the brush, if we do... // ask user for type, size, etc.... - if(polygonDlg.DoModal() == IDOK) - { + if ( polygonDlg.DoModal() == IDOK ) { DShape poly; - g_FuncTable.m_pfnDeleteBrushHandle(brush); + g_FuncTable.m_pfnDeleteBrushHandle( brush ); - if(polygonDlg.m_bInverse) - poly.BuildInversePrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop); + if ( polygonDlg.m_bInverse ) { + poly.BuildInversePrism( vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop ); + } else { - if(polygonDlg.m_bBorder) - poly.BuildBorderedPrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_nBorderSize, polygonDlg.m_bAlignTop); - else - poly.BuildRegularPrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop); + if ( polygonDlg.m_bBorder ) { + poly.BuildBorderedPrism( vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_nBorderSize, polygonDlg.m_bAlignTop ); + } + else{ + poly.BuildRegularPrism( vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop ); + } } poly.Commit(); @@ -115,134 +116,135 @@ void PolygonBuilder(vec3_t vMin, vec3_t vMax) } -void IntersectionFinder() -{ - if(intrDlg.DoModal() == IDCANCEL) +void IntersectionFinder(){ + if ( intrDlg.DoModal() == IDCANCEL ) { return; + } - if(intrDlg.m_nBrushOptions == BRUSH_OPT_SELECTED) - { + if ( intrDlg.m_nBrushOptions == BRUSH_OPT_SELECTED ) { // ensure we have enough brushes selected - if( g_FuncTable.m_pfnSelectedBrushCount() < 2 ) - { - MessageBox(NULL, "Invalid number of brushes selected, choose at least 2", "Error", MB_OK); - return; + if ( g_FuncTable.m_pfnSelectedBrushCount() < 2 ) { + MessageBox( NULL, "Invalid number of brushes selected, choose at least 2", "Error", MB_OK ); + return; } } - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); + CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); + intrInfoDlg->Create( IDD_INTERSECT_INFO_DIALOG ); DEntity world; - switch(intrDlg.m_nBrushOptions) + switch ( intrDlg.m_nBrushOptions ) { case BRUSH_OPT_SELECTED: - { - world.LoadSelectedBrushes(&intrInfoDlg->m_prog1); - break; - } + { + world.LoadSelectedBrushes( &intrInfoDlg->m_prog1 ); + break; + } case BRUSH_OPT_WHOLE_MAP: - { - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); - break; - } + { + world.LoadFromEntity( 0, &intrInfoDlg->m_prog1 ); + break; + } } - world.RemoveNonCheckBrushes(&exclusionList, intrDlg.m_bUseDetail); + world.RemoveNonCheckBrushes( &exclusionList, intrDlg.m_bUseDetail ); BOOL* pbSelectList; - if(intrDlg.m_bDuplicateOnly) + if ( intrDlg.m_bDuplicateOnly ) { pbSelectList = world.BuildDuplicateList(); - else + } + else{ pbSelectList = world.BuildIntersectList(); + } + + world.SelectBrushes( pbSelectList ); - world.SelectBrushes(pbSelectList); - intrInfoDlg->DestroyWindow(); delete[] pbSelectList; } -void StairBuilder(vec3_t vMin, vec3_t vMax) -{ +void StairBuilder( vec3_t vMin, vec3_t vMax ){ // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; + if ( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) { + MessageBox( NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK ); + return; } // tell Radiant we want to access the selected brushes g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - + // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); + brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); // cant release until we delete the brush, if we do... // ask user for type, size, etc.... - if(stairDlg.DoModal() == IDOK) - { - + if ( stairDlg.DoModal() == IDOK ) { + // calc brush size vec3_t size; - _VectorSubtract(vMax, vMin, size); + _VectorSubtract( vMax, vMin, size ); - if(((int)size[2] % stairDlg.m_nStairHeight) != 0) - { + if ( ( (int)size[2] % stairDlg.m_nStairHeight ) != 0 ) { // stairs must fit evenly into brush - MessageBox(NULL, "Invalid stair height\nHeight of block must be divisable by stair height", "Error", MB_OK); + MessageBox( NULL, "Invalid stair height\nHeight of block must be divisable by stair height", "Error", MB_OK ); } else { - + // Remove Size Brush - g_FuncTable.m_pfnDeleteBrushHandle(brush); + g_FuncTable.m_pfnDeleteBrushHandle( brush ); + - // Get Step Count, Direction of Stairs, Stair Style int numSteps = (int)size[2] / stairDlg.m_nStairHeight; int direction = stairDlg.m_StairDir; int style = stairDlg.m_StairStyle; - if(stairDlg.m_StairStyle == STYLE_CORNER) - { - BuildCornerStairs(vMin, vMax, numSteps, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture); + if ( stairDlg.m_StairStyle == STYLE_CORNER ) { + BuildCornerStairs( vMin, vMax, numSteps, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture ); } else { // Get Step Dimensions float stairHeight = (float)stairDlg.m_nStairHeight; float stairWidth; - if((direction == MOVE_EAST) || (direction == MOVE_WEST)) - stairWidth = (size[0])/numSteps; - else - stairWidth = (size[1])/numSteps; + if ( ( direction == MOVE_EAST ) || ( direction == MOVE_WEST ) ) { + stairWidth = ( size[0] ) / numSteps; + } + else{ + stairWidth = ( size[1] ) / numSteps; + } // Build Base For Stair (bob's style) - if(style == STYLE_BOB) - Build_Wedge(direction, vMin, vMax, TRUE); + if ( style == STYLE_BOB ) { + Build_Wedge( direction, vMin, vMax, TRUE ); + } // Set First Step Starting Position vMax[2] = vMin[2] + stairHeight; - SetInitialStairPos(direction, vMin, vMax, stairWidth); + SetInitialStairPos( direction, vMin, vMax, stairWidth ); // Build The Steps - for(int i = 0; i < numSteps; i++) + for ( int i = 0; i < numSteps; i++ ) { - if(style == STYLE_BOB) - Build_StairStep_Wedge(direction, vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, stairDlg.m_bDetail); - else if(style == STYLE_ORIGINAL) - Build_StairStep(vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, direction); + if ( style == STYLE_BOB ) { + Build_StairStep_Wedge( direction, vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, stairDlg.m_bDetail ); + } + else if ( style == STYLE_ORIGINAL ) { + Build_StairStep( vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, direction ); + } // get step into next position - MoveBlock(direction, vMin, vMax, stairWidth); + MoveBlock( direction, vMin, vMax, stairWidth ); vMax[2] += stairHeight; - if(style == STYLE_BOB) - vMin[2] += stairHeight; // wedge bottom must be raised + if ( style == STYLE_BOB ) { + vMin[2] += stairHeight; // wedge bottom must be raised + } } } } @@ -251,149 +253,145 @@ void StairBuilder(vec3_t vMin, vec3_t vMax) g_FuncTable.m_pfnReleaseSelectedBrushHandles(); } -void DoorBuilder(vec3_t vMin, vec3_t vMax) -{ +void DoorBuilder( vec3_t vMin, vec3_t vMax ){ // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; + if ( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) { + MessageBox( NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK ); + return; } // tell Radiant we want to access the selected brushes g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - + // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); + brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); // cant release until we delete the brush, if we do... - strcpy(doorDlg.m_fbTextureName.GetBuffer(256), g_FuncTable.m_pfnGetCurrentTexture()); - - if(doorDlg.DoModal() == IDOK) - { - g_FuncTable.m_pfnDeleteBrushHandle(brush); + strcpy( doorDlg.m_fbTextureName.GetBuffer( 256 ), g_FuncTable.m_pfnGetCurrentTexture() ); - BuildDoorsX2(vMin, vMax, - doorDlg.m_bSclMainHor, doorDlg.m_bSclMainVert, - doorDlg.m_bSclTrimHor, doorDlg.m_bSclTrimVert, - (LPCTSTR)doorDlg.m_fbTextureName, - (LPCTSTR)doorDlg.m_trimTextureName, - doorDlg.m_doorDirection); + if ( doorDlg.DoModal() == IDOK ) { + g_FuncTable.m_pfnDeleteBrushHandle( brush ); + + BuildDoorsX2( vMin, vMax, + doorDlg.m_bSclMainHor, doorDlg.m_bSclMainVert, + doorDlg.m_bSclTrimHor, doorDlg.m_bSclTrimVert, + (LPCTSTR)doorDlg.m_fbTextureName, + (LPCTSTR)doorDlg.m_trimTextureName, + doorDlg.m_doorDirection ); } g_FuncTable.m_pfnReleaseSelectedBrushHandles(); } -void FixBrushes() -{ +void FixBrushes(){ DEntity world; - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); + CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); + intrInfoDlg->Create( IDD_INTERSECT_INFO_DIALOG ); - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); + world.LoadFromEntity( 0, &intrInfoDlg->m_prog1 ); intrInfoDlg->DestroyWindow(); - - CBrushCheckDialog* chkDlg = new CBrushCheckDialog(); - chkDlg->Create(IDD_BRUSHCHECKER_DIALOG); - int count = world.FixBrushes(TRUE, &chkDlg->m_prog1); + CBrushCheckDialog* chkDlg = new CBrushCheckDialog(); + chkDlg->Create( IDD_BRUSHCHECKER_DIALOG ); + + int count = world.FixBrushes( TRUE, &chkDlg->m_prog1 ); chkDlg->DestroyWindow(); - Sys_Printf("%i invalid/duplicate planes removed\n", count); + Sys_Printf( "%i invalid/duplicate planes removed\n", count ); } -void AutoCaulk() -{ - UndoableCommand undo("bobToolz.autoCaulk"); +void AutoCaulk(){ + UndoableCommand undo( "bobToolz.autoCaulk" ); - if(!el1Loaded) + if ( !el1Loaded ) { autocaulkDlg.m_Warning1 = "WARNING: Brush exclusion list not found\n, ALL BRUSHES WILL BE USED"; + } - if(autocaulkDlg.DoModal() == IDCANCEL) + if ( autocaulkDlg.DoModal() == IDCANCEL ) { return; + } - if(autocaulkDlg.m_nMode == MODE_AC_BUILD_MINI_PRT) - { - BuildMiniPrt(&exclusionList); + if ( autocaulkDlg.m_nMode == MODE_AC_BUILD_MINI_PRT ) { + BuildMiniPrt( &exclusionList ); return; } CAutoCaulkDialog* acDlg = new CAutoCaulkDialog; - acDlg->Create(IDD_AUTOCAULK_DIALOG); + acDlg->Create( IDD_AUTOCAULK_DIALOG ); char filename[1204]; - if(autocaulkDlg.m_nMode == MODE_AC_NORMAL) - { + if ( autocaulkDlg.m_nMode == MODE_AC_NORMAL ) { char* rad_filename = g_BSPTable.m_pfnGetMapName(); - if(!rad_filename) - { - MessageBox(NULL, "An Error Occurred While Trying To Get The Map Filename", "Error", MB_OK); + if ( !rad_filename ) { + MessageBox( NULL, "An Error Occurred While Trying To Get The Map Filename", "Error", MB_OK ); acDlg->DestroyWindow(); return; } - strcpy(filename, rad_filename); - - char* ext = strrchr(filename, '.')+1; - strcpy(ext, "prt");// rename the extension + strcpy( filename, rad_filename ); + + char* ext = strrchr( filename, '.' ) + 1; + strcpy( ext, "prt" ); // rename the extension } else - { - IEpair* pEp = g_EpairTable.m_pfnIEpairForProjectKeys(); - char *pn = pEp->ValueForKey("mapspath"); - pEp->DecRef(); + { + IEpair* pEp = g_EpairTable.m_pfnIEpairForProjectKeys(); + char *pn = pEp->ValueForKey( "mapspath" ); + pEp->DecRef(); - strcpy( filename, pn ); - strcat( filename, "/ac_prt.prt" ); - } + strcpy( filename, pn ); + strcat( filename, "/ac_prt.prt" ); + } DEntity portals; - if(!portals.LoadFromPrt(filename, &acDlg->m_prog1)) - { - MessageBox(NULL, "Failed To Load Portal File", "Error", MB_OK); + if ( !portals.LoadFromPrt( filename, &acDlg->m_prog1 ) ) { + MessageBox( NULL, "Failed To Load Portal File", "Error", MB_OK ); acDlg->DestroyWindow(); return; } // load portal file - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); + CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); + intrInfoDlg->Create( IDD_INTERSECT_INFO_DIALOG ); DEntity world; - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); + world.LoadFromEntity( 0, &intrInfoDlg->m_prog1 ); intrInfoDlg->DestroyWindow(); - if(autocaulkDlg.m_nMode == MODE_AC_NORMAL) - world.RemoveNonCheckBrushes(&exclusionList, FALSE); - else - world.RemoveNonCheckBrushes(&exclusionList, TRUE); + if ( autocaulkDlg.m_nMode == MODE_AC_NORMAL ) { + world.RemoveNonCheckBrushes( &exclusionList, FALSE ); + } + else{ + world.RemoveNonCheckBrushes( &exclusionList, TRUE ); + } - world.ResetChecks(&exclusionList_Face); + world.ResetChecks( &exclusionList_Face ); int caulkedCount = 0; - int killCnt = world.AutoCaulk(&portals, autocaulkDlg.m_bAllowDestruction, &caulkedCount, &acDlg->m_prog2); + int killCnt = world.AutoCaulk( &portals, autocaulkDlg.m_bAllowDestruction, &caulkedCount, &acDlg->m_prog2 ); - if(autocaulkDlg.m_bAllowDestruction) - Sys_Printf("%i unrequired brush(es) killed\n", killCnt); - Sys_Printf("%i face(s) caulked\n", caulkedCount); + if ( autocaulkDlg.m_bAllowDestruction ) { + Sys_Printf( "%i unrequired brush(es) killed\n", killCnt ); + } + Sys_Printf( "%i face(s) caulked\n", caulkedCount ); acDlg->DestroyWindow(); } -void ResetTextures() -{ +void ResetTextures(){ texRstDlg.m_TextureName = GetCurrentTexture(); texRstDlg.m_NewTextureName = GetCurrentTexture(); - if(texRstDlg.DoModal() == IDCANCEL) + if ( texRstDlg.DoModal() == IDCANCEL ) { return; + } float fScale[2]; float fShift[2]; @@ -404,102 +402,102 @@ void ResetTextures() fShift[0] = (float)texRstDlg.m_nShiftHorizontal; DEntity world; - world.LoadFromEntity(0, NULL); + world.LoadFromEntity( 0, NULL ); - if(texRstDlg.m_bAllTextures) - world.ResetTextures(NULL, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture); - else - world.ResetTextures(texRstDlg.m_TextureName, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture); + if ( texRstDlg.m_bAllTextures ) { + world.ResetTextures( NULL, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture ); + } + else{ + world.ResetTextures( texRstDlg.m_TextureName, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture ); + } } -void PathPlotter() -{ +void PathPlotter(){ int ret = ppDlg.DoModal(); - if(ret == IDCANCEL) + if ( ret == IDCANCEL ) { return; - if(ret == IDNO) - { - if(g_PathView) + } + if ( ret == IDNO ) { + if ( g_PathView ) { delete g_PathView; + } return; } - if( g_FuncTable.m_pfnSelectedBrushCount() != 1) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); + if ( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) { + MessageBox( NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK ); return; } // tell Radiant we want to access the selected brushes g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - + // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); + brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); // cant release until we delete the brush, if we do... DEntity world; - world.LoadEPairList(*g_FuncTable.m_pfnGetEntityKeyValList(brush->owner)); + world.LoadEPairList( *g_FuncTable.m_pfnGetEntityKeyValList( brush->owner ) ); - DEPair* trigger_ep = world.FindEPairByKey("targetname"); + DEPair* trigger_ep = world.FindEPairByKey( "targetname" ); - if(trigger_ep) - { - if(!strcmp(world.m_Classname, "trigger_push")) - { - DEPair* target_ep = world.FindEPairByKey("target"); - if(target_ep) - { - entity_s* entTarget = FindEntityFromTargetname(target_ep->value); - if(entTarget) - { - if(g_PathView) + if ( trigger_ep ) { + if ( !strcmp( world.m_Classname, "trigger_push" ) ) { + DEPair* target_ep = world.FindEPairByKey( "target" ); + if ( target_ep ) { + entity_s* entTarget = FindEntityFromTargetname( target_ep->value ); + if ( entTarget ) { + if ( g_PathView ) { delete g_PathView; + } g_PathView = new DBobView; - g_PathView->Begin(trigger_ep->value, target_ep->value, ppDlg.m_fMultiplier, ppDlg.m_nPoints, ppDlg.m_fGravity, ppDlg.m_bNoUpdate, ppDlg.m_bShowExtra); + g_PathView->Begin( trigger_ep->value, target_ep->value, ppDlg.m_fMultiplier, ppDlg.m_nPoints, ppDlg.m_fGravity, ppDlg.m_bNoUpdate, ppDlg.m_bShowExtra ); + } + else{ + MessageBox( NULL, "trigger_push target could not be found.", "Error", MB_OK ); } - else - MessageBox(NULL, "trigger_push target could not be found.", "Error", MB_OK); } - else - MessageBox(NULL, "trigger_push has no target.", "Error", MB_OK); + else{ + MessageBox( NULL, "trigger_push has no target.", "Error", MB_OK ); + } } - else - MessageBox(NULL, "You must select a 'trigger_push' entity.", "Error", MB_OK); - } - else - MessageBox(NULL, "Entity must have a targetname", "Error", MB_OK); + else{ + MessageBox( NULL, "You must select a 'trigger_push' entity.", "Error", MB_OK ); + } + } + else{ + MessageBox( NULL, "Entity must have a targetname", "Error", MB_OK ); + } g_FuncTable.m_pfnReleaseSelectedBrushHandles(); } -void PitBuilder(vec3_t vMin, vec3_t vMax) -{ +void PitBuilder( vec3_t vMin, vec3_t vMax ){ // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; + if ( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) { + MessageBox( NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK ); + return; } // tell Radiant we want to access the selected brushes g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - + // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); + brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); // cant release until we delete the brush, if we do... DShape pit; - if(pit.BuildPit(vMin, vMax)) - { + if ( pit.BuildPit( vMin, vMax ) ) { pit.Commit(); - g_FuncTable.m_pfnDeleteBrushHandle(brush); + g_FuncTable.m_pfnDeleteBrushHandle( brush ); + } + else{ + MessageBox( NULL, "Failed To Make Pit\nTry Making The Brush Bigger", "Error", MB_OK ); } - else - MessageBox(NULL, "Failed To Make Pit\nTry Making The Brush Bigger", "Error", MB_OK); g_FuncTable.m_pfnReleaseSelectedBrushHandles(); } diff --git a/contrib/bobtoolz/funchandlers.h b/contrib/bobtoolz/funchandlers.h index 3f4202ff..b25cc6d8 100644 --- a/contrib/bobtoolz/funchandlers.h +++ b/contrib/bobtoolz/funchandlers.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ class DBobView; class DVisDrawer; @@ -28,22 +28,22 @@ extern DTrainDrawer* g_TrainView; extern DTreePlanter* g_TreePlanter; // intersect stuff -#define BRUSH_OPT_WHOLE_MAP 0 -#define BRUSH_OPT_SELECTED 1 +#define BRUSH_OPT_WHOLE_MAP 0 +#define BRUSH_OPT_SELECTED 1 // defines for stairs -#define MOVE_NORTH 0 -#define MOVE_SOUTH 1 -#define MOVE_EAST 2 -#define MOVE_WEST 3 +#define MOVE_NORTH 0 +#define MOVE_SOUTH 1 +#define MOVE_EAST 2 +#define MOVE_WEST 3 -#define STYLE_ORIGINAL 0 -#define STYLE_BOB 1 -#define STYLE_CORNER 2 +#define STYLE_ORIGINAL 0 +#define STYLE_BOB 1 +#define STYLE_CORNER 2 // defines for doors -#define DIRECTION_NS 0 -#define DIRECTION_EW 1 +#define DIRECTION_NS 0 +#define DIRECTION_EW 1 // help void LoadLists(); diff --git a/contrib/bobtoolz/lists.cpp b/contrib/bobtoolz/lists.cpp index 9823b051..9b657c31 100644 --- a/contrib/bobtoolz/lists.cpp +++ b/contrib/bobtoolz/lists.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "lists.h" @@ -27,25 +27,25 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "misc.h" -bool LoadExclusionList(char* filename, std::list* exclusionList) -{ - FILE* eFile = fopen(filename, "r"); - if(eFile) - { +bool LoadExclusionList( char* filename, std::list* exclusionList ){ + FILE* eFile = fopen( filename, "r" ); + if ( eFile ) { char buffer[256]; int cnt = 0; - while(!feof(eFile)) + while ( !feof( eFile ) ) { - memset(buffer, 0, 256); - fscanf(eFile, "%s\n", buffer); + memset( buffer, 0, 256 ); + fscanf( eFile, "%s\n", buffer ); - if(strlen(buffer) > 0) - exclusionList->push_back(buffer); - else + if ( strlen( buffer ) > 0 ) { + exclusionList->push_back( buffer ); + } + else{ cnt++; + } } - fclose(eFile); + fclose( eFile ); return TRUE; } @@ -54,29 +54,27 @@ bool LoadExclusionList(char* filename, std::list* exclusionList) return FALSE; } -bool LoadGList(char* filename, GList** loadlist) -{ - FILE* eFile = fopen(filename, "r"); - if(eFile) - { +bool LoadGList( char* filename, GList** loadlist ){ + FILE* eFile = fopen( filename, "r" ); + if ( eFile ) { char buffer[256]; int cnt = 0; - while(!feof(eFile)) + while ( !feof( eFile ) ) { - memset(buffer, 0, 256); - fscanf(eFile, "%s\n", buffer); - - if(strlen(buffer) > 0) - { - char* buffer2 = new char[strlen(buffer) + 1]; - strcpy(buffer2, buffer); - *loadlist = g_list_append(*loadlist, buffer2); + memset( buffer, 0, 256 ); + fscanf( eFile, "%s\n", buffer ); + + if ( strlen( buffer ) > 0 ) { + char* buffer2 = new char[strlen( buffer ) + 1]; + strcpy( buffer2, buffer ); + *loadlist = g_list_append( *loadlist, buffer2 ); } - else + else{ cnt++; + } } - fclose(eFile); + fclose( eFile ); return TRUE; } diff --git a/contrib/bobtoolz/lists.h b/contrib/bobtoolz/lists.h index c4ccf77e..827c9cbc 100644 --- a/contrib/bobtoolz/lists.h +++ b/contrib/bobtoolz/lists.h @@ -1,25 +1,25 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include "str.h" -typedef struct _GList GList; +typedef struct _GList GList; -bool LoadExclusionList(char* filename, std::list* exclusionList); -bool LoadGList(char* filename, GList** loadlist); +bool LoadExclusionList( char* filename, std::list* exclusionList ); +bool LoadGList( char* filename, GList** loadlist ); diff --git a/contrib/bobtoolz/misc.cpp b/contrib/bobtoolz/misc.cpp index 5d926986..aa22640a 100644 --- a/contrib/bobtoolz/misc.cpp +++ b/contrib/bobtoolz/misc.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "misc.h" @@ -49,100 +49,95 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "scenelib.h" /*========================== - Global Vars -==========================*/ + Global Vars + ==========================*/ //HANDLE bsp_process; -char g_CurrentTexture[256] = ""; +char g_CurrentTexture[256] = ""; //============================================================= //============================================================= -void ReadCurrentTexture() -{ +void ReadCurrentTexture(){ const char* textureName = GlobalRadiant().TextureBrowser_getSelectedShader(); - strcpy(g_CurrentTexture, textureName); + strcpy( g_CurrentTexture, textureName ); } -const char* GetCurrentTexture() -{ +const char* GetCurrentTexture(){ ReadCurrentTexture(); return g_CurrentTexture; } -void MoveBlock(int dir, vec3_t min, vec3_t max, float dist) -{ - switch(dir) +void MoveBlock( int dir, vec3_t min, vec3_t max, float dist ){ + switch ( dir ) { - case MOVE_EAST: - { - min[0]+=dist; - max[0]+=dist; - break; - } - case MOVE_WEST: - { - min[0]-=dist; - max[0]-=dist; - break; - } - case MOVE_NORTH: - { - min[1]+=dist; - max[1]+=dist; - break; - } - case MOVE_SOUTH: - { - min[1]-=dist; - max[1]-=dist; - break; - } + case MOVE_EAST: + { + min[0] += dist; + max[0] += dist; + break; + } + case MOVE_WEST: + { + min[0] -= dist; + max[0] -= dist; + break; + } + case MOVE_NORTH: + { + min[1] += dist; + max[1] += dist; + break; + } + case MOVE_SOUTH: + { + min[1] -= dist; + max[1] -= dist; + break; + } } } -void SetInitialStairPos(int dir, vec3_t min, vec3_t max, float width) -{ - switch(dir) +void SetInitialStairPos( int dir, vec3_t min, vec3_t max, float width ){ + switch ( dir ) { - case MOVE_EAST: - { - max[0] = min[0] + width; - break; - } - case MOVE_WEST: - { - min[0] = max[0] - width; - break; - } - case MOVE_NORTH: - { - max[1] = min[1] + width; - break; - } - case MOVE_SOUTH: - { - min[1] = max[1] - width; - break; - } + case MOVE_EAST: + { + max[0] = min[0] + width; + break; + } + case MOVE_WEST: + { + min[0] = max[0] - width; + break; + } + case MOVE_NORTH: + { + max[1] = min[1] + width; + break; + } + case MOVE_SOUTH: + { + min[1] = max[1] - width; + break; + } } } -char* TranslateString (char *buf) -{ - static char buf2[32768]; +char* TranslateString( char *buf ){ + static char buf2[32768]; - std::size_t l = strlen(buf); + std::size_t l = strlen( buf ); char* out = buf2; - for (int i=0 ; i -bool Q_Exec( const char *pCmd, bool bCreateConsole ) -{ +bool Q_Exec( const char *pCmd, bool bCreateConsole ){ // G_DeWan: Don't know if this is needed for linux version PROCESS_INFORMATION pi; STARTUPINFO si = {0}; // Initialize all members to zero - si.cb = sizeof(STARTUPINFO); // Set byte count - DWORD dwCreationFlags; + si.cb = sizeof( STARTUPINFO ); // Set byte count + DWORD dwCreationFlags; - if (bCreateConsole) - dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; - else - dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; + if ( bCreateConsole ) { + dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; + } + else{ + dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; + } - for(; *pCmd == ' '; pCmd++); + for (; *pCmd == ' '; pCmd++ ) ; - if(!CreateProcess(NULL, (char *)pCmd, NULL, NULL, false, dwCreationFlags, NULL, NULL, &si, &pi)) + if ( !CreateProcess( NULL, (char *)pCmd, NULL, NULL, false, dwCreationFlags, NULL, NULL, &si, &pi ) ) { return false; + } - return true; + return true; } #endif -void StartBSP() -{ +void StartBSP(){ char exename[256]; - GetFilename(exename, "q3map"); - UnixToDosPath(exename); // do we want this done in linux version? + GetFilename( exename, "q3map" ); + UnixToDosPath( exename ); // do we want this done in linux version? + + char mapname[256]; + const char *pn = GlobalRadiant().getMapsPath(); - char mapname[256]; - const char *pn = GlobalRadiant().getMapsPath(); - strcpy( mapname, pn ); strcat( mapname, "/ac_prt.map" ); - UnixToDosPath(mapname); + UnixToDosPath( mapname ); char command[1024]; - sprintf(command, "%s -nowater -fulldetail %s", exename, mapname); + sprintf( command, "%s -nowater -fulldetail %s", exename, mapname ); Q_Exec( command, true ); } class EntityWriteMiniPrt { - mutable DEntity world; - FILE* pFile; - std::list* exclusionList; +mutable DEntity world; +FILE* pFile; +std::list* exclusionList; public: - EntityWriteMiniPrt(FILE* pFile, std::list* exclusionList) - : pFile(pFile), exclusionList(exclusionList) - { - } - void operator()(scene::Instance& instance) const - { - const char* classname = Node_getEntity(instance.path().top())->getKeyValue("classname"); - - if(!strcmp(classname, "worldspawn")) - { - world.LoadFromEntity(instance.path().top(), false); - world.RemoveNonCheckBrushes(exclusionList, true); - world.SaveToFile(pFile); - } - else if(strstr(classname, "info_")) - { - world.ClearBrushes(); - world.ClearEPairs(); - world.LoadEPairList(Node_getEntity(instance.path().top())); - world.SaveToFile(pFile); - } - } +EntityWriteMiniPrt( FILE* pFile, std::list* exclusionList ) + : pFile( pFile ), exclusionList( exclusionList ){ +} +void operator()( scene::Instance& instance ) const { + const char* classname = Node_getEntity( instance.path().top() )->getKeyValue( "classname" ); + + if ( !strcmp( classname, "worldspawn" ) ) { + world.LoadFromEntity( instance.path().top(), false ); + world.RemoveNonCheckBrushes( exclusionList, true ); + world.SaveToFile( pFile ); + } + else if ( strstr( classname, "info_" ) ) { + world.ClearBrushes(); + world.ClearEPairs(); + world.LoadEPairList( Node_getEntity( instance.path().top() ) ); + world.SaveToFile( pFile ); + } +} }; - -void BuildMiniPrt(std::list* exclusionList) -{ + +void BuildMiniPrt( std::list* exclusionList ){ // yes, we could just use -fulldetail option, but, as SPOG said // it'd be faster without all the hint, donotenter etc textures and // doors, etc - - + + char buffer[128]; - const char *pn = GlobalRadiant().getMapsPath(); + const char *pn = GlobalRadiant().getMapsPath(); strcpy( buffer, pn ); strcat( buffer, "/ac_prt.map" ); - FILE* pFile = fopen(buffer, "w"); + FILE* pFile = fopen( buffer, "w" ); // ahem, thx rr2 - if(!pFile) + if ( !pFile ) { return; + } - Scene_forEachEntity(EntityWriteMiniPrt(pFile, exclusionList)); + Scene_forEachEntity( EntityWriteMiniPrt( pFile, exclusionList ) ); - fclose(pFile); + fclose( pFile ); StartBSP(); } class EntityFindByTargetName { - const char* targetname; +const char* targetname; public: - mutable const scene::Path* result; - EntityFindByTargetName(const char* targetname) - : targetname(targetname), result(0) - { - } - void operator()(scene::Instance& instance) const - { - if(result == 0) - { - const char* value = Node_getEntity(instance.path().top())->getKeyValue("targetname"); - - if(!strcmp(value, targetname)) - { - result = &instance.path(); - } - } - } +mutable const scene::Path* result; +EntityFindByTargetName( const char* targetname ) + : targetname( targetname ), result( 0 ){ +} +void operator()( scene::Instance& instance ) const { + if ( result == 0 ) { + const char* value = Node_getEntity( instance.path().top() )->getKeyValue( "targetname" ); + + if ( !strcmp( value, targetname ) ) { + result = &instance.path(); + } + } +} }; - -const scene::Path* FindEntityFromTargetname(const char* targetname) -{ - return Scene_forEachEntity(EntityFindByTargetName(targetname)).result; + +const scene::Path* FindEntityFromTargetname( const char* targetname ){ + return Scene_forEachEntity( EntityFindByTargetName( targetname ) ).result; } -void FillDefaultTexture(_QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture) -{ +void FillDefaultTexture( _QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture ){ faceData->m_texdef.rotate = 0; faceData->m_texdef.scale[0] = 0.5; faceData->m_texdef.scale[1] = 0.5; @@ -355,52 +339,52 @@ void FillDefaultTexture(_QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, faceData->contents = 0; faceData->flags = 0; faceData->value = 0; - if(*texture) + if ( *texture ) { faceData->m_shader = texture; - else + } + else{ faceData->m_shader = "textures/common/caulk"; - VectorCopy(va, faceData->m_p0); - VectorCopy(vb, faceData->m_p1); - VectorCopy(vc, faceData->m_p2); + } + VectorCopy( va, faceData->m_p0 ); + VectorCopy( vb, faceData->m_p1 ); + VectorCopy( vc, faceData->m_p2 ); } -float Determinant3x3(float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3) -{ - return a1*(b2*c3-b3*c2) - a2*(b1*c3-b3*c1) + a3*(b1*c2-b2*c1); +float Determinant3x3( float a1, float a2, float a3, + float b1, float b2, float b3, + float c1, float c2, float c3 ){ + return a1 * ( b2 * c3 - b3 * c2 ) - a2 * ( b1 * c3 - b3 * c1 ) + a3 * ( b1 * c2 - b2 * c1 ); } -bool GetEntityCentre(const char* entity, vec3_t centre) -{ - const scene::Path* ent = FindEntityFromTargetname(entity); - if(!ent) +bool GetEntityCentre( const char* entity, vec3_t centre ){ + const scene::Path* ent = FindEntityFromTargetname( entity ); + if ( !ent ) { return false; + } - scene::Instance& instance = *GlobalSceneGraph().find(*ent); - VectorCopy(instance.worldAABB().origin, centre); + scene::Instance& instance = *GlobalSceneGraph().find( *ent ); + VectorCopy( instance.worldAABB().origin, centre ); return true; } -vec_t Min(vec_t a, vec_t b) -{ - if(a < b) +vec_t Min( vec_t a, vec_t b ){ + if ( a < b ) { return a; + } return b; } void MakeNormal( const vec_t* va, const vec_t* vb, const vec_t* vc, vec_t* out ) { vec3_t v1, v2; - VectorSubtract(va, vb, v1); - VectorSubtract(vc, vb, v2); - CrossProduct(v1, v2, out); + VectorSubtract( va, vb, v1 ); + VectorSubtract( vc, vb, v2 ); + CrossProduct( v1, v2, out ); } -char* GetFilename(char* buffer, const char* filename) { - strcpy(buffer, GlobalRadiant().getAppPath()); - strcat(buffer, "plugins/"); - strcat(buffer, filename); +char* GetFilename( char* buffer, const char* filename ) { + strcpy( buffer, GlobalRadiant().getAppPath() ); + strcat( buffer, "plugins/" ); + strcat( buffer, filename ); return buffer; } - diff --git a/contrib/bobtoolz/misc.h b/contrib/bobtoolz/misc.h index 61faee5d..02ca174b 100644 --- a/contrib/bobtoolz/misc.h +++ b/contrib/bobtoolz/misc.h @@ -1,23 +1,23 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_MISC_H) +#if !defined( INCLUDED_MISC_H ) #define INCLUDED_MISC_H #include "mathlib.h" @@ -25,33 +25,33 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "str.h" #include "iscenegraph.h" -#define MAX_ROUND_ERROR 0.05 +#define MAX_ROUND_ERROR 0.05 -vec_t Min(vec_t a, vec_t b); +vec_t Min( vec_t a, vec_t b ); // reads current texture into global, returns pointer to it const char* GetCurrentTexture(); class _QERFaceData; -void FillDefaultTexture(_QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture); +void FillDefaultTexture( _QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture ); -void BuildMiniPrt(std::list* exclusionList); +void BuildMiniPrt( std::list* exclusionList ); -void MoveBlock(int dir, vec3_t min, vec3_t max, float dist); -void SetInitialStairPos(int dir, vec3_t min, vec3_t max, float width); +void MoveBlock( int dir, vec3_t min, vec3_t max, float dist ); +void SetInitialStairPos( int dir, vec3_t min, vec3_t max, float width ); -const scene::Path* FindEntityFromTargetname(const char* targetname); +const scene::Path* FindEntityFromTargetname( const char* targetname ); -char* UnixToDosPath(char* path); +char* UnixToDosPath( char* path ); -char* GetFilename(char* buffer, const char* filename); -char* GetGameFilename(char* buffer, const char* filename); +char* GetFilename( char* buffer, const char* filename ); +char* GetGameFilename( char* buffer, const char* filename ); -float Determinant3x3(float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3); +float Determinant3x3( float a1, float a2, float a3, + float b1, float b2, float b3, + float c1, float c2, float c3 ); -bool GetEntityCentre(const char* entity, vec3_t centre); +bool GetEntityCentre( const char* entity, vec3_t centre ); void MakeNormal( const vec_t* va, const vec_t* vb, const vec_t* vc, vec_t* out ); #endif diff --git a/contrib/bobtoolz/resource-gtk.h b/contrib/bobtoolz/resource-gtk.h index 9297877f..93528395 100644 --- a/contrib/bobtoolz/resource-gtk.h +++ b/contrib/bobtoolz/resource-gtk.h @@ -4,7 +4,7 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 diff --git a/contrib/bobtoolz/resource.h b/contrib/bobtoolz/resource.h index 2c7f97ed..7689553f 100644 --- a/contrib/bobtoolz/resource.h +++ b/contrib/bobtoolz/resource.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. @@ -104,7 +104,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define IDC_DUPLICATEONLY_CHECK 1050 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 diff --git a/contrib/bobtoolz/shapes.cpp b/contrib/bobtoolz/shapes.cpp index e38dd495..f466c515 100644 --- a/contrib/bobtoolz/shapes.cpp +++ b/contrib/bobtoolz/shapes.cpp @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "shapes.h" @@ -48,121 +48,115 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //#include "dialogs-gtk.h" /************************ - Cube Diagram + Cube Diagram ************************/ /* - 7 ----- 5 - /| /| - / | / | - / | / | - 4 ----- 6 | - | 2|_|___|8 - | / | / - | / | / ----> WEST, definitely - |/ | / - 1|_____|/3 + 7 ----- 5 + /| /| + / | / | + / | / | + 4 ----- 6 | + | 2|_|___|8 + | / | / + | / | / ----> WEST, definitely + ||/ | / + 1|_____|/3 -*/ + */ /************************ - Global Variables + Global Variables ************************/ -vec3_t g_Origin = {0.0f, 0.0f, 0.0f}; +vec3_t g_Origin = {0.0f, 0.0f, 0.0f}; extern bool bFacesAll[]; /************************ - Helper Functions + Helper Functions ************************/ -float Deg2Rad(float angle) -{ - return (float)(angle*Q_PI/180); +float Deg2Rad( float angle ){ + return (float)( angle * Q_PI / 180 ); } -void AddFaceWithTexture(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail) -{ +void AddFaceWithTexture( scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail ){ _QERFaceData faceData; - FillDefaultTexture(&faceData, va, vb, vc, texture); - if(detail) + FillDefaultTexture( &faceData, va, vb, vc, texture ); + if ( detail ) { faceData.contents |= FACE_DETAIL; - GlobalBrushCreator().Brush_addFace(brush, faceData); + } + GlobalBrushCreator().Brush_addFace( brush, faceData ); } -void AddFaceWithTextureScaled(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, - const char* texture, bool bVertScale, bool bHorScale, - float minX, float minY, float maxX, float maxY) -{ +void AddFaceWithTextureScaled( scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, + const char* texture, bool bVertScale, bool bHorScale, + float minX, float minY, float maxX, float maxY ){ qtexture_t* pqtTexInfo; - // TTimo: there used to be a call to pfnHasShader here - // this was not necessary. In Radiant everything is shader. - // If a texture doesn't have a shader script, a default shader object is used. - // The IShader object was leaking also + // TTimo: there used to be a call to pfnHasShader here + // this was not necessary. In Radiant everything is shader. + // If a texture doesn't have a shader script, a default shader object is used. + // The IShader object was leaking also // collect texture info: sizes, etc - IShader* i = GlobalShaderSystem().getShaderForName(texture); - pqtTexInfo = i->getTexture(); // shader width/height doesn't come out properly + IShader* i = GlobalShaderSystem().getShaderForName( texture ); + pqtTexInfo = i->getTexture(); // shader width/height doesn't come out properly - if(pqtTexInfo) - { + if ( pqtTexInfo ) { float scale[2] = {0.5f, 0.5f}; float shift[2] = {0, 0}; - if(bHorScale) - { + if ( bHorScale ) { float width = maxX - minX; - scale[0] = width/pqtTexInfo->width; - shift[0] = -(float)((int)maxX%(int)width)/scale[0]; + scale[0] = width / pqtTexInfo->width; + shift[0] = -(float)( (int)maxX % (int)width ) / scale[0]; } - if(bVertScale) - { + if ( bVertScale ) { float height = maxY - minY; - scale[1] = height/pqtTexInfo->height; - shift[1] = (float)((int)minY%(int)height)/scale[1]; + scale[1] = height / pqtTexInfo->height; + shift[1] = (float)( (int)minY % (int)height ) / scale[1]; } _QERFaceData addFace; - FillDefaultTexture(&addFace, va, vb, vc, texture); + FillDefaultTexture( &addFace, va, vb, vc, texture ); addFace.m_texdef.scale[0] = scale[0]; addFace.m_texdef.scale[1] = scale[1]; addFace.m_texdef.shift[0] = shift[0]; addFace.m_texdef.shift[1] = shift[1]; - GlobalBrushCreator().Brush_addFace(brush, addFace); + GlobalBrushCreator().Brush_addFace( brush, addFace ); } else { // shouldn't even get here, as default missing texture should be returned if // texture doesn't exist, but just in case - AddFaceWithTexture(brush, va, vb, vc, texture, false); + AddFaceWithTexture( brush, va, vb, vc, texture, false ); globalErrorStream() << "BobToolz::Invalid Texture Name-> " << texture; } - // the IShader is not kept referenced, DecRef it - i->DecRef(); + // the IShader is not kept referenced, DecRef it + i->DecRef(); } /************************ - --Main Functions-- + --Main Functions-- ************************/ -void Build_Wedge(int dir, vec3_t min, vec3_t max, bool bUp) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); +void Build_Wedge( int dir, vec3_t min, vec3_t max, bool bUp ){ + NodeSmartReference newBrush( GlobalBrushCreator().createBrush() ); vec3_t v1, v2, v3, v5, v6, v7, v8; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - VectorCopy(max, v8); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); + VectorCopy( max, v8 ); v2[0] = max[0]; v3[1] = max[1]; @@ -171,85 +165,99 @@ void Build_Wedge(int dir, vec3_t min, vec3_t max, bool bUp) v7[1] = min[1]; v8[2] = min[2]; - if(bUp) - { + if ( bUp ) { - if(dir != MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); + if ( dir != MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v3, v6, "textures/common/caulk", false ); + } - if(dir != MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v8, "textures/common/caulk", false); + if ( dir != MOVE_WEST ) { + AddFaceWithTexture( newBrush, v7, v5, v8, "textures/common/caulk", false ); + } - if(dir != MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); + if ( dir != MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v7, v2, "textures/common/caulk", false ); + } - if(dir != MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v8, v6, "textures/common/caulk", false); + if ( dir != MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v3, v8, v6, "textures/common/caulk", false ); + } - AddFaceWithTexture(newBrush, v1, v2, v3, "textures/common/caulk", false); + AddFaceWithTexture( newBrush, v1, v2, v3, "textures/common/caulk", false ); - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v5, "textures/common/caulk", false); + if ( dir == MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v3, v5, "textures/common/caulk", false ); + } - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v2, v6, v8, "textures/common/caulk", false); + if ( dir == MOVE_WEST ) { + AddFaceWithTexture( newBrush, v2, v6, v8, "textures/common/caulk", false ); + } - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v6, v5, "textures/common/caulk", false); + if ( dir == MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v6, v5, "textures/common/caulk", false ); + } - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v3, v8, "textures/common/caulk", false); + if ( dir == MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v7, v3, v8, "textures/common/caulk", false ); + } } else { - if(dir != MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v8, "textures/common/caulk", false); + if ( dir != MOVE_WEST ) { + AddFaceWithTexture( newBrush, v7, v5, v8, "textures/common/caulk", false ); + } - if(dir != MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); + if ( dir != MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v3, v6, "textures/common/caulk", false ); + } - if(dir != MOVE_NORTH) - AddFaceWithTexture(newBrush, v3, v8, v6, "textures/common/caulk", false); + if ( dir != MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v3, v8, v6, "textures/common/caulk", false ); + } + + if ( dir != MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v1, v7, v2, "textures/common/caulk", false ); + } - if(dir != MOVE_SOUTH) - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); - - AddFaceWithTexture(newBrush, v6, v5, v7, "textures/common/caulk", false); + AddFaceWithTexture( newBrush, v6, v5, v7, "textures/common/caulk", false ); - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v1, v5, v3, "textures/common/caulk", false); + if ( dir == MOVE_WEST ) { + AddFaceWithTexture( newBrush, v1, v5, v3, "textures/common/caulk", false ); + } - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v2, v8, v6, "textures/common/caulk", false); + if ( dir == MOVE_EAST ) { + AddFaceWithTexture( newBrush, v2, v8, v6, "textures/common/caulk", false ); + } - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v5, v6, "textures/common/caulk", false); + if ( dir == MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v5, v6, "textures/common/caulk", false ); + } - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v8, v3, "textures/common/caulk", false); + if ( dir == MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v7, v8, v3, "textures/common/caulk", false ); + } } - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( newBrush ); } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- -void Build_StairStep_Wedge(int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); +void Build_StairStep_Wedge( int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail ){ + NodeSmartReference newBrush( GlobalBrushCreator().createBrush() ); //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7, v8; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - VectorCopy(max, v8); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); + VectorCopy( max, v8 ); v2[0] = max[0]; v3[1] = max[1]; @@ -262,73 +270,80 @@ void Build_StairStep_Wedge(int dir, vec3_t min, vec3_t max, const char* mainText //---------------------------------- - AddFaceWithTexture(newBrush, v6, v5, v7, mainTexture, detail); + AddFaceWithTexture( newBrush, v6, v5, v7, mainTexture, detail ); - if(dir != MOVE_EAST) - { - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v5, v2, v7, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v5, v2, v7, "textures/common/caulk", detail); + if ( dir != MOVE_EAST ) { + if ( dir == MOVE_WEST ) { + AddFaceWithTexture( newBrush, v5, v2, v7, riserTexture, detail ); + } + else{ + AddFaceWithTexture( newBrush, v5, v2, v7, "textures/common/caulk", detail ); + } } - if(dir != MOVE_WEST) - { - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", detail); + if ( dir != MOVE_WEST ) { + if ( dir == MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v3, v6, riserTexture, detail ); + } + else{ + AddFaceWithTexture( newBrush, v1, v3, v6, "textures/common/caulk", detail ); + } } - if(dir != MOVE_NORTH) - { - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v5, v6, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v3, v5, v6, "textures/common/caulk", detail); + if ( dir != MOVE_NORTH ) { + if ( dir == MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v3, v5, v6, riserTexture, detail ); + } + else{ + AddFaceWithTexture( newBrush, v3, v5, v6, "textures/common/caulk", detail ); + } } - if(dir != MOVE_SOUTH) - { - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", detail); + if ( dir != MOVE_SOUTH ) { + if ( dir == MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v7, v2, riserTexture, detail ); + } + else{ + AddFaceWithTexture( newBrush, v1, v7, v2, "textures/common/caulk", detail ); + } } - - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v5, v3, "textures/common/caulk", detail); - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v2, v8, v6, "textures/common/caulk", detail); + if ( dir == MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v5, v3, "textures/common/caulk", detail ); + } + + if ( dir == MOVE_WEST ) { + AddFaceWithTexture( newBrush, v2, v8, v6, "textures/common/caulk", detail ); + } - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v5, v6, "textures/common/caulk", detail); + if ( dir == MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v5, v6, "textures/common/caulk", detail ); + } - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v8, v3, "textures/common/caulk", detail); + if ( dir == MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v7, v8, v3, "textures/common/caulk", detail ); + } - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( newBrush ); } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- // internal use only, to get a box without finishing construction -scene::Node& Build_Get_BoundingCube_Selective(vec3_t min, vec3_t max, char* texture, bool* useFaces) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); +scene::Node& Build_Get_BoundingCube_Selective( vec3_t min, vec3_t max, char* texture, bool* useFaces ){ + NodeSmartReference newBrush( GlobalBrushCreator().createBrush() ); //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); v2[0] = max[0]; v3[1] = max[1]; @@ -340,46 +355,50 @@ scene::Node& Build_Get_BoundingCube_Selective(vec3_t min, vec3_t max, char* text //----- Add Six Cube Faces --------- - if(useFaces[0]) - AddFaceWithTexture(newBrush, v1, v2, v3, texture, false); - if(useFaces[1]) - AddFaceWithTexture(newBrush, v1, v3, v6, texture, false); - if(useFaces[2]) - AddFaceWithTexture(newBrush, v1, v7, v2, texture, false); + if ( useFaces[0] ) { + AddFaceWithTexture( newBrush, v1, v2, v3, texture, false ); + } + if ( useFaces[1] ) { + AddFaceWithTexture( newBrush, v1, v3, v6, texture, false ); + } + if ( useFaces[2] ) { + AddFaceWithTexture( newBrush, v1, v7, v2, texture, false ); + } - if(useFaces[3]) - AddFaceWithTexture(newBrush, v5, v6, v3, texture, false); - if(useFaces[4]) - AddFaceWithTexture(newBrush, v5, v2, v7, texture, false); - if(useFaces[5]) - AddFaceWithTexture(newBrush, v5, v7, v6, texture, false); + if ( useFaces[3] ) { + AddFaceWithTexture( newBrush, v5, v6, v3, texture, false ); + } + if ( useFaces[4] ) { + AddFaceWithTexture( newBrush, v5, v2, v7, texture, false ); + } + if ( useFaces[5] ) { + AddFaceWithTexture( newBrush, v5, v7, v6, texture, false ); + } //---------------------------------- return newBrush; } -scene::Node& Build_Get_BoundingCube(vec3_t min, vec3_t max, char* texture) -{ - return Build_Get_BoundingCube_Selective(min, max, texture, bFacesAll); +scene::Node& Build_Get_BoundingCube( vec3_t min, vec3_t max, char* texture ){ + return Build_Get_BoundingCube_Selective( min, max, texture, bFacesAll ); } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- -void Build_StairStep(vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); +void Build_StairStep( vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction ){ + NodeSmartReference newBrush( GlobalBrushCreator().createBrush() ); //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); v2[0] = max[0]; v3[1] = max[1]; @@ -389,64 +408,73 @@ void Build_StairStep(vec3_t min, vec3_t max, const char* mainTexture, const char //---------------------------------- - AddFaceWithTexture(newBrush, v6, v5, v7, mainTexture, false); + AddFaceWithTexture( newBrush, v6, v5, v7, mainTexture, false ); // top gets current texture - if(direction == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, riserTexture, false); - else - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); + if ( direction == MOVE_EAST ) { + AddFaceWithTexture( newBrush, v1, v3, v6, riserTexture, false ); + } + else{ + AddFaceWithTexture( newBrush, v1, v3, v6, "textures/common/caulk", false ); + } // west facing side, etc... - - if(direction == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, riserTexture, false); - else - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); - if(direction == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v5, v6, riserTexture, false); - else - AddFaceWithTexture(newBrush, v3, v5, v6, "textures/common/caulk", false); - - if(direction == MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v2, riserTexture, false); - else - AddFaceWithTexture(newBrush, v7, v5, v2, "textures/common/caulk", false); + if ( direction == MOVE_NORTH ) { + AddFaceWithTexture( newBrush, v1, v7, v2, riserTexture, false ); + } + else{ + AddFaceWithTexture( newBrush, v1, v7, v2, "textures/common/caulk", false ); + } + + if ( direction == MOVE_SOUTH ) { + AddFaceWithTexture( newBrush, v3, v5, v6, riserTexture, false ); + } + else{ + AddFaceWithTexture( newBrush, v3, v5, v6, "textures/common/caulk", false ); + } + + if ( direction == MOVE_WEST ) { + AddFaceWithTexture( newBrush, v7, v5, v2, riserTexture, false ); + } + else{ + AddFaceWithTexture( newBrush, v7, v5, v2, "textures/common/caulk", false ); + } - AddFaceWithTexture(newBrush, v1, v2, v3, "textures/common/caulk", false); + AddFaceWithTexture( newBrush, v1, v2, v3, "textures/common/caulk", false ); // base is caulked - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( newBrush ); // finish brush } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- -void BuildDoorsX2(vec3_t min, vec3_t max, - bool bSclMainHor, bool bSclMainVert, - bool bSclTrimHor, bool bSclTrimVert, - const char* mainTexture, const char* trimTexture, - int direction) -{ +void BuildDoorsX2( vec3_t min, vec3_t max, + bool bSclMainHor, bool bSclMainVert, + bool bSclTrimHor, bool bSclTrimVert, + const char* mainTexture, const char* trimTexture, + int direction ){ int xy; - if(direction == 0) + if ( direction == 0 ) { xy = 0; - else + } + else{ xy = 1; + } //----- Build Outer Bounds --------- vec3_t v1, v2, v3, v5, v6, v7, ve_1, ve_2, ve_3; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); + VectorCopy( min, v1 ); + VectorCopy( min, v2 ); + VectorCopy( min, v3 ); + VectorCopy( max, v5 ); + VectorCopy( max, v6 ); + VectorCopy( max, v7 ); v2[0] = max[0]; v3[1] = max[1]; @@ -454,19 +482,18 @@ void BuildDoorsX2(vec3_t min, vec3_t max, v6[0] = min[0]; v7[1] = min[1]; - float width = (max[xy] - min[xy])/2; - - if(direction == 0) - { - VectorCopy(v1, ve_1); - VectorCopy(v3, ve_2); - VectorCopy(v6, ve_3); + float width = ( max[xy] - min[xy] ) / 2; + + if ( direction == 0 ) { + VectorCopy( v1, ve_1 ); + VectorCopy( v3, ve_2 ); + VectorCopy( v6, ve_3 ); } else { - VectorCopy(v7, ve_1); - VectorCopy(v1, ve_2); - VectorCopy(v2, ve_3); + VectorCopy( v7, ve_1 ); + VectorCopy( v1, ve_2 ); + VectorCopy( v2, ve_3 ); } ve_1[xy] += width; @@ -475,98 +502,95 @@ void BuildDoorsX2(vec3_t min, vec3_t max, //---------------------------------- - NodeSmartReference newBrush1(GlobalBrushCreator().createBrush()); - NodeSmartReference newBrush2(GlobalBrushCreator().createBrush()); + NodeSmartReference newBrush1( GlobalBrushCreator().createBrush() ); + NodeSmartReference newBrush2( GlobalBrushCreator().createBrush() ); - AddFaceWithTexture(newBrush1, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(newBrush1, v5, v7, v6, "textures/common/caulk", false); + AddFaceWithTexture( newBrush1, v1, v2, v3, "textures/common/caulk", false ); + AddFaceWithTexture( newBrush1, v5, v7, v6, "textures/common/caulk", false ); - AddFaceWithTexture(newBrush2, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v7, v6, "textures/common/caulk", false); + AddFaceWithTexture( newBrush2, v1, v2, v3, "textures/common/caulk", false ); + AddFaceWithTexture( newBrush2, v5, v7, v6, "textures/common/caulk", false ); - if(direction == 0) - { - AddFaceWithTexture(newBrush1, v1, v3, v6, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v2, v7, "textures/common/caulk", false); + if ( direction == 0 ) { + AddFaceWithTexture( newBrush1, v1, v3, v6, "textures/common/caulk", false ); + AddFaceWithTexture( newBrush2, v5, v2, v7, "textures/common/caulk", false ); } else { - AddFaceWithTexture(newBrush1, v1, v7, v2, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v6, v3, "textures/common/caulk", false); + AddFaceWithTexture( newBrush1, v1, v7, v2, "textures/common/caulk", false ); + AddFaceWithTexture( newBrush2, v5, v6, v3, "textures/common/caulk", false ); } - if(direction == 0) - { - AddFaceWithTextureScaled(newBrush1, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2]); - AddFaceWithTextureScaled(newBrush1, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2]); + if ( direction == 0 ) { + AddFaceWithTextureScaled( newBrush1, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, + min[0], min[2], max[0], max[2] ); + AddFaceWithTextureScaled( newBrush1, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, + max[0], min[2], min[0], max[2] ); + - - AddFaceWithTextureScaled(newBrush2, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2]); - AddFaceWithTextureScaled(newBrush2, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2]); // flip max/min to reverse tex dir + AddFaceWithTextureScaled( newBrush2, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, + min[0], min[2], max[0], max[2] ); + AddFaceWithTextureScaled( newBrush2, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, + max[0], min[2], min[0], max[2] ); // flip max/min to reverse tex dir - - AddFaceWithTextureScaled(newBrush1, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - min[1], min[2], max[1], max[2]); - AddFaceWithTextureScaled(newBrush2, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - max[1], min[2], min[1], max[2]); + AddFaceWithTextureScaled( newBrush1, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, + min[1], min[2], max[1], max[2] ); + + AddFaceWithTextureScaled( newBrush2, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, + max[1], min[2], min[1], max[2] ); } else { - AddFaceWithTextureScaled(newBrush1, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2]); - AddFaceWithTextureScaled(newBrush1, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2]); + AddFaceWithTextureScaled( newBrush1, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, + min[1], min[2], max[1], max[2] ); + AddFaceWithTextureScaled( newBrush1, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, + max[1], min[2], min[1], max[2] ); + - - AddFaceWithTextureScaled(newBrush2, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2]); - AddFaceWithTextureScaled(newBrush2, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2]); // flip max/min to reverse tex dir + AddFaceWithTextureScaled( newBrush2, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, + min[1], min[2], max[1], max[2] ); + AddFaceWithTextureScaled( newBrush2, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, + max[1], min[2], min[1], max[2] ); // flip max/min to reverse tex dir - AddFaceWithTextureScaled(newBrush1, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - min[0], min[2], max[0], max[2]); + AddFaceWithTextureScaled( newBrush1, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, + min[0], min[2], max[0], max[2] ); - AddFaceWithTextureScaled(newBrush2, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - max[0], min[2], min[0], max[2]); + AddFaceWithTextureScaled( newBrush2, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, + max[0], min[2], min[0], max[2] ); } //---------------------------------- - - EntityClass* doorClass = GlobalEntityClassManager().findOrInsert("func_door", true); - NodeSmartReference pEDoor1(GlobalEntityCreator().createEntity(doorClass)); - NodeSmartReference pEDoor2(GlobalEntityCreator().createEntity(doorClass)); - if(direction == 0) - { - Node_getEntity(pEDoor1)->setKeyValue("angle", "180"); - Node_getEntity(pEDoor2)->setKeyValue("angle", "360"); + EntityClass* doorClass = GlobalEntityClassManager().findOrInsert( "func_door", true ); + NodeSmartReference pEDoor1( GlobalEntityCreator().createEntity( doorClass ) ); + NodeSmartReference pEDoor2( GlobalEntityCreator().createEntity( doorClass ) ); + + if ( direction == 0 ) { + Node_getEntity( pEDoor1 )->setKeyValue( "angle", "180" ); + Node_getEntity( pEDoor2 )->setKeyValue( "angle", "360" ); } else { - Node_getEntity(pEDoor1)->setKeyValue("angle", "270"); - Node_getEntity(pEDoor2)->setKeyValue("angle", "90"); + Node_getEntity( pEDoor1 )->setKeyValue( "angle", "270" ); + Node_getEntity( pEDoor2 )->setKeyValue( "angle", "90" ); } - srand((unsigned)time(NULL)); + srand( (unsigned)time( NULL ) ); char teamname[256]; - sprintf(teamname, "t%i", rand()); - Node_getEntity(pEDoor1)->setKeyValue("team", teamname); - Node_getEntity(pEDoor2)->setKeyValue("team", teamname); + sprintf( teamname, "t%i", rand() ); + Node_getEntity( pEDoor1 )->setKeyValue( "team", teamname ); + Node_getEntity( pEDoor2 )->setKeyValue( "team", teamname ); - Node_getTraversable(pEDoor1)->insert(newBrush1); - Node_getTraversable(pEDoor2)->insert(newBrush2); + Node_getTraversable( pEDoor1 )->insert( newBrush1 ); + Node_getTraversable( pEDoor2 )->insert( newBrush2 ); - Node_getTraversable(GlobalSceneGraph().root())->insert(pEDoor1); - Node_getTraversable(GlobalSceneGraph().root())->insert(pEDoor2); + Node_getTraversable( GlobalSceneGraph().root() )->insert( pEDoor1 ); + Node_getTraversable( GlobalSceneGraph().root() )->insert( pEDoor2 ); // ResetCurrentTexture(); } @@ -574,71 +598,69 @@ void BuildDoorsX2(vec3_t min, vec3_t max, //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- -void MakeBevel(vec3_t vMin, vec3_t vMax) -{ - NodeSmartReference patch(GlobalPatchCreator().createPatch()); - GlobalPatchCreator().Patch_resize(patch, 3, 3); - GlobalPatchCreator().Patch_setShader(patch, "textures/common/caulk"); - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch); +void MakeBevel( vec3_t vMin, vec3_t vMax ){ + NodeSmartReference patch( GlobalPatchCreator().createPatch() ); + GlobalPatchCreator().Patch_resize( patch, 3, 3 ); + GlobalPatchCreator().Patch_setShader( patch, "textures/common/caulk" ); + PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints( patch ); vec3_t x_3, y_3, z_3; - x_3[0] = vMin[0]; x_3[1] = vMin[0]; x_3[2] = vMax[0]; - y_3[0] = vMin[1]; y_3[1] = vMax[1]; y_3[2] = vMax[1]; - z_3[0] = vMin[2]; z_3[1] = (vMax[2] + vMin[2])/2; z_3[2] = vMax[2]; + x_3[0] = vMin[0]; x_3[1] = vMin[0]; x_3[2] = vMax[0]; + y_3[0] = vMin[1]; y_3[1] = vMax[1]; y_3[2] = vMax[1]; + z_3[0] = vMin[2]; z_3[1] = ( vMax[2] + vMin[2] ) / 2; z_3[2] = vMax[2]; /* - x_3[0] = 0; x_3[1] = 0; x_3[2] = 64; - y_3[0] = 0; y_3[1] = 64; y_3[2] = 64; - z_3[0] = 0; z_3[1] = 32; z_3[2] = 64;*/ - for(int i = 0; i < 3; i++) + x_3[0] = 0; x_3[1] = 0; x_3[2] = 64; + y_3[0] = 0; y_3[1] = 64; y_3[2] = 64; + z_3[0] = 0; z_3[1] = 32; z_3[2] = 64;*/ + for ( int i = 0; i < 3; i++ ) { - for(int j = 0; j < 3; j++) + for ( int j = 0; j < 3; j++ ) { - PatchControl& p = matrix(i, j); + PatchControl& p = matrix( i, j ); p.m_vertex[0] = x_3[i]; p.m_vertex[1] = y_3[i]; p.m_vertex[2] = z_3[j]; } } //does invert the matrix, else the patch face is on wrong side. - for(int i = 0 ; i < 3 ; i++ ) + for ( int i = 0 ; i < 3 ; i++ ) { - for(int j = 0; j < 1; j++) + for ( int j = 0; j < 1; j++ ) { - PatchControl& p = matrix(i,2- j); - PatchControl& q = matrix(i, j); - std::swap(p.m_vertex, q.m_vertex); + PatchControl& p = matrix( i,2 - j ); + PatchControl& q = matrix( i, j ); + std::swap( p.m_vertex, q.m_vertex ); //std::swap(p.m_texcoord, q.m_texcoord); } } - GlobalPatchCreator().Patch_controlPointsChanged(patch); - //TODO - the patch has textures weird, patchmanip.h has all function it needs.. lots of duplicate code.. + GlobalPatchCreator().Patch_controlPointsChanged( patch ); + //TODO - the patch has textures weird, patchmanip.h has all function it needs.. lots of duplicate code.. //NaturalTexture(patch); - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(patch); + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( patch ); } -void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex) -{ - vec3_t* topPoints = new vec3_t[nSteps+1]; - vec3_t* botPoints = new vec3_t[nSteps+1]; +void BuildCornerStairs( vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex ){ + vec3_t* topPoints = new vec3_t[nSteps + 1]; + vec3_t* botPoints = new vec3_t[nSteps + 1]; //bool bFacesUse[6] = {true, true, false, true, false, false}; vec3_t centre; - VectorCopy(vMin, centre); + VectorCopy( vMin, centre ); centre[0] = vMax[0]; - int height = (int)(vMax[2] - vMin[2]) / nSteps; + int height = (int)( vMax[2] - vMin[2] ) / nSteps; vec3_t vTop, vBot; - VectorCopy(vMax, vTop); - VectorCopy(vMin, vBot); + VectorCopy( vMax, vTop ); + VectorCopy( vMin, vBot ); vTop[2] = vMin[2] + height; - int i; - for(i = 0; i <= nSteps; i++) + int i; + for ( i = 0; i <= nSteps; i++ ) { - VectorCopy(centre, topPoints[i]); - VectorCopy(centre, botPoints[i]); - + VectorCopy( centre, topPoints[i] ); + VectorCopy( centre, botPoints[i] ); + topPoints[i][2] = vMax[2]; botPoints[i][2] = vMin[2]; @@ -650,39 +672,39 @@ void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTex } vec3_t tp[3]; - for(int j = 0; j < 3; j++) - VectorCopy(topPoints[j], tp[j]); + for ( int j = 0; j < 3; j++ ) + VectorCopy( topPoints[j], tp[j] ); - for(i = 0; i < nSteps; i++) + for ( i = 0; i < nSteps; i++ ) { - NodeSmartReference brush(GlobalBrushCreator().createBrush()); + NodeSmartReference brush( GlobalBrushCreator().createBrush() ); vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(vBot, v1); - VectorCopy(vBot, v2); - VectorCopy(vBot, v3); - VectorCopy(vTop, v5); - VectorCopy(vTop, v6); - VectorCopy(vTop, v7); - + VectorCopy( vBot, v1 ); + VectorCopy( vBot, v2 ); + VectorCopy( vBot, v3 ); + VectorCopy( vTop, v5 ); + VectorCopy( vTop, v6 ); + VectorCopy( vTop, v7 ); + v2[0] = vTop[0]; v3[1] = vTop[1]; - + v6[0] = vBot[0]; v7[1] = vBot[1]; - - AddFaceWithTexture(brush, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(brush, v1, v3, v6, "textures/common/caulk", false); - AddFaceWithTexture(brush, v5, v6, v3, "textures/common/caulk", false); - - for(int j = 0; j < 3; j++) + + AddFaceWithTexture( brush, v1, v2, v3, "textures/common/caulk", false ); + AddFaceWithTexture( brush, v1, v3, v6, "textures/common/caulk", false ); + AddFaceWithTexture( brush, v5, v6, v3, "textures/common/caulk", false ); + + for ( int j = 0; j < 3; j++ ) tp[j][2] = vTop[2]; - AddFaceWithTexture(brush, tp[2], tp[1], tp[0], mainTexture, false); + AddFaceWithTexture( brush, tp[2], tp[1], tp[0], mainTexture, false ); - AddFaceWithTexture(brush, centre, botPoints[i+1], topPoints[i+1], "textures/common/caulk", false); - AddFaceWithTexture(brush, centre, topPoints[i], botPoints[i], riserTex, false); + AddFaceWithTexture( brush, centre, botPoints[i + 1], topPoints[i + 1], "textures/common/caulk", false ); + AddFaceWithTexture( brush, centre, topPoints[i], botPoints[i], riserTex, false ); - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(brush); + Node_getTraversable( GlobalRadiant().getMapWorldEntity() )->insert( brush ); vTop[2] += height; vBot[2] += height; @@ -693,5 +715,5 @@ void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTex vMin[2] += height; vMax[2] += height; - MakeBevel(vMin, vMax); + MakeBevel( vMin, vMax ); } diff --git a/contrib/bobtoolz/shapes.h b/contrib/bobtoolz/shapes.h index 0fa92659..c35809e7 100644 --- a/contrib/bobtoolz/shapes.h +++ b/contrib/bobtoolz/shapes.h @@ -1,21 +1,21 @@ /* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans + BobToolz plugin for GtkRadiant + Copyright (C) 2001 Gordon Biggans -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // TODO: implement all this stuff via DBrush class. started with DShape // TODO: Auto Face Scaling, no need to pass parms, calculated via brush. @@ -24,30 +24,30 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define FACE_DETAIL 0x8000000 // defines for polygon stuff -#define MAX_POLYGON_FACES 128 +#define MAX_POLYGON_FACES 128 namespace scene { - class Node; +class Node; } #include "mathlib.h" // generic (detail added 12/01/01, for AC+) -void AddFaceWithTexture(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail); +void AddFaceWithTexture( scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail ); // ------------- // ---caulked--- // ------------- -void Build_Wedge(int dir, vec3_t min, vec3_t max, bool bUp); +void Build_Wedge( int dir, vec3_t min, vec3_t max, bool bUp ); // -------------- // ---textured--- // -------------- -void BuildDoorsX2(vec3_t min, vec3_t max, bool bSclMainHor, bool bSclMainVert, bool bSclTrimHor, bool bSclTrimVert, const char* mainTexture, const char* trimTexture, int direction); -void Build_StairStep(vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction); -void Build_StairStep_Wedge(int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail); -void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex); +void BuildDoorsX2( vec3_t min, vec3_t max, bool bSclMainHor, bool bSclMainVert, bool bSclTrimHor, bool bSclTrimVert, const char* mainTexture, const char* trimTexture, int direction ); +void Build_StairStep( vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction ); +void Build_StairStep_Wedge( int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail ); +void BuildCornerStairs( vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex ); // stairs stuff. //void Build_Prism_Border(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop = FALSE); //moved to DShape diff --git a/contrib/bobtoolz/visfind.cpp b/contrib/bobtoolz/visfind.cpp index e5b890b1..629c1633 100644 --- a/contrib/bobtoolz/visfind.cpp +++ b/contrib/bobtoolz/visfind.cpp @@ -10,11 +10,11 @@ #include typedef struct { - int portalclusters; - int leafbytes; //leafbytes = ((portalclusters+63)&~63)>>3; + int portalclusters; + int leafbytes; //leafbytes = ((portalclusters+63)&~63)>>3; } vis_header; -// added because int shift = 32; i = 0xFFFFFFFF >> shift; +// added because int shift = 32; i = 0xFFFFFFFF >> shift; // then i = 0xFFFFFFFF, when it should = 0 const unsigned long bitmasks[33] = { @@ -29,150 +29,156 @@ const unsigned long bitmasks[33] = 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF }; -int bsp_leafnumfororigin(vec3_t origin) -{ - dnode_t *node; - dplane_t *plane; - float d; +int bsp_leafnumfororigin( vec3_t origin ){ + dnode_t *node; + dplane_t *plane; + float d; // TODO: check if origin is in the map?? node = dnodes; - while (true) + while ( true ) { plane = &dplanes[node->planeNum]; - d = DotProduct (origin, plane->normal) - plane->dist; - if ( d >= 0 ) - if ( node->children[0] < 0 ) - return -(node->children[0]+1); - else + d = DotProduct( origin, plane->normal ) - plane->dist; + if ( d >= 0 ) { + if ( node->children[0] < 0 ) { + return -( node->children[0] + 1 ); + } + else{ node = &dnodes[node->children[0]]; + } + } else - if ( node->children[1] < 0 ) - return -(node->children[1]+1); - else - node = &dnodes[node->children[1]]; + if ( node->children[1] < 0 ) { + return -( node->children[1] + 1 ); + } + else{ + node = &dnodes[node->children[1]]; + } } return 0; } -int bsp_leafnumforcluster(int cluster) -{ +int bsp_leafnumforcluster( int cluster ){ dleaf_t *l; int i; for ( i = 0, l = dleafs; i < numleafs; i++, l++ ) - if ( l->cluster == cluster ) return(i); - return(0); + if ( l->cluster == cluster ) { + return( i ); + } + return( 0 ); } // leaf1 = origin leaf // leaf2 = leaf to test for /*int bsp_InPVS(int cluster1, int cluster2) -{ - vis_header *vheader; - byte *visdata; + { + vis_header *vheader; + byte *visdata; - vheader = (vis_header *) visBytes; - visdata = visBytes + VIS_HEADER_SIZE; + vheader = (vis_header *) visBytes; + visdata = visBytes + VIS_HEADER_SIZE; - return( *( visdata + ( cluster1 * vheader->leafbytes ) + (cluster2 / 8) ) & ( 1 << ( cluster2 % 8 ) ) ); -}*/ + return( *( visdata + ( cluster1 * vheader->leafbytes ) + (cluster2 / 8) ) & ( 1 << ( cluster2 % 8 ) ) ); + }*/ -void bsp_setbitvectorlength( byte *v, int length_bits, int length_vector ) -{ +void bsp_setbitvectorlength( byte *v, int length_bits, int length_vector ){ int i; - i = length_bits/8; + i = length_bits / 8; - *(v+i) = (byte) bitmasks[length_bits % 8]; + *( v + i ) = (byte) bitmasks[length_bits % 8]; - memset((v+i+1), 0, length_vector-i-1); + memset( ( v + i + 1 ), 0, length_vector - i - 1 ); } -void bsp_bitvectorsubtract(byte *first, byte *second, byte *out, int length) -{ +void bsp_bitvectorsubtract( byte *first, byte *second, byte *out, int length ){ int i; for ( i = 0; i < length; i++ ) - *(out+i) = *(first+i) & ~(*(second+i)); + *( out + i ) = *( first + i ) & ~( *( second + i ) ); } -int bsp_countclusters(byte *bitvector, int length) -{ +int bsp_countclusters( byte *bitvector, int length ){ int i, j, c; c = 0; for ( i = 0; i < length; i++ ) for ( j = 0; j < 8; j++ ) - if ( (*(bitvector+i) & (1 << j)) ) c++; - return(c); + if ( ( *( bitvector + i ) & ( 1 << j ) ) ) { + c++; + } + return( c ); } -int bsp_countclusters_mask(byte *bitvector, byte *maskvector, int length) -{ +int bsp_countclusters_mask( byte *bitvector, byte *maskvector, int length ){ int i, j, c; c = 0; for ( i = 0; i < length; i++ ) for ( j = 0; j < 8; j++ ) - if ( (*(bitvector+i) & (1 << j)) && (*(maskvector+i) & (1 << j)) ) c++; - return(c); + if ( ( *( bitvector + i ) & ( 1 << j ) ) && ( *( maskvector + i ) & ( 1 << j ) ) ) { + c++; + } + return( c ); } -void AddCluster(std::list *pointlist, dleaf_t *cl, bool* repeatlist, vec3_t clr) -{ - DWinding* w; - +void AddCluster( std::list *pointlist, dleaf_t *cl, bool* repeatlist, vec3_t clr ){ + DWinding* w; + int* leafsurf = &dleafsurfaces[cl->firstLeafSurface]; - for(int k = 0; k < cl->numLeafSurfaces; k++, leafsurf++) + for ( int k = 0; k < cl->numLeafSurfaces; k++, leafsurf++ ) { - if(repeatlist[*leafsurf]) + if ( repeatlist[*leafsurf] ) { continue; + } dsurface_t* surf = &drawSurfaces[*leafsurf]; - if(surf->surfaceType != MST_PLANAR) + if ( surf->surfaceType != MST_PLANAR ) { continue; + } qdrawVert_t* vert = &drawVerts[surf->firstVert]; - if(surf->firstVert + surf->numVerts > numDrawVerts) - DoMessageBox("Warning", "Warning", eMB_OK); + if ( surf->firstVert + surf->numVerts > numDrawVerts ) { + DoMessageBox( "Warning", "Warning", eMB_OK ); + } w = new DWinding(); - w->AllocWinding(surf->numVerts); + w->AllocWinding( surf->numVerts ); - for (int l = 0; l < surf->numVerts; l++, vert++) + for ( int l = 0; l < surf->numVerts; l++, vert++ ) { - (w->p[l])[0] = vert->xyz[0]; - (w->p[l])[1] = vert->xyz[1]; - (w->p[l])[2] = vert->xyz[2]; + ( w->p[l] )[0] = vert->xyz[0]; + ( w->p[l] )[1] = vert->xyz[1]; + ( w->p[l] )[2] = vert->xyz[2]; - w->clr[0] = clr[0]; - w->clr[1] = clr[1]; - w->clr[2] = clr[2]; + w->clr[0] = clr[0]; + w->clr[1] = clr[1]; + w->clr[2] = clr[2]; } - pointlist->push_back(w); + pointlist->push_back( w ); repeatlist[*leafsurf] = true; } } /* -============= -CreateTrace -============= -*/ -std::list *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byte *visdata, byte *seen ) -{ - byte *vis; - int i, j, clusterNum; + ============= + CreateTrace + ============= + */ +std::list *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byte *visdata, byte *seen ){ + byte *vis; + int i, j, clusterNum; std::list *pointlist = new std::list; - bool* repeatlist = new bool[numDrawSurfaces]; - dleaf_t *cl; + bool* repeatlist = new bool[numDrawSurfaces]; + dleaf_t *cl; - vec3_t clrRnd[5] = { + vec3_t clrRnd[5] = { {0.f, 0.f, 1.f}, {0.f, 1.f, 1.f}, {1.f, 0.f, 0.f}, @@ -180,24 +186,25 @@ std::list *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byt {1.f, 1.f, 0.f}, }; - vec3_t clrGreen = {0.f, 1.f, 0.f}; - - memset(repeatlist, 0, sizeof(bool)*numDrawSurfaces); - + vec3_t clrGreen = {0.f, 1.f, 0.f}; + + memset( repeatlist, 0, sizeof( bool ) * numDrawSurfaces ); + vis = visdata + ( c * header->leafbytes ); clusterNum = 0; - AddCluster(pointlist, &(dleafs[bsp_leafnumforcluster( c )]), repeatlist, clrGreen); + AddCluster( pointlist, &( dleafs[bsp_leafnumforcluster( c )] ), repeatlist, clrGreen ); for ( i = 0; i < header->leafbytes; i++ ) { for ( j = 0; j < 8; j++ ) { - cl = &(dleafs[bsp_leafnumforcluster( clusterNum )]); + cl = &( dleafs[bsp_leafnumforcluster( clusterNum )] ); - if ( ( *(vis + i) & (1 << j) ) && (*(seen+i) & (1 << j)) && (leaf->area == cl->area)) - AddCluster(pointlist, cl, repeatlist, clrRnd[rand()%5]); + if ( ( *( vis + i ) & ( 1 << j ) ) && ( *( seen + i ) & ( 1 << j ) ) && ( leaf->area == cl->area ) ) { + AddCluster( pointlist, cl, repeatlist, clrRnd[rand() % 5] ); + } clusterNum++; } } @@ -208,38 +215,37 @@ std::list *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byt } /* -============= -TraceCluster - -setup for CreateTrace -============= -*/ -std::list *TraceCluster (int leafnum) -{ - byte seen[(MAX_MAP_LEAFS/8) + 1]; - vis_header *vheader; - byte *visdata; - dleaf_t *leaf; + ============= + TraceCluster + + setup for CreateTrace + ============= + */ +std::list *TraceCluster( int leafnum ){ + byte seen[( MAX_MAP_LEAFS / 8 ) + 1]; + vis_header *vheader; + byte *visdata; + dleaf_t *leaf; vheader = (vis_header *) visBytes; - visdata = visBytes + sizeof(vis_header); + visdata = visBytes + sizeof( vis_header ); - memset(seen, 0xFF, sizeof(seen)); - bsp_setbitvectorlength(seen, vheader->portalclusters, sizeof(seen)); + memset( seen, 0xFF, sizeof( seen ) ); + bsp_setbitvectorlength( seen, vheader->portalclusters, sizeof( seen ) ); - leaf = &(dleafs[leafnum]); + leaf = &( dleafs[leafnum] ); - return CreateTrace(leaf, leaf->cluster, vheader, visdata, seen); + return CreateTrace( leaf, leaf->cluster, vheader, visdata, seen ); } -std::list* BuildTrace(char* filename, vec3_t v_origin) -{ - if(!LoadBSPFile(filename)) +std::list* BuildTrace( char* filename, vec3_t v_origin ){ + if ( !LoadBSPFile( filename ) ) { return NULL; - - int leafnum = bsp_leafnumfororigin(v_origin); + } + + int leafnum = bsp_leafnumfororigin( v_origin ); - std::list *pointlist = TraceCluster(leafnum); + std::list *pointlist = TraceCluster( leafnum ); FreeBSPData(); diff --git a/contrib/bobtoolz/visfind.h b/contrib/bobtoolz/visfind.h index 3476d864..54b3660d 100644 --- a/contrib/bobtoolz/visfind.h +++ b/contrib/bobtoolz/visfind.h @@ -4,4 +4,4 @@ class DWinding; -std::list *BuildTrace(char* filename, vec3_t v_origin); +std::list *BuildTrace( char* filename, vec3_t v_origin ); diff --git a/contrib/brushexport/callbacks.cpp b/contrib/brushexport/callbacks.cpp index 0aea73da..6a346f3a 100644 --- a/contrib/brushexport/callbacks.cpp +++ b/contrib/brushexport/callbacks.cpp @@ -13,136 +13,137 @@ void DestroyWindow(); namespace callbacks { -void OnDestroy(GtkWidget* w, gpointer data) -{ +void OnDestroy( GtkWidget* w, gpointer data ){ DestroyWindow(); } -void OnExportClicked(GtkButton* button, gpointer user_data) -{ - GtkWidget* window = lookup_widget(GTK_WIDGET(button), "w_plugplug2"); - ASSERT_NOTNULL(window); - const char* cpath = GlobalRadiant().m_pfnFileDialog(window, false, "Save as Obj", 0, 0, false, false, true); - if(!cpath) +void OnExportClicked( GtkButton* button, gpointer user_data ){ + GtkWidget* window = lookup_widget( GTK_WIDGET( button ), "w_plugplug2" ); + ASSERT_NOTNULL( window ); + const char* cpath = GlobalRadiant().m_pfnFileDialog( window, false, "Save as Obj", 0, 0, false, false, true ); + if ( !cpath ) { return; + } + + std::string path( cpath ); + + // get ignore list from ui + std::set ignore; + + GtkTreeView* view = GTK_TREE_VIEW( lookup_widget( GTK_WIDGET( button ), "t_materialist" ) ); + GtkListStore* list = GTK_LIST_STORE( gtk_tree_view_get_model( view ) ); + + GtkTreeIter iter; + gboolean valid = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( list ), &iter ); + while ( valid ) + { + gchar* data; + gtk_tree_model_get( GTK_TREE_MODEL( list ), &iter, 0, &data, -1 ); + globalOutputStream() << data << "\n"; + ignore.insert( std::string( data ) ); + g_free( data ); + valid = gtk_tree_model_iter_next( GTK_TREE_MODEL( list ), &iter ); + } + + for ( std::set::iterator it( ignore.begin() ); it != ignore.end(); ++it ) + globalOutputStream() << it->c_str() << "\n"; + + // collapse mode + collapsemode mode = COLLAPSE_NONE; + + GtkWidget* radio = lookup_widget( GTK_WIDGET( button ), "r_collapse" ); + ASSERT_NOTNULL( radio ); - std::string path(cpath); - - // get ignore list from ui - std::set ignore; - - GtkTreeView* view = GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")); - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(view)); - - GtkTreeIter iter; - gboolean valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(list), &iter); - while(valid) - { - gchar* data; - gtk_tree_model_get(GTK_TREE_MODEL(list), &iter, 0, &data, -1); - globalOutputStream() << data << "\n"; - ignore.insert(std::string(data)); - g_free(data); - valid = gtk_tree_model_iter_next (GTK_TREE_MODEL(list), &iter); - } - - for(std::set::iterator it(ignore.begin()); it != ignore.end(); ++it) - globalOutputStream() << it->c_str() << "\n"; - - // collapse mode - collapsemode mode = COLLAPSE_NONE; - - GtkWidget* radio = lookup_widget(GTK_WIDGET(button), "r_collapse"); - ASSERT_NOTNULL(radio); - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))) - mode = COLLAPSE_ALL; - else - { - radio = lookup_widget(GTK_WIDGET(button), "r_collapsebymaterial"); - ASSERT_NOTNULL(radio); - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))) - mode = COLLAPSE_BY_MATERIAL; + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio ) ) ) { + mode = COLLAPSE_ALL; + } else { - radio = lookup_widget(GTK_WIDGET(button), "r_nocollapse"); - ASSERT_NOTNULL(radio); - ASSERT_NOTNULL(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))); - mode = COLLAPSE_NONE; + radio = lookup_widget( GTK_WIDGET( button ), "r_collapsebymaterial" ); + ASSERT_NOTNULL( radio ); + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio ) ) ) { + mode = COLLAPSE_BY_MATERIAL; + } + else + { + radio = lookup_widget( GTK_WIDGET( button ), "r_nocollapse" ); + ASSERT_NOTNULL( radio ); + ASSERT_NOTNULL( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio ) ) ); + mode = COLLAPSE_NONE; + } } - } - // export materials? - GtkWidget* toggle = lookup_widget(GTK_WIDGET(button), "t_exportmaterials"); - ASSERT_NOTNULL(toggle); + // export materials? + GtkWidget* toggle = lookup_widget( GTK_WIDGET( button ), "t_exportmaterials" ); + ASSERT_NOTNULL( toggle ); + + bool exportmat = FALSE; - bool exportmat = FALSE; + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( toggle ) ) ) { + exportmat = TRUE; + } - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle))) - exportmat = TRUE; + // limit material names? + toggle = lookup_widget( GTK_WIDGET( button ), "t_limitmatnames" ); + ASSERT_NOTNULL( toggle ); - // limit material names? - toggle = lookup_widget(GTK_WIDGET(button), "t_limitmatnames"); - ASSERT_NOTNULL(toggle); + bool limitMatNames = FALSE; - bool limitMatNames = FALSE; + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( toggle ) ) && exportmat ) { + limitMatNames = TRUE; + } - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)) && exportmat) - limitMatNames = TRUE; + // create objects instead of groups? + toggle = lookup_widget( GTK_WIDGET( button ), "t_objects" ); + ASSERT_NOTNULL( toggle ); - // create objects instead of groups? - toggle = lookup_widget(GTK_WIDGET(button), "t_objects"); - ASSERT_NOTNULL(toggle); + bool objects = FALSE; - bool objects = FALSE; + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( toggle ) ) && exportmat ) { + objects = TRUE; + } - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)) && exportmat) - objects = TRUE; - - // export - ExportSelection(ignore, mode, exportmat, path, limitMatNames, objects); + // export + ExportSelection( ignore, mode, exportmat, path, limitMatNames, objects ); } -void OnAddMaterial(GtkButton* button, gpointer user_data) -{ - GtkEntry* edit = GTK_ENTRY(lookup_widget(GTK_WIDGET(button), "ed_materialname")); - ASSERT_NOTNULL(edit); - - const gchar* name = gtk_entry_get_text(edit); - if(g_utf8_strlen(name, -1) > 0) - { - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")))); - GtkTreeIter iter; - gtk_list_store_append(list, &iter); - gtk_list_store_set(list, &iter, 0, name, -1); - gtk_entry_set_text(edit, ""); - } +void OnAddMaterial( GtkButton* button, gpointer user_data ){ + GtkEntry* edit = GTK_ENTRY( lookup_widget( GTK_WIDGET( button ), "ed_materialname" ) ); + ASSERT_NOTNULL( edit ); + + const gchar* name = gtk_entry_get_text( edit ); + if ( g_utf8_strlen( name, -1 ) > 0 ) { + GtkListStore* list = GTK_LIST_STORE( gtk_tree_view_get_model( GTK_TREE_VIEW( lookup_widget( GTK_WIDGET( button ), "t_materialist" ) ) ) ); + GtkTreeIter iter; + gtk_list_store_append( list, &iter ); + gtk_list_store_set( list, &iter, 0, name, -1 ); + gtk_entry_set_text( edit, "" ); + } } -void OnRemoveMaterial(GtkButton* button, gpointer user_data) -{ - GtkTreeView* view = GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")); - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(view)); - GtkTreeSelection* sel = gtk_tree_view_get_selection(view); - +void OnRemoveMaterial( GtkButton* button, gpointer user_data ){ + GtkTreeView* view = GTK_TREE_VIEW( lookup_widget( GTK_WIDGET( button ), "t_materialist" ) ); + GtkListStore* list = GTK_LIST_STORE( gtk_tree_view_get_model( view ) ); + GtkTreeSelection* sel = gtk_tree_view_get_selection( view ); + GtkTreeIter iter; - if(gtk_tree_selection_get_selected(sel, 0, &iter)) - gtk_list_store_remove(list, &iter); + if ( gtk_tree_selection_get_selected( sel, 0, &iter ) ) { + gtk_list_store_remove( list, &iter ); + } } -void OnExportMatClicked(GtkButton* button, gpointer user_data) -{ - GtkWidget* toggleLimit = lookup_widget(GTK_WIDGET(button), "t_limitmatnames"); - GtkWidget* toggleObject = lookup_widget(GTK_WIDGET(button), "t_objects"); +void OnExportMatClicked( GtkButton* button, gpointer user_data ){ + GtkWidget* toggleLimit = lookup_widget( GTK_WIDGET( button ), "t_limitmatnames" ); + GtkWidget* toggleObject = lookup_widget( GTK_WIDGET( button ), "t_objects" ); - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) - { - gtk_widget_set_sensitive(GTK_WIDGET(toggleLimit), TRUE); - gtk_widget_set_sensitive(GTK_WIDGET(toggleObject), TRUE); - } else { - gtk_widget_set_sensitive(GTK_WIDGET(toggleLimit), FALSE); - gtk_widget_set_sensitive(GTK_WIDGET(toggleObject), FALSE); + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( button ) ) ) { + gtk_widget_set_sensitive( GTK_WIDGET( toggleLimit ), TRUE ); + gtk_widget_set_sensitive( GTK_WIDGET( toggleObject ), TRUE ); + } + else { + gtk_widget_set_sensitive( GTK_WIDGET( toggleLimit ), FALSE ); + gtk_widget_set_sensitive( GTK_WIDGET( toggleObject ), FALSE ); } } -}// callbacks +} // callbacks diff --git a/contrib/brushexport/callbacks.h b/contrib/brushexport/callbacks.h index 9bf95684..eea5aa8b 100644 --- a/contrib/brushexport/callbacks.h +++ b/contrib/brushexport/callbacks.h @@ -3,10 +3,10 @@ typedef struct _GtkButton GtkButton; namespace callbacks { -void OnDestroy(GtkWidget*, gpointer); -void OnExportClicked(GtkButton*, gpointer); -void OnAddMaterial(GtkButton*, gpointer); -void OnRemoveMaterial(GtkButton*, gpointer); -void OnExportMatClicked(GtkButton* button, gpointer); +void OnDestroy( GtkWidget *, gpointer ); +void OnExportClicked( GtkButton *, gpointer ); +void OnAddMaterial( GtkButton *, gpointer ); +void OnRemoveMaterial( GtkButton *, gpointer ); +void OnExportMatClicked( GtkButton * button, gpointer ); -}// callbacks +} // callbacks diff --git a/contrib/brushexport/export.cpp b/contrib/brushexport/export.cpp index bd71b993..4a1e2d4c 100644 --- a/contrib/brushexport/export.cpp +++ b/contrib/brushexport/export.cpp @@ -15,141 +15,133 @@ #define MAX_MATERIAL_NAME 20 /* - Abstract baseclass for modelexporters - the class collects all the data which then gets - exported through the WriteToFile method. -*/ + Abstract baseclass for modelexporters + the class collects all the data which then gets + exported through the WriteToFile method. + */ class ExportData { public: - ExportData(const std::set& ignorelist, collapsemode mode, bool limNames, bool objs); - virtual ~ExportData(void); - - virtual void BeginBrush(Brush& b); - virtual void AddBrushFace(Face& f); - virtual void EndBrush(void); - - virtual bool WriteToFile(const std::string& path, collapsemode mode) const = 0; - +ExportData( const std::set& ignorelist, collapsemode mode, bool limNames, bool objs ); +virtual ~ExportData( void ); + +virtual void BeginBrush( Brush& b ); +virtual void AddBrushFace( Face& f ); +virtual void EndBrush( void ); + +virtual bool WriteToFile( const std::string& path, collapsemode mode ) const = 0; + protected: - // a group of faces - class group - { - public: - std::string name; - std::list faces; - }; - - std::list groups; - +// a group of faces +class group +{ +public: +std::string name; +std::list faces; +}; + +std::list groups; + private: - // "textures/common/caulk" -> "caulk" - void GetShaderNameFromShaderPath(const char* path, std::string& name); +// "textures/common/caulk" -> "caulk" +void GetShaderNameFromShaderPath( const char* path, std::string& name ); - group* current; - collapsemode mode; - const std::set& ignorelist; +group* current; +collapsemode mode; +const std::set& ignorelist; }; -ExportData::ExportData(const std::set& _ignorelist, collapsemode _mode, bool _limNames, bool _objs) - : mode(_mode), - ignorelist(_ignorelist) -{ +ExportData::ExportData( const std::set& _ignorelist, collapsemode _mode, bool _limNames, bool _objs ) + : mode( _mode ), + ignorelist( _ignorelist ){ current = 0; - + // in this mode, we need just one group - if(mode == COLLAPSE_ALL) - { - groups.push_back(group()); + if ( mode == COLLAPSE_ALL ) { + groups.push_back( group() ); current = &groups.back(); current->name = "all"; } } -ExportData::~ExportData(void) -{ - +ExportData::~ExportData( void ){ + } -void ExportData::BeginBrush(Brush& b) -{ +void ExportData::BeginBrush( Brush& b ){ // create a new group for each brush - if(mode == COLLAPSE_NONE) - { - groups.push_back(group()); + if ( mode == COLLAPSE_NONE ) { + groups.push_back( group() ); current = &groups.back(); - - StringOutputStream str(256); + + StringOutputStream str( 256 ); str << "Brush" << (const unsigned int)groups.size(); current->name = str.c_str(); } } -void ExportData::EndBrush(void) -{ +void ExportData::EndBrush( void ){ // all faces of this brush were on the ignorelist, discard the emptygroup - if(mode == COLLAPSE_NONE) - { - ASSERT_NOTNULL(current); - if(current->faces.empty()) - { + if ( mode == COLLAPSE_NONE ) { + ASSERT_NOTNULL( current ); + if ( current->faces.empty() ) { groups.pop_back(); current = 0; } } } -void ExportData::AddBrushFace(Face& f) -{ +void ExportData::AddBrushFace( Face& f ){ std::string shadername; - GetShaderNameFromShaderPath(f.GetShader(), shadername); - + GetShaderNameFromShaderPath( f.GetShader(), shadername ); + // ignore faces from ignore list - if(ignorelist.find(shadername) != ignorelist.end()) + if ( ignorelist.find( shadername ) != ignorelist.end() ) { return; - - if(mode == COLLAPSE_BY_MATERIAL) - { + } + + if ( mode == COLLAPSE_BY_MATERIAL ) { // find a group for this material current = 0; - const std::list::iterator end(groups.end()); - for(std::list::iterator it(groups.begin()); it != end; ++it) + const std::list::iterator end( groups.end() ); + for ( std::list::iterator it( groups.begin() ); it != end; ++it ) { - if(it->name == shadername) - current = &(*it); + if ( it->name == shadername ) { + current = &( *it ); + } } - + // no group found, create one - if(!current) - { - groups.push_back(group()); + if ( !current ) { + groups.push_back( group() ); current = &groups.back(); current->name = shadername; } } - - ASSERT_NOTNULL(current); - + + ASSERT_NOTNULL( current ); + // add face to current group - current->faces.push_back(&f); - + current->faces.push_back( &f ); + #ifdef _DEBUG globalOutputStream() << "Added Face to group " << current->name.c_str() << "\n"; #endif } -void ExportData::GetShaderNameFromShaderPath(const char* path, std::string& name) -{ - std::string tmp(path); +void ExportData::GetShaderNameFromShaderPath( const char* path, std::string& name ){ + std::string tmp( path ); + + size_t last_slash = tmp.find_last_of( "/" ); - size_t last_slash = tmp.find_last_of("/"); - - if(last_slash != std::string::npos && last_slash == (tmp.length() - 1)) + if ( last_slash != std::string::npos && last_slash == ( tmp.length() - 1 ) ) { name = path; - else - name = tmp.substr(last_slash + 1, tmp.length() - last_slash); + } + else{ + name = tmp.substr( last_slash + 1, tmp.length() - last_slash ); + } #ifdef _DEBUG globalOutputStream() << "Last: " << (const unsigned int) last_slash << " " << "length: " << (const unsigned int)tmp.length() << "Name: " << name.c_str() << "\n"; @@ -157,139 +149,133 @@ void ExportData::GetShaderNameFromShaderPath(const char* path, std::string& name } /* - Exporter writing facedata as wavefront object -*/ + Exporter writing facedata as wavefront object + */ class ExportDataAsWavefront : public ExportData { private: - bool expmat; - bool limNames; - bool objs; +bool expmat; +bool limNames; +bool objs; public: - ExportDataAsWavefront(const std::set& _ignorelist, collapsemode _mode, bool _expmat, bool _limNames, bool _objs) - : ExportData(_ignorelist, _mode, _limNames, _objs) - { - expmat = _expmat; - limNames = _limNames; - objs = _objs; - } - - bool WriteToFile(const std::string& path, collapsemode mode) const; +ExportDataAsWavefront( const std::set& _ignorelist, collapsemode _mode, bool _expmat, bool _limNames, bool _objs ) + : ExportData( _ignorelist, _mode, _limNames, _objs ){ + expmat = _expmat; + limNames = _limNames; + objs = _objs; +} + +bool WriteToFile( const std::string& path, collapsemode mode ) const; }; -bool ExportDataAsWavefront::WriteToFile(const std::string& path, collapsemode mode) const -{ +bool ExportDataAsWavefront::WriteToFile( const std::string& path, collapsemode mode ) const { std::string objFile = path; - if(path.compare(path.length() - 4, 4, ".obj") != 0) + if ( path.compare( path.length() - 4, 4, ".obj" ) != 0 ) { objFile += ".obj"; + } - std::string mtlFile = objFile.substr(0, objFile.length() -4) + ".mtl"; + std::string mtlFile = objFile.substr( 0, objFile.length() - 4 ) + ".mtl"; std::set materials; - TextFileOutputStream out(objFile.c_str()); - - if(out.failed()) - { + TextFileOutputStream out( objFile.c_str() ); + + if ( out.failed() ) { globalErrorStream() << "Unable to open file\n"; return false; } - + out << "# Wavefront Objectfile exported with radiants brushexport plugin 3.0 by Thomas 'namespace' Nitschke, spam@codecreator.net\n\n"; - if(expmat) - { - size_t last = mtlFile.find_last_of("//"); - std::string mtllib = mtlFile.substr(last + 1, mtlFile.size() - last).c_str(); + if ( expmat ) { + size_t last = mtlFile.find_last_of( "//" ); + std::string mtllib = mtlFile.substr( last + 1, mtlFile.size() - last ).c_str(); out << "mtllib " << mtllib.c_str() << "\n"; } - + unsigned int vertex_count = 0; - const std::list::const_iterator gend(groups.end()); - for(std::list::const_iterator git(groups.begin()); git != gend; ++git) + const std::list::const_iterator gend( groups.end() ); + for ( std::list::const_iterator git( groups.begin() ); git != gend; ++git ) { typedef std::multimap bm; bm brushMaterials; typedef std::pair String_Pair; - const std::list::const_iterator end(git->faces.end()); - + const std::list::const_iterator end( git->faces.end() ); + // submesh starts here - if(objs) - { + if ( objs ) { out << "\no "; - } else { + } + else { out << "\ng "; } out << git->name.c_str() << "\n"; // material - if(expmat && mode == COLLAPSE_ALL) - { + if ( expmat && mode == COLLAPSE_ALL ) { out << "usemtl material" << "\n\n"; - materials.insert("material"); + materials.insert( "material" ); } - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) + for ( std::list::const_iterator it( git->faces.begin() ); it != end; ++it ) { - const Winding& w((*it)->getWinding()); - + const Winding& w( ( *it )->getWinding() ); + // vertices - for(size_t i = 0; i < w.numpoints; ++i) - out << "v " << FloatFormat(w[i].vertex.x(), 1, 6) << " " << FloatFormat(w[i].vertex.z(), 1, 6) << " " << FloatFormat(w[i].vertex.y(), 1, 6) << "\n"; + for ( size_t i = 0; i < w.numpoints; ++i ) + out << "v " << FloatFormat( w[i].vertex.x(), 1, 6 ) << " " << FloatFormat( w[i].vertex.z(), 1, 6 ) << " " << FloatFormat( w[i].vertex.y(), 1, 6 ) << "\n"; } - out << "\n"; - - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) + out << "\n"; + + for ( std::list::const_iterator it( git->faces.begin() ); it != end; ++it ) { - const Winding& w((*it)->getWinding()); - + const Winding& w( ( *it )->getWinding() ); + // texcoords - for(size_t i = 0; i < w.numpoints; ++i) - out << "vt " << FloatFormat(w[i].texcoord.x(), 1, 6) << " " << FloatFormat(w[i].texcoord.y(), 1, 6) << "\n"; + for ( size_t i = 0; i < w.numpoints; ++i ) + out << "vt " << FloatFormat( w[i].texcoord.x(), 1, 6 ) << " " << FloatFormat( w[i].texcoord.y(), 1, 6 ) << "\n"; } - - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) + + for ( std::list::const_iterator it( git->faces.begin() ); it != end; ++it ) { - const Winding& w((*it)->getWinding()); - + const Winding& w( ( *it )->getWinding() ); + // faces - StringOutputStream faceLine(256); + StringOutputStream faceLine( 256 ); faceLine << "\nf"; - for(size_t i = 0; i < w.numpoints; ++i, ++vertex_count) + for ( size_t i = 0; i < w.numpoints; ++i, ++vertex_count ) { - faceLine << " " << vertex_count+1 << "/" << vertex_count+1; + faceLine << " " << vertex_count + 1 << "/" << vertex_count + 1; } - if(mode != COLLAPSE_ALL) - { - materials.insert((*it)->getShader().getShader()); - brushMaterials.insert(String_Pair((*it)->getShader().getShader(), faceLine.c_str())); - } else { + if ( mode != COLLAPSE_ALL ) { + materials.insert( ( *it )->getShader().getShader() ); + brushMaterials.insert( String_Pair( ( *it )->getShader().getShader(), faceLine.c_str() ) ); + } + else { out << faceLine.c_str(); } } - if(mode != COLLAPSE_ALL) - { + if ( mode != COLLAPSE_ALL ) { std::string lastMat; std::string mat; std::string faces; - for(bm::iterator iter = brushMaterials.begin(); iter != brushMaterials.end(); iter++) + for ( bm::iterator iter = brushMaterials.begin(); iter != brushMaterials.end(); iter++ ) { - mat = (*iter).first.c_str(); - faces = (*iter).second.c_str(); - - if(mat != lastMat) - { - if(limNames && mat.size() > MAX_MATERIAL_NAME) - { - out << "\nusemtl " << mat.substr(mat.size() - MAX_MATERIAL_NAME, mat.size()).c_str(); - } else { + mat = ( *iter ).first.c_str(); + faces = ( *iter ).second.c_str(); + + if ( mat != lastMat ) { + if ( limNames && mat.size() > MAX_MATERIAL_NAME ) { + out << "\nusemtl " << mat.substr( mat.size() - MAX_MATERIAL_NAME, mat.size() ).c_str(); + } + else { out << "\nusemtl " << mat.c_str(); } } @@ -302,28 +288,26 @@ bool ExportDataAsWavefront::WriteToFile(const std::string& path, collapsemode mo out << "\n"; } - if(expmat) - { - TextFileOutputStream outMtl(mtlFile.c_str()); - if(outMtl.failed()) - { + if ( expmat ) { + TextFileOutputStream outMtl( mtlFile.c_str() ); + if ( outMtl.failed() ) { globalErrorStream() << "Unable to open material file\n"; return false; } outMtl << "# Wavefront material file exported with NetRadiants brushexport plugin.\n"; outMtl << "# Material Count: " << (const Unsigned)materials.size() << "\n\n"; - for(std::set::const_iterator it(materials.begin()); it != materials.end(); ++it) + for ( std::set::const_iterator it( materials.begin() ); it != materials.end(); ++it ) { - if(limNames && it->size() > MAX_MATERIAL_NAME) - { - outMtl << "newmtl " << it->substr(it->size() - MAX_MATERIAL_NAME, it->size()).c_str() << "\n"; - } else { + if ( limNames && it->size() > MAX_MATERIAL_NAME ) { + outMtl << "newmtl " << it->substr( it->size() - MAX_MATERIAL_NAME, it->size() ).c_str() << "\n"; + } + else { outMtl << "newmtl " << it->c_str() << "\n"; } } } - + return true; } @@ -331,50 +315,46 @@ bool ExportDataAsWavefront::WriteToFile(const std::string& path, collapsemode mo class ForEachFace : public BrushVisitor { public: - ForEachFace(ExportData& _exporter) - : exporter(_exporter) - {} - - void visit(Face& face) const - { - exporter.AddBrushFace(face); - } - +ForEachFace( ExportData& _exporter ) + : exporter( _exporter ) +{} + +void visit( Face& face ) const { + exporter.AddBrushFace( face ); +} + private: - ExportData& exporter; +ExportData& exporter; }; class ForEachSelected : public SelectionSystem::Visitor { public: - ForEachSelected(ExportData& _exporter) - : exporter(_exporter) - {} - - void visit(scene::Instance& instance) const - { - BrushInstance* bptr = InstanceTypeCast::cast(instance); - if(bptr) - { - Brush& brush(bptr->getBrush()); - - exporter.BeginBrush(brush); - ForEachFace face_vis(exporter); - brush.forEachFace(face_vis); - exporter.EndBrush(); - } - } - +ForEachSelected( ExportData& _exporter ) + : exporter( _exporter ) +{} + +void visit( scene::Instance& instance ) const { + BrushInstance* bptr = InstanceTypeCast::cast( instance ); + if ( bptr ) { + Brush& brush( bptr->getBrush() ); + + exporter.BeginBrush( brush ); + ForEachFace face_vis( exporter ); + brush.forEachFace( face_vis ); + exporter.EndBrush(); + } +} + private: - ExportData& exporter; +ExportData& exporter; }; - -bool ExportSelection(const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limNames, bool objs) -{ - ExportDataAsWavefront exporter(ignorelist, m, exmat, limNames, objs); - - ForEachSelected vis(exporter); - GlobalSelectionSystem().foreachSelected(vis); - - return exporter.WriteToFile(path, m); + +bool ExportSelection( const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limNames, bool objs ){ + ExportDataAsWavefront exporter( ignorelist, m, exmat, limNames, objs ); + + ForEachSelected vis( exporter ); + GlobalSelectionSystem().foreachSelected( vis ); + + return exporter.WriteToFile( path, m ); } diff --git a/contrib/brushexport/export.h b/contrib/brushexport/export.h index 3482bbed..40fa7c44 100644 --- a/contrib/brushexport/export.h +++ b/contrib/brushexport/export.h @@ -10,6 +10,6 @@ enum collapsemode COLLAPSE_NONE }; -bool ExportSelection(const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limitMatNames, bool objects); +bool ExportSelection( const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limitMatNames, bool objects ); -#endif +#endif diff --git a/contrib/brushexport/interface.cpp b/contrib/brushexport/interface.cpp index 6525e201..76279ab0 100644 --- a/contrib/brushexport/interface.cpp +++ b/contrib/brushexport/interface.cpp @@ -5,237 +5,233 @@ #include "callbacks.h" #include "support.h" -#define GLADE_HOOKUP_OBJECT(component,widget,name) \ - g_object_set_data_full (G_OBJECT (component), name, \ - gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref) +#define GLADE_HOOKUP_OBJECT( component,widget,name ) \ + g_object_set_data_full( G_OBJECT( component ), name, \ + gtk_widget_ref( widget ), (GDestroyNotify) gtk_widget_unref ) -#define GLADE_HOOKUP_OBJECT_NO_REF(component,widget,name) \ - g_object_set_data (G_OBJECT (component), name, widget) +#define GLADE_HOOKUP_OBJECT_NO_REF( component,widget,name ) \ + g_object_set_data( G_OBJECT( component ), name, widget ) // created by glade GtkWidget* -create_w_plugplug2 (void) -{ - GtkWidget *w_plugplug2; - GtkWidget *vbox1; - GtkWidget *hbox2; - GtkWidget *vbox4; - GtkWidget *r_collapse; - GSList *r_collapse_group = NULL; - GtkWidget *r_collapsebymaterial; - GtkWidget *r_nocollapse; - GtkWidget *vbox3; - GtkWidget *b_export; - GtkWidget *b_close; - GtkWidget *vbox2; - GtkWidget *label1; - GtkWidget *scrolledwindow1; - GtkWidget *t_materialist; - GtkWidget *ed_materialname; - GtkWidget *hbox1; - GtkWidget *b_addmaterial; - GtkWidget *b_removematerial; - GtkWidget *t_exportmaterials; - GtkWidget *t_limitmatnames; - GtkWidget *t_objects; - GtkTooltips *tooltips; - - tooltips = gtk_tooltips_new(); - - w_plugplug2 = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_widget_set_name (w_plugplug2, "w_plugplug2"); - gtk_window_set_title (GTK_WINDOW (w_plugplug2), "BrushExport-Plugin 3.0 by namespace"); - gtk_window_set_position (GTK_WINDOW (w_plugplug2), GTK_WIN_POS_CENTER); - gtk_window_set_destroy_with_parent (GTK_WINDOW (w_plugplug2), TRUE); - - vbox1 = gtk_vbox_new (FALSE, 0); - gtk_widget_set_name (vbox1, "vbox1"); - gtk_widget_show (vbox1); - gtk_container_add (GTK_CONTAINER (w_plugplug2), vbox1); - gtk_container_set_border_width (GTK_CONTAINER (vbox1), 5); - - hbox2 = gtk_hbox_new (TRUE, 5); - gtk_widget_set_name (hbox2, "hbox2"); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox1), hbox2, FALSE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (hbox2), 5); - - vbox4 = gtk_vbox_new (TRUE, 0); - gtk_widget_set_name (vbox4, "vbox4"); - gtk_widget_show (vbox4); - gtk_box_pack_start (GTK_BOX (hbox2), vbox4, TRUE, FALSE, 0); - - r_collapse = gtk_radio_button_new_with_mnemonic (NULL, "Collapse mesh"); - gtk_widget_set_name (r_collapse, "r_collapse"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_collapse, "Collapse all brushes into a single group", "Collapse all brushes into a single group"); - gtk_widget_show (r_collapse); - gtk_box_pack_start (GTK_BOX (vbox4), r_collapse, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_collapse), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_collapse)); - - r_collapsebymaterial = gtk_radio_button_new_with_mnemonic (NULL, "Collapse by material"); - gtk_widget_set_name (r_collapsebymaterial, "r_collapsebymaterial"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_collapsebymaterial, "Collapse into groups by material", "Collapse into groups by material"); - gtk_widget_show (r_collapsebymaterial); - gtk_box_pack_start (GTK_BOX (vbox4), r_collapsebymaterial, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_collapsebymaterial), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_collapsebymaterial)); - - r_nocollapse = gtk_radio_button_new_with_mnemonic (NULL, "Don't collapse"); - gtk_widget_set_name (r_nocollapse, "r_nocollapse"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_nocollapse, "Every brush is stored in its own group", "Every brush is stored in its own group"); - gtk_widget_show (r_nocollapse); - gtk_box_pack_start (GTK_BOX (vbox4), r_nocollapse, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_nocollapse), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_nocollapse)); - - vbox3 = gtk_vbox_new (FALSE, 0); - gtk_widget_set_name (vbox3, "vbox3"); - gtk_widget_show (vbox3); - gtk_box_pack_start (GTK_BOX (hbox2), vbox3, FALSE, FALSE, 0); - - b_export = gtk_button_new_from_stock ("gtk-save"); - gtk_widget_set_name (b_export, "b_export"); - gtk_widget_show (b_export); - gtk_box_pack_start (GTK_BOX (vbox3), b_export, TRUE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (b_export), 5); - - b_close = gtk_button_new_from_stock ("gtk-cancel"); - gtk_widget_set_name (b_close, "b_close"); - gtk_widget_show (b_close); - gtk_box_pack_start (GTK_BOX (vbox3), b_close, TRUE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (b_close), 5); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_set_name (vbox2, "vbox2"); - gtk_widget_show (vbox2); - gtk_box_pack_start (GTK_BOX (vbox1), vbox2, TRUE, TRUE, 0); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 2); - - label1 = gtk_label_new ("Ignored materials:"); - gtk_widget_set_name (label1, "label1"); - gtk_widget_show (label1); - gtk_box_pack_start (GTK_BOX (vbox2), label1, FALSE, FALSE, 0); - - scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL); - gtk_widget_set_name (scrolledwindow1, "scrolledwindow1"); - gtk_widget_show (scrolledwindow1); - gtk_box_pack_start (GTK_BOX (vbox2), scrolledwindow1, TRUE, TRUE, 0); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow1), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow1), GTK_SHADOW_IN); - - t_materialist = gtk_tree_view_new (); - gtk_widget_set_name (t_materialist, "t_materialist"); - gtk_widget_show (t_materialist); - gtk_container_add (GTK_CONTAINER (scrolledwindow1), t_materialist); - gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (t_materialist), FALSE); - gtk_tree_view_set_enable_search (GTK_TREE_VIEW (t_materialist), FALSE); - - ed_materialname = gtk_entry_new (); - gtk_widget_set_name (ed_materialname, "ed_materialname"); - gtk_widget_show (ed_materialname); - gtk_box_pack_start (GTK_BOX (vbox2), ed_materialname, FALSE, FALSE, 0); - - hbox1 = gtk_hbox_new (TRUE, 0); - gtk_widget_set_name (hbox1, "hbox1"); - gtk_widget_show (hbox1); - gtk_box_pack_start (GTK_BOX (vbox2), hbox1, FALSE, FALSE, 0); - - b_addmaterial = gtk_button_new_from_stock ("gtk-add"); - gtk_widget_set_name (b_addmaterial, "b_addmaterial"); - gtk_widget_show (b_addmaterial); - gtk_box_pack_start (GTK_BOX (hbox1), b_addmaterial, FALSE, FALSE, 0); - - b_removematerial = gtk_button_new_from_stock ("gtk-remove"); - gtk_widget_set_name (b_removematerial, "b_removematerial"); - gtk_widget_show (b_removematerial); - gtk_box_pack_start (GTK_BOX (hbox1), b_removematerial, FALSE, FALSE, 0); - - t_limitmatnames = gtk_check_button_new_with_mnemonic ("Use short material names (max. 20 chars)"); - gtk_widget_set_name (t_limitmatnames, "t_limitmatnames"); - gtk_widget_show (t_limitmatnames); - gtk_box_pack_end (GTK_BOX (vbox2), t_limitmatnames, FALSE, FALSE, 0); - - t_objects = gtk_check_button_new_with_mnemonic ("Create (o)bjects instead of (g)roups"); - gtk_widget_set_name (t_objects, "t_objects"); - gtk_widget_show (t_objects); - gtk_box_pack_end (GTK_BOX (vbox2), t_objects, FALSE, FALSE, 0); - - t_exportmaterials = gtk_check_button_new_with_mnemonic ("Create material information (.mtl file)"); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(t_exportmaterials), true); - gtk_widget_set_name (t_exportmaterials, "t_exportmaterials"); - gtk_widget_show (t_exportmaterials); - gtk_box_pack_end (GTK_BOX (vbox2), t_exportmaterials, FALSE, FALSE, 10); - - using namespace callbacks; - g_signal_connect(G_OBJECT(w_plugplug2), "destroy", G_CALLBACK(OnDestroy), NULL); - g_signal_connect_swapped(G_OBJECT(b_close), "clicked", G_CALLBACK (OnDestroy), NULL); - - g_signal_connect ((gpointer) b_export, "clicked", G_CALLBACK (OnExportClicked), NULL); - g_signal_connect ((gpointer) b_addmaterial, "clicked", G_CALLBACK (OnAddMaterial), NULL); - g_signal_connect ((gpointer) b_removematerial, "clicked", G_CALLBACK (OnRemoveMaterial), NULL); - g_signal_connect ((gpointer) t_exportmaterials, "clicked", G_CALLBACK (OnExportMatClicked), NULL); - - /* Store pointers to all widgets, for use by lookup_widget(). */ - GLADE_HOOKUP_OBJECT_NO_REF (w_plugplug2, w_plugplug2, "w_plugplug2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox1, "vbox1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, hbox2, "hbox2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox4, "vbox4"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_collapse, "r_collapse"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_collapsebymaterial, "r_collapsebymaterial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_nocollapse, "r_nocollapse"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox3, "vbox3"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_export, "b_export"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_close, "b_close"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox2, "vbox2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, label1, "label1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, scrolledwindow1, "scrolledwindow1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_materialist, "t_materialist"); - GLADE_HOOKUP_OBJECT (w_plugplug2, ed_materialname, "ed_materialname"); - GLADE_HOOKUP_OBJECT (w_plugplug2, hbox1, "hbox1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_addmaterial, "b_addmaterial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_removematerial, "b_removematerial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_exportmaterials, "t_exportmaterials"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_limitmatnames, "t_limitmatnames"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_objects, "t_objects"); - - return w_plugplug2; +create_w_plugplug2( void ){ + GtkWidget *w_plugplug2; + GtkWidget *vbox1; + GtkWidget *hbox2; + GtkWidget *vbox4; + GtkWidget *r_collapse; + GSList *r_collapse_group = NULL; + GtkWidget *r_collapsebymaterial; + GtkWidget *r_nocollapse; + GtkWidget *vbox3; + GtkWidget *b_export; + GtkWidget *b_close; + GtkWidget *vbox2; + GtkWidget *label1; + GtkWidget *scrolledwindow1; + GtkWidget *t_materialist; + GtkWidget *ed_materialname; + GtkWidget *hbox1; + GtkWidget *b_addmaterial; + GtkWidget *b_removematerial; + GtkWidget *t_exportmaterials; + GtkWidget *t_limitmatnames; + GtkWidget *t_objects; + GtkTooltips *tooltips; + + tooltips = gtk_tooltips_new(); + + w_plugplug2 = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_widget_set_name( w_plugplug2, "w_plugplug2" ); + gtk_window_set_title( GTK_WINDOW( w_plugplug2 ), "BrushExport-Plugin 3.0 by namespace" ); + gtk_window_set_position( GTK_WINDOW( w_plugplug2 ), GTK_WIN_POS_CENTER ); + gtk_window_set_destroy_with_parent( GTK_WINDOW( w_plugplug2 ), TRUE ); + + vbox1 = gtk_vbox_new( FALSE, 0 ); + gtk_widget_set_name( vbox1, "vbox1" ); + gtk_widget_show( vbox1 ); + gtk_container_add( GTK_CONTAINER( w_plugplug2 ), vbox1 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox1 ), 5 ); + + hbox2 = gtk_hbox_new( TRUE, 5 ); + gtk_widget_set_name( hbox2, "hbox2" ); + gtk_widget_show( hbox2 ); + gtk_box_pack_start( GTK_BOX( vbox1 ), hbox2, FALSE, FALSE, 0 ); + gtk_container_set_border_width( GTK_CONTAINER( hbox2 ), 5 ); + + vbox4 = gtk_vbox_new( TRUE, 0 ); + gtk_widget_set_name( vbox4, "vbox4" ); + gtk_widget_show( vbox4 ); + gtk_box_pack_start( GTK_BOX( hbox2 ), vbox4, TRUE, FALSE, 0 ); + + r_collapse = gtk_radio_button_new_with_mnemonic( NULL, "Collapse mesh" ); + gtk_widget_set_name( r_collapse, "r_collapse" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), r_collapse, "Collapse all brushes into a single group", "Collapse all brushes into a single group" ); + gtk_widget_show( r_collapse ); + gtk_box_pack_start( GTK_BOX( vbox4 ), r_collapse, FALSE, FALSE, 0 ); + gtk_radio_button_set_group( GTK_RADIO_BUTTON( r_collapse ), r_collapse_group ); + r_collapse_group = gtk_radio_button_get_group( GTK_RADIO_BUTTON( r_collapse ) ); + + r_collapsebymaterial = gtk_radio_button_new_with_mnemonic( NULL, "Collapse by material" ); + gtk_widget_set_name( r_collapsebymaterial, "r_collapsebymaterial" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), r_collapsebymaterial, "Collapse into groups by material", "Collapse into groups by material" ); + gtk_widget_show( r_collapsebymaterial ); + gtk_box_pack_start( GTK_BOX( vbox4 ), r_collapsebymaterial, FALSE, FALSE, 0 ); + gtk_radio_button_set_group( GTK_RADIO_BUTTON( r_collapsebymaterial ), r_collapse_group ); + r_collapse_group = gtk_radio_button_get_group( GTK_RADIO_BUTTON( r_collapsebymaterial ) ); + + r_nocollapse = gtk_radio_button_new_with_mnemonic( NULL, "Don't collapse" ); + gtk_widget_set_name( r_nocollapse, "r_nocollapse" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), r_nocollapse, "Every brush is stored in its own group", "Every brush is stored in its own group" ); + gtk_widget_show( r_nocollapse ); + gtk_box_pack_start( GTK_BOX( vbox4 ), r_nocollapse, FALSE, FALSE, 0 ); + gtk_radio_button_set_group( GTK_RADIO_BUTTON( r_nocollapse ), r_collapse_group ); + r_collapse_group = gtk_radio_button_get_group( GTK_RADIO_BUTTON( r_nocollapse ) ); + + vbox3 = gtk_vbox_new( FALSE, 0 ); + gtk_widget_set_name( vbox3, "vbox3" ); + gtk_widget_show( vbox3 ); + gtk_box_pack_start( GTK_BOX( hbox2 ), vbox3, FALSE, FALSE, 0 ); + + b_export = gtk_button_new_from_stock( "gtk-save" ); + gtk_widget_set_name( b_export, "b_export" ); + gtk_widget_show( b_export ); + gtk_box_pack_start( GTK_BOX( vbox3 ), b_export, TRUE, FALSE, 0 ); + gtk_container_set_border_width( GTK_CONTAINER( b_export ), 5 ); + + b_close = gtk_button_new_from_stock( "gtk-cancel" ); + gtk_widget_set_name( b_close, "b_close" ); + gtk_widget_show( b_close ); + gtk_box_pack_start( GTK_BOX( vbox3 ), b_close, TRUE, FALSE, 0 ); + gtk_container_set_border_width( GTK_CONTAINER( b_close ), 5 ); + + vbox2 = gtk_vbox_new( FALSE, 5 ); + gtk_widget_set_name( vbox2, "vbox2" ); + gtk_widget_show( vbox2 ); + gtk_box_pack_start( GTK_BOX( vbox1 ), vbox2, TRUE, TRUE, 0 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 2 ); + + label1 = gtk_label_new( "Ignored materials:" ); + gtk_widget_set_name( label1, "label1" ); + gtk_widget_show( label1 ); + gtk_box_pack_start( GTK_BOX( vbox2 ), label1, FALSE, FALSE, 0 ); + + scrolledwindow1 = gtk_scrolled_window_new( NULL, NULL ); + gtk_widget_set_name( scrolledwindow1, "scrolledwindow1" ); + gtk_widget_show( scrolledwindow1 ); + gtk_box_pack_start( GTK_BOX( vbox2 ), scrolledwindow1, TRUE, TRUE, 0 ); + gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledwindow1 ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); + gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledwindow1 ), GTK_SHADOW_IN ); + + t_materialist = gtk_tree_view_new(); + gtk_widget_set_name( t_materialist, "t_materialist" ); + gtk_widget_show( t_materialist ); + gtk_container_add( GTK_CONTAINER( scrolledwindow1 ), t_materialist ); + gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( t_materialist ), FALSE ); + gtk_tree_view_set_enable_search( GTK_TREE_VIEW( t_materialist ), FALSE ); + + ed_materialname = gtk_entry_new(); + gtk_widget_set_name( ed_materialname, "ed_materialname" ); + gtk_widget_show( ed_materialname ); + gtk_box_pack_start( GTK_BOX( vbox2 ), ed_materialname, FALSE, FALSE, 0 ); + + hbox1 = gtk_hbox_new( TRUE, 0 ); + gtk_widget_set_name( hbox1, "hbox1" ); + gtk_widget_show( hbox1 ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox1, FALSE, FALSE, 0 ); + + b_addmaterial = gtk_button_new_from_stock( "gtk-add" ); + gtk_widget_set_name( b_addmaterial, "b_addmaterial" ); + gtk_widget_show( b_addmaterial ); + gtk_box_pack_start( GTK_BOX( hbox1 ), b_addmaterial, FALSE, FALSE, 0 ); + + b_removematerial = gtk_button_new_from_stock( "gtk-remove" ); + gtk_widget_set_name( b_removematerial, "b_removematerial" ); + gtk_widget_show( b_removematerial ); + gtk_box_pack_start( GTK_BOX( hbox1 ), b_removematerial, FALSE, FALSE, 0 ); + + t_limitmatnames = gtk_check_button_new_with_mnemonic( "Use short material names (max. 20 chars)" ); + gtk_widget_set_name( t_limitmatnames, "t_limitmatnames" ); + gtk_widget_show( t_limitmatnames ); + gtk_box_pack_end( GTK_BOX( vbox2 ), t_limitmatnames, FALSE, FALSE, 0 ); + + t_objects = gtk_check_button_new_with_mnemonic( "Create (o)bjects instead of (g)roups" ); + gtk_widget_set_name( t_objects, "t_objects" ); + gtk_widget_show( t_objects ); + gtk_box_pack_end( GTK_BOX( vbox2 ), t_objects, FALSE, FALSE, 0 ); + + t_exportmaterials = gtk_check_button_new_with_mnemonic( "Create material information (.mtl file)" ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( t_exportmaterials ), true ); + gtk_widget_set_name( t_exportmaterials, "t_exportmaterials" ); + gtk_widget_show( t_exportmaterials ); + gtk_box_pack_end( GTK_BOX( vbox2 ), t_exportmaterials, FALSE, FALSE, 10 ); + + using namespace callbacks; + g_signal_connect( G_OBJECT( w_plugplug2 ), "destroy", G_CALLBACK( OnDestroy ), NULL ); + g_signal_connect_swapped( G_OBJECT( b_close ), "clicked", G_CALLBACK( OnDestroy ), NULL ); + + g_signal_connect( ( gpointer )b_export, "clicked", G_CALLBACK( OnExportClicked ), NULL ); + g_signal_connect( ( gpointer )b_addmaterial, "clicked", G_CALLBACK( OnAddMaterial ), NULL ); + g_signal_connect( ( gpointer )b_removematerial, "clicked", G_CALLBACK( OnRemoveMaterial ), NULL ); + g_signal_connect( ( gpointer )t_exportmaterials, "clicked", G_CALLBACK( OnExportMatClicked ), NULL ); + + /* Store pointers to all widgets, for use by lookup_widget(). */ + GLADE_HOOKUP_OBJECT_NO_REF( w_plugplug2, w_plugplug2, "w_plugplug2" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, vbox1, "vbox1" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, hbox2, "hbox2" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, vbox4, "vbox4" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, r_collapse, "r_collapse" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, r_collapsebymaterial, "r_collapsebymaterial" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, r_nocollapse, "r_nocollapse" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, vbox3, "vbox3" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, b_export, "b_export" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, b_close, "b_close" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, vbox2, "vbox2" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, label1, "label1" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, scrolledwindow1, "scrolledwindow1" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, t_materialist, "t_materialist" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, ed_materialname, "ed_materialname" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, hbox1, "hbox1" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, b_addmaterial, "b_addmaterial" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, b_removematerial, "b_removematerial" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, t_exportmaterials, "t_exportmaterials" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, t_limitmatnames, "t_limitmatnames" ); + GLADE_HOOKUP_OBJECT( w_plugplug2, t_objects, "t_objects" ); + + return w_plugplug2; } // global main window, is 0 when not created GtkWidget* g_brushexp_window = 0; // spawn plugin window (and make sure it got destroyed first or never created) -void CreateWindow(void) -{ - ASSERT_NOTNULL(!g_brushexp_window); +void CreateWindow( void ){ + ASSERT_NOTNULL( !g_brushexp_window ); - GtkWidget* wnd = create_w_plugplug2(); + GtkWidget* wnd = create_w_plugplug2(); // column & renderer GtkTreeViewColumn* col = gtk_tree_view_column_new(); - gtk_tree_view_column_set_title(col, "materials"); - gtk_tree_view_append_column(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), col); + gtk_tree_view_column_set_title( col, "materials" ); + gtk_tree_view_append_column( GTK_TREE_VIEW( lookup_widget( wnd, "t_materialist" ) ), col ); GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), -1, "", renderer, "text", 0, NULL); - + gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( lookup_widget( wnd, "t_materialist" ) ), -1, "", renderer, "text", 0, NULL ); + // list store - GtkListStore* ignorelist = gtk_list_store_new(1, G_TYPE_STRING); - gtk_tree_view_set_model(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), GTK_TREE_MODEL(ignorelist)); - g_object_unref(ignorelist); - - gtk_widget_show_all(wnd); + GtkListStore* ignorelist = gtk_list_store_new( 1, G_TYPE_STRING ); + gtk_tree_view_set_model( GTK_TREE_VIEW( lookup_widget( wnd, "t_materialist" ) ), GTK_TREE_MODEL( ignorelist ) ); + g_object_unref( ignorelist ); + + gtk_widget_show_all( wnd ); g_brushexp_window = wnd; } -void DestroyWindow(void) -{ - ASSERT_NOTNULL(g_brushexp_window); - gtk_widget_destroy(g_brushexp_window); +void DestroyWindow( void ){ + ASSERT_NOTNULL( g_brushexp_window ); + gtk_widget_destroy( g_brushexp_window ); g_brushexp_window = 0; } -bool IsWindowOpen(void) -{ +bool IsWindowOpen( void ){ return g_brushexp_window != 0; } diff --git a/contrib/brushexport/plugin.cpp b/contrib/brushexport/plugin.cpp index 3b3fab09..274c840e 100644 --- a/contrib/brushexport/plugin.cpp +++ b/contrib/brushexport/plugin.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2006, Thomas Nitschke. -All Rights Reserved. + Copyright (C) 2006, Thomas Nitschke. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "plugin.h" #include "iplugin.h" @@ -44,91 +44,82 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "typesystem.h" -void CreateWindow (void); -void DestroyWindow(void); -bool IsWindowOpen(void); +void CreateWindow( void ); +void DestroyWindow( void ); +bool IsWindowOpen( void ); namespace BrushExport { - GtkWindow* g_mainwnd; - - const char* init(void* hApp, void* pMainWidget) - { - g_mainwnd = (GtkWindow*)pMainWidget; - ASSERT_NOTNULL(g_mainwnd); - return ""; - } - const char* getName() - { - return "Brush export Plugin"; - } - const char* getCommandList() - { - return "Export selected as Wavefront Object;About"; - } - const char* getCommandTitleList() - { - return ""; - } - - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), "Brushexport plugin v 2.0 by namespace (www.codecreator.net)\n" - "Enjoy!\n\nSend feedback to spam@codecreator.net", "About me...", - eMB_OK, - eMB_ICONDEFAULT); - } - else if(string_equal(command, "Export selected as Wavefront Object")) - { - if(IsWindowOpen()) - DestroyWindow(); - CreateWindow(); - } - } +GtkWindow* g_mainwnd; + +const char* init( void* hApp, void* pMainWidget ){ + g_mainwnd = (GtkWindow*)pMainWidget; + ASSERT_NOTNULL( g_mainwnd ); + return ""; +} +const char* getName(){ + return "Brush export Plugin"; +} +const char* getCommandList(){ + return "Export selected as Wavefront Object;About"; +} +const char* getCommandTitleList(){ + return ""; +} + +void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ + if ( string_equal( command, "About" ) ) { + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), "Brushexport plugin v 2.0 by namespace (www.codecreator.net)\n" + "Enjoy!\n\nSend feedback to spam@codecreator.net", "About me...", + eMB_OK, + eMB_ICONDEFAULT ); + } + else if ( string_equal( command, "Export selected as Wavefront Object" ) ) { + if ( IsWindowOpen() ) { + DestroyWindow(); + } + CreateWindow(); + } +} } class BrushExportDependencies : - public GlobalRadiantModuleRef, - public GlobalFiletypesModuleRef, - public GlobalBrushModuleRef, - public GlobalFileSystemModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalSelectionModuleRef + public GlobalRadiantModuleRef, + public GlobalFiletypesModuleRef, + public GlobalBrushModuleRef, + public GlobalFileSystemModuleRef, + public GlobalSceneGraphModuleRef, + public GlobalSelectionModuleRef { public: - BrushExportDependencies(void) - : GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")) - {} +BrushExportDependencies( void ) + : GlobalBrushModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "brushtypes" ) ) +{} }; class BrushExportModule : public TypeSystemRef { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "brushexport2"); - - BrushExportModule() - { - m_plugin.m_pfnQERPlug_Init = &BrushExport::init; - m_plugin.m_pfnQERPlug_GetName = &BrushExport::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &BrushExport::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &BrushExport::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &BrushExport::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "brushexport2" ); + +BrushExportModule(){ + m_plugin.m_pfnQERPlug_Init = &BrushExport::init; + m_plugin.m_pfnQERPlug_GetName = &BrushExport::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &BrushExport::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &BrushExport::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &BrushExport::dispatch; +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonBrushExportModule; SingletonBrushExportModule g_BrushExportModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - g_BrushExportModule.selfRegister(); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); + g_BrushExportModule.selfRegister(); } diff --git a/contrib/brushexport/plugin.h b/contrib/brushexport/plugin.h index da0faa13..d924f647 100644 --- a/contrib/brushexport/plugin.h +++ b/contrib/brushexport/plugin.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2006, Thomas Nitschke. -All Rights Reserved. + Copyright (C) 2006, Thomas Nitschke. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_BRUSH_EXPORT_H) +#if !defined( INCLUDED_BRUSH_EXPORT_H ) #define INCLUDED_BRUSH_EXPORT_H #endif diff --git a/contrib/brushexport/support.cpp b/contrib/brushexport/support.cpp index 2835b112..79c5e145 100644 --- a/contrib/brushexport/support.cpp +++ b/contrib/brushexport/support.cpp @@ -3,29 +3,31 @@ #include "support.h" GtkWidget* -lookup_widget (GtkWidget *widget, - const gchar *widget_name) -{ - GtkWidget *parent, *found_widget; +lookup_widget( GtkWidget *widget, + const gchar *widget_name ){ + GtkWidget *parent, *found_widget; - for (;;) - { - if (GTK_IS_MENU (widget)) - parent = gtk_menu_get_attach_widget (GTK_MENU (widget)); - else - parent = widget->parent; - if (!parent) - parent = (GtkWidget*) g_object_get_data (G_OBJECT (widget), "GladeParentKey"); - if (parent == NULL) - break; - widget = parent; - } + for (;; ) + { + if ( GTK_IS_MENU( widget ) ) { + parent = gtk_menu_get_attach_widget( GTK_MENU( widget ) ); + } + else{ + parent = widget->parent; + } + if ( !parent ) { + parent = (GtkWidget*) g_object_get_data( G_OBJECT( widget ), "GladeParentKey" ); + } + if ( parent == NULL ) { + break; + } + widget = parent; + } - found_widget = (GtkWidget*) g_object_get_data (G_OBJECT (widget), - widget_name); - if (!found_widget) - g_warning ("Widget not found: %s", widget_name); - return found_widget; + found_widget = (GtkWidget*) g_object_get_data( G_OBJECT( widget ), + widget_name ); + if ( !found_widget ) { + g_warning( "Widget not found: %s", widget_name ); + } + return found_widget; } - - diff --git a/contrib/brushexport/support.h b/contrib/brushexport/support.h index 628885a5..e8f4cb04 100644 --- a/contrib/brushexport/support.h +++ b/contrib/brushexport/support.h @@ -18,7 +18,5 @@ * or alternatively any widget in the component, and the name of the widget * you want returned. */ -GtkWidget* lookup_widget (GtkWidget *widget, - const gchar *widget_name); - - +GtkWidget* lookup_widget( GtkWidget *widget, + const gchar *widget_name ); diff --git a/contrib/camera/camera.cpp b/contrib/camera/camera.cpp index 488e6549..5647f4c0 100644 --- a/contrib/camera/camera.cpp +++ b/contrib/camera/camera.cpp @@ -1,28 +1,28 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" @@ -44,75 +44,79 @@ GtkWidget *g_pCameraInspectorWnd = NULL; CCamera *firstCam = NULL; // double linked list CCamera *firstFreeCam = NULL; // single linked list CCamera *currentCam = NULL; // single item -bool g_bEditOn = false; -int g_iEditMode = 0; // 0: editting points 1: adding points -int g_iActiveTarget = -1; -int g_iPreviewRunning = 0; // 0: no preview 1: start preview 2: preview in progress +bool g_bEditOn = false; +int g_iEditMode = 0; // 0: editting points 1: adding points +int g_iActiveTarget = -1; +int g_iPreviewRunning = 0; // 0: no preview 1: start preview 2: preview in progress static const char *PLUGIN_ABOUT = "Camera v1.0 for NetRadiant\n" - "by Arnout van Meer (rr2do2@splashdamage.com)\n\n" - "This product contains software technology\n" - "from id Software, Inc. ('id Technology').\n" - "id Technology (c) 2001, 2002 id Software, Inc."; + "by Arnout van Meer (rr2do2@splashdamage.com)\n\n" + "This product contains software technology\n" + "from id Software, Inc. ('id Technology').\n" + "id Technology (c) 2001, 2002 id Software, Inc."; #include "iplugin.h" -const char* QERPlug_Init(void* hApp, void* pMainWidget) -{ - g_pRadiantWnd = (GtkWidget*)pMainWidget; - - // initialize cams - for( int i = 0; i < MAX_CAMERAS; i++ ) { - if( i == 0 ) { - firstFreeCam = new CCamera( i ); - firstCam = firstFreeCam; - } else { - firstCam->SetNext( new CCamera( i ) ); - firstCam = firstCam->GetNext(); - } - } - firstCam = NULL; - - if( !Renderer ) - { - Renderer = new CRenderer; - } - - if( g_pCameraInspectorWnd == NULL ) - g_pCameraInspectorWnd = CreateCameraInspectorDialog(); - - GetFileTypeRegistry()->addType("camera", "", filetype_t("Camera file", "*.camera")); - - return "Camera for NetRadiant"; +const char* QERPlug_Init( void* hApp, void* pMainWidget ){ + g_pRadiantWnd = (GtkWidget*)pMainWidget; + + // initialize cams + for ( int i = 0; i < MAX_CAMERAS; i++ ) { + if ( i == 0 ) { + firstFreeCam = new CCamera( i ); + firstCam = firstFreeCam; + } + else { + firstCam->SetNext( new CCamera( i ) ); + firstCam = firstCam->GetNext(); + } + } + firstCam = NULL; + + if ( !Renderer ) { + Renderer = new CRenderer; + } + + if ( g_pCameraInspectorWnd == NULL ) { + g_pCameraInspectorWnd = CreateCameraInspectorDialog(); + } + + GetFileTypeRegistry()->addType( "camera", "", filetype_t( "Camera file", "*.camera" ) ); + + return "Camera for NetRadiant"; } -const char* QERPlug_GetName() -{ - return PLUGIN_NAME; +const char* QERPlug_GetName(){ + return PLUGIN_NAME; } -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; +const char* QERPlug_GetCommandList(){ + return PLUGIN_COMMANDS; } -void QERPlug_Dispatch (const char* p, float* vMin, float* vMax, bool bSingleBrush) -{ - if( !strcmp( p, "New Fixed Camera" ) ) - DoNewFixedCamera(); - else if( !strcmp( p, "New Interpolated Camera" ) ) - DoNewInterpolatedCamera(); - else if( !strcmp( p, "New Spline Camera" ) ) - DoNewSplineCamera(); - else if( !strcmp( p, "Camera Inspector..." ) ) - DoCameraInspector(); - else if( !strcmp( p, "Preview Camera" ) ) - DoPreviewCamera(); - else if( !strcmp( p, "Load Camera..." ) ) - DoLoadCamera(); - else if( !strcmp( p, "About..." ) ) - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, PLUGIN_ABOUT, "About", eMB_OK ); +void QERPlug_Dispatch( const char* p, float* vMin, float* vMax, bool bSingleBrush ){ + if ( !strcmp( p, "New Fixed Camera" ) ) { + DoNewFixedCamera(); + } + else if ( !strcmp( p, "New Interpolated Camera" ) ) { + DoNewInterpolatedCamera(); + } + else if ( !strcmp( p, "New Spline Camera" ) ) { + DoNewSplineCamera(); + } + else if ( !strcmp( p, "Camera Inspector..." ) ) { + DoCameraInspector(); + } + else if ( !strcmp( p, "Preview Camera" ) ) { + DoPreviewCamera(); + } + else if ( !strcmp( p, "Load Camera..." ) ) { + DoLoadCamera(); + } + else if ( !strcmp( p, "About..." ) ) { + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, PLUGIN_ABOUT, "About", eMB_OK ); + } } @@ -120,48 +124,41 @@ void QERPlug_Dispatch (const char* p, float* vMin, float* vMax, bool bSingleBrus #include "itoolbar.h" -unsigned int ToolbarButtonCount() -{ - return 1; +unsigned int ToolbarButtonCount(){ + return 1; } class CameraInspectorButton : public IToolbarButton { public: - virtual const char* getImage() const - { - return "camera_insp.bmp"; - } - virtual const char* getText() const - { - return "Inspector"; - } - virtual const char* getTooltip() const - { - return "Camera Inspector"; - } - virtual void activate() const - { - DoCameraInspector(); - } - virtual EType getType() const - { - return eButton; - } +virtual const char* getImage() const { + return "camera_insp.bmp"; +} +virtual const char* getText() const { + return "Inspector"; +} +virtual const char* getTooltip() const { + return "Camera Inspector"; +} +virtual void activate() const { + DoCameraInspector(); +} +virtual EType getType() const { + return eButton; +} }; CameraInspectorButton g_camerainspectorbutton; -const IToolbarButton* GetToolbarButton(unsigned int index) -{ - return &g_camerainspectorbutton; +const IToolbarButton* GetToolbarButton( unsigned int index ){ + return &g_camerainspectorbutton; } -_QERFuncTable_1 g_FuncTable; -_QERQglTable g_QglTable; -_QERUITable g_UITable; -_QERCameraTable g_CameraTable; +_QERFuncTable_1 g_FuncTable; +_QERQglTable g_QglTable; +_QERUITable g_UITable; +_QERCameraTable g_CameraTable; // ============================================================================= // SYNAPSE @@ -171,69 +168,63 @@ _QERCameraTable g_CameraTable; class CameraSynapseClient : public CSynapseClient { public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - CameraSynapseClient() { } - virtual ~CameraSynapseClient() { } +// CSynapseClient API +bool RequestAPI( APIDescriptor_t *pAPI ); +const char* GetInfo(); + +CameraSynapseClient() { } +virtual ~CameraSynapseClient() { } }; CSynapseServer* g_pSynapseServer = NULL; CameraSynapseClient g_SynapseClient; -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(TOOLBAR_MAJOR, "camera", sizeof(_QERPlugToolbarTable)); - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "camera", sizeof(_QERPluginTable)); - - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(_QERFuncTable_1), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(UI_MAJOR, NULL, sizeof(_QERUITable), SYN_REQUIRE, &g_UITable); - g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(_QERQglTable), SYN_REQUIRE, &g_QglTable); - g_SynapseClient.AddAPI(CAMERA_MAJOR, NULL, sizeof(_QERCameraTable), SYN_REQUIRE, &g_CameraTable); - - return &g_SynapseClient; +extern "C" CSynapseClient * SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces( const char *version, CSynapseServer *pServer ){ + if ( strcmp( version, SYNAPSE_VERSION ) ) { + Syn_Printf( "ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version ); + return NULL; + } + g_pSynapseServer = pServer; + g_pSynapseServer->IncRef(); + Set_Syn_Printf( g_pSynapseServer->Get_Syn_Printf() ); + + g_SynapseClient.AddAPI( TOOLBAR_MAJOR, "camera", sizeof( _QERPlugToolbarTable ) ); + g_SynapseClient.AddAPI( PLUGIN_MAJOR, "camera", sizeof( _QERPluginTable ) ); + + g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( _QERFuncTable_1 ), SYN_REQUIRE, &g_FuncTable ); + g_SynapseClient.AddAPI( UI_MAJOR, NULL, sizeof( _QERUITable ), SYN_REQUIRE, &g_UITable ); + g_SynapseClient.AddAPI( QGL_MAJOR, NULL, sizeof( _QERQglTable ), SYN_REQUIRE, &g_QglTable ); + g_SynapseClient.AddAPI( CAMERA_MAJOR, NULL, sizeof( _QERCameraTable ), SYN_REQUIRE, &g_CameraTable ); + + return &g_SynapseClient; } -bool CameraSynapseClient::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, TOOLBAR_MAJOR)) - { - _QERPlugToolbarTable* pTable= static_cast<_QERPlugToolbarTable*>(pAPI->mpTable); - - pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; - pTable->m_pfnGetToolbarButton = &GetToolbarButton; - return true; - } - else if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; +bool CameraSynapseClient::RequestAPI( APIDescriptor_t *pAPI ){ + if ( !strcmp( pAPI->major_name, TOOLBAR_MAJOR ) ) { + _QERPlugToolbarTable* pTable = static_cast<_QERPlugToolbarTable*>( pAPI->mpTable ); + + pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; + pTable->m_pfnGetToolbarButton = &GetToolbarButton; + return true; + } + else if ( !strcmp( pAPI->major_name, PLUGIN_MAJOR ) ) { + _QERPluginTable* pTable = static_cast<_QERPluginTable*>( pAPI->mpTable ); + + pTable->m_pfnQERPlug_Init = QERPlug_Init; + pTable->m_pfnQERPlug_GetName = QERPlug_GetName; + pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + return true; + } + + Syn_Printf( "ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo() ); + return false; } #include "version.h" -const char* CameraSynapseClient::GetInfo() -{ - return "Camera plugin v1.0 - Arnout van Meer - built " __DATE__ " " RADIANT_VERSION; +const char* CameraSynapseClient::GetInfo(){ + return "Camera plugin v1.0 - Arnout van Meer - built " __DATE__ " " RADIANT_VERSION; } @@ -242,49 +233,53 @@ const char* CameraSynapseClient::GetInfo() // CCamera // CCamera *AllocCam() { - if( !firstFreeCam ) - return( NULL ); - - CCamera *cam = firstFreeCam; - firstFreeCam = firstFreeCam->GetNext(); - cam->Init(); - if( firstCam ) { - cam->SetNext( firstCam ); - firstCam->SetPrev( cam ); - } - firstCam = cam; - - return( cam ); + if ( !firstFreeCam ) { + return( NULL ); + } + + CCamera *cam = firstFreeCam; + firstFreeCam = firstFreeCam->GetNext(); + cam->Init(); + if ( firstCam ) { + cam->SetNext( firstCam ); + firstCam->SetPrev( cam ); + } + firstCam = cam; + + return( cam ); } void FreeCam( CCamera *cam ) { - if( cam->GetPrev() ) { - if( cam->GetNext() ) { - cam->GetPrev()->SetNext( cam->GetNext() ); - cam->GetNext()->SetPrev( cam->GetPrev() ); - } else { - cam->GetPrev()->SetNext( NULL ); - } - } else if( cam->GetNext() ) { - cam->GetNext()->SetPrev( NULL ); - firstCam = cam->GetNext(); - } else { - firstCam = NULL; - } - - cam->GetCam()->clear(); - cam->Init(); - - if( firstFreeCam ) { - cam->SetNext( firstFreeCam ); - } - firstFreeCam = cam; + if ( cam->GetPrev() ) { + if ( cam->GetNext() ) { + cam->GetPrev()->SetNext( cam->GetNext() ); + cam->GetNext()->SetPrev( cam->GetPrev() ); + } + else { + cam->GetPrev()->SetNext( NULL ); + } + } + else if ( cam->GetNext() ) { + cam->GetNext()->SetPrev( NULL ); + firstCam = cam->GetNext(); + } + else { + firstCam = NULL; + } + + cam->GetCam()->clear(); + cam->Init(); + + if ( firstFreeCam ) { + cam->SetNext( firstFreeCam ); + } + firstFreeCam = cam; } void SetCurrentCam( CCamera *cam ) { - currentCam = cam; + currentCam = cam; } CCamera *GetCurrentCam() { - return( currentCam ); + return( currentCam ); } diff --git a/contrib/camera/camera.h b/contrib/camera/camera.h index 4c7f6cb2..896ca1be 100644 --- a/contrib/camera/camera.h +++ b/contrib/camera/camera.h @@ -1,28 +1,28 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #ifndef _CAMERA_H_ #define _CAMERA_H_ @@ -59,17 +59,17 @@ class CCamera; #include "renderer.h" #include "listener.h" -extern _QERFuncTable_1 g_FuncTable; -extern _QERQglTable g_QglTable; -extern _QERUITable g_UITable; -extern _QERCameraTable g_CameraTable; +extern _QERFuncTable_1 g_FuncTable; +extern _QERQglTable g_QglTable; +extern _QERUITable g_UITable; +extern _QERCameraTable g_CameraTable; extern CRenderer *Renderer; extern CListener *Listener; // splinelib #define CAMERA_PLUGIN -#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) +#define DotProduct( a,b ) ( ( a )[0] * ( b )[0] + ( a )[1] * ( b )[1] + ( a )[2] * ( b )[2] ) #include "splines/splines.h" @@ -77,7 +77,7 @@ extern CListener *Listener; #define MAX_CAMERAS 64 extern idCameraDef camera[MAX_CAMERAS]; -extern "C" qboolean loadCamera(int camNum, const char *name); +extern "C" qboolean loadCamera( int camNum, const char *name ); #ifndef PATH_MAX #define PATH_MAX 260 @@ -89,64 +89,66 @@ extern "C" qboolean loadCamera(int camNum, const char *name); class CCamera { public: - CCamera( int i ) { - cam = &camera[i]; - camnum = i; - Init(); - } - ~CCamera(); - - void Init() { - next = prev = NULL; - fileName[0] = '\0'; - hasbeensaved = 0; - } - - idCameraDef *GetCam() { - return( cam ); - } - int GetCamNum() { - return( camnum ); - } - - char *GetFileName() { - return( fileName ); - } - void SetFileName( const char *name, bool save ) { - strcpy( fileName, name ); - if( save ) - hasbeensaved = 1; - } - - CCamera *GetNext() { - return( next ); - } - - CCamera *GetPrev() { - return( prev ); - } - - void SetNext( CCamera *camera ) { - next = camera; - } - void SetPrev( CCamera *camera ) { - prev = camera; - } - - int HasBeenSaved() { - return( hasbeensaved ); +CCamera( int i ) { + cam = &camera[i]; + camnum = i; + Init(); +} +~CCamera(); + +void Init() { + next = prev = NULL; + fileName[0] = '\0'; + hasbeensaved = 0; +} + +idCameraDef *GetCam() { + return( cam ); +} +int GetCamNum() { + return( camnum ); +} + +char *GetFileName() { + return( fileName ); +} +void SetFileName( const char *name, bool save ) { + strcpy( fileName, name ); + if ( save ) { + hasbeensaved = 1; } - void HasBeenModified() { - if( hasbeensaved ) - hasbeensaved = 2; +} + +CCamera *GetNext() { + return( next ); +} + +CCamera *GetPrev() { + return( prev ); +} + +void SetNext( CCamera *camera ) { + next = camera; +} +void SetPrev( CCamera *camera ) { + prev = camera; +} + +int HasBeenSaved() { + return( hasbeensaved ); +} +void HasBeenModified() { + if ( hasbeensaved ) { + hasbeensaved = 2; } +} protected: - idCameraDef *cam; - int camnum; - CCamera *next, *prev; - char fileName[PATH_MAX]; - int hasbeensaved; // 0:never saved 1:saved 2:saved, but modified +idCameraDef *cam; +int camnum; +CCamera *next, *prev; +char fileName[PATH_MAX]; +int hasbeensaved; // 0:never saved 1:saved 2:saved, but modified }; CCamera *AllocCam(); diff --git a/contrib/camera/dialogs.cpp b/contrib/camera/dialogs.cpp index 40df284e..acd2fbd4 100644 --- a/contrib/camera/dialogs.cpp +++ b/contrib/camera/dialogs.cpp @@ -1,28 +1,28 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" @@ -38,192 +38,188 @@ static GtkWidget *g_pTrackCamera = NULL; static GtkWidget *g_pCamName = NULL; static char *g_cNull = '\0'; -static gint ci_editmode_edit( GtkWidget *widget, gpointer data ) -{ +static gint ci_editmode_edit( GtkWidget *widget, gpointer data ){ g_iEditMode = 0; return TRUE; } -static gint ci_editmode_add( GtkWidget *widget, gpointer data ) -{ +static gint ci_editmode_add( GtkWidget *widget, gpointer data ){ g_iEditMode = 1; return TRUE; } /*static gint ci_delete_selected( GtkWidget *widget, gpointer data ) -{ - return TRUE; -} + { + return TRUE; + } -static gint ci_select_all( GtkWidget *widget, gpointer data ) -{ - return TRUE; -}*/ + static gint ci_select_all( GtkWidget *widget, gpointer data ) + { + return TRUE; + }*/ -static gint ci_new( GtkWidget *widget, gpointer data ) -{ +static gint ci_new( GtkWidget *widget, gpointer data ){ GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame; //, *name; GtkWidget *fixed, *interpolated, *spline; EMessageBoxReturn ret; - int loop = 1; + int loop = 1; GSList *targetTypeRadio = NULL; // char buf[128]; // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "New Camera" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( window ), "New Camera" ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize (window); + gtk_widget_realize( window ); // fill the window vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); + frame = gtk_frame_new( "Type" ); + gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); + gtk_widget_show( frame ); vbox2 = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 5 ); gtk_widget_show( vbox2 ); // -------------------------- // fixed = gtk_radio_button_new_with_label( targetTypeRadio, "Fixed" ); gtk_box_pack_start( GTK_BOX( vbox2 ), fixed, FALSE, FALSE, 3 ); - gtk_widget_show( fixed ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); + gtk_widget_show( fixed ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); interpolated = gtk_radio_button_new_with_label( targetTypeRadio, "Interpolated" ); gtk_box_pack_start( GTK_BOX( vbox2 ), interpolated, FALSE, FALSE, 3 ); - gtk_widget_show( interpolated ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); + gtk_widget_show( interpolated ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); spline = gtk_radio_button_new_with_label( targetTypeRadio, "Spline" ); gtk_box_pack_start( GTK_BOX( vbox2 ), spline, FALSE, FALSE, 3 ); - gtk_widget_show( spline ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); + gtk_widget_show( spline ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); - // -------------------------- // + // -------------------------- // - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + gtk_widget_show( w ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; // -------------------------- // - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); bool dialogError = TRUE; - while (dialogError) { + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if( ret == eIDOK ) { - if( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) + if ( ret == eIDOK ) { + if ( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) { DoNewFixedCamera(); - else if( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) { DoNewInterpolatedCamera(); - else if( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) { DoNewSplineCamera(); + } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); - return TRUE; + return TRUE; } -static gint ci_load( GtkWidget *widget, gpointer data ) -{ - DoLoadCamera(); +static gint ci_load( GtkWidget *widget, gpointer data ){ + DoLoadCamera(); - return TRUE; + return TRUE; } -static gint ci_save( GtkWidget *widget, gpointer data ) -{ - DoSaveCamera(); +static gint ci_save( GtkWidget *widget, gpointer data ){ + DoSaveCamera(); - return TRUE; + return TRUE; } -static gint ci_unload( GtkWidget *widget, gpointer data ) -{ +static gint ci_unload( GtkWidget *widget, gpointer data ){ DoUnloadCamera(); return TRUE; } -static gint ci_apply( GtkWidget *widget, gpointer data ) -{ - if( GetCurrentCam() ) { +static gint ci_apply( GtkWidget *widget, gpointer data ){ + if ( GetCurrentCam() ) { const char *str; char buf[128]; bool build = false; - str = gtk_entry_get_text( GTK_ENTRY(g_pCamName) ); + str = gtk_entry_get_text( GTK_ENTRY( g_pCamName ) ); - if( str ) { + if ( str ) { GetCurrentCam()->GetCam()->setName( str ); build = true; } - str = gtk_entry_get_text( GTK_ENTRY(g_pSecondsEntry) ); - - if( str ) { + str = gtk_entry_get_text( GTK_ENTRY( g_pSecondsEntry ) ); + + if ( str ) { GetCurrentCam()->GetCam()->setBaseTime( atof( str ) ); build = true; } - if( build ) { + if ( build ) { GetCurrentCam()->GetCam()->buildCamera(); } sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getBaseTime() ); - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), buf ); + gtk_entry_set_text( GTK_ENTRY( g_pSecondsEntry ), buf ); sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getTotalTime() ); gtk_label_set_text( g_pCurrentTime, "0.00" ); @@ -235,111 +231,113 @@ static gint ci_apply( GtkWidget *widget, gpointer data ) GetCurrentCam()->HasBeenModified(); } - return TRUE; + return TRUE; } -static gint ci_preview( GtkWidget *widget, gpointer data ) -{ - if( GetCurrentCam() ) { +static gint ci_preview( GtkWidget *widget, gpointer data ){ + if ( GetCurrentCam() ) { g_iPreviewRunning = 1; g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); } - return TRUE; + return TRUE; } -static gint ci_expose( GtkWidget *widget, gpointer data ) -{ - // start edit mode - DoStartEdit( GetCurrentCam() ); +static gint ci_expose( GtkWidget *widget, gpointer data ){ + // start edit mode + DoStartEdit( GetCurrentCam() ); - return FALSE; + return FALSE; } -static gint ci_close( GtkWidget *widget, gpointer data ) -{ - gtk_widget_hide( g_pCameraInspectorWnd ); +static gint ci_close( GtkWidget *widget, gpointer data ){ + gtk_widget_hide( g_pCameraInspectorWnd ); - // exit edit mode - DoStopEdit(); + // exit edit mode + DoStopEdit(); - return TRUE; + return TRUE; } static GtkWidget *g_pPathListCombo = NULL; static GtkLabel *g_pPathType = NULL; -static void RefreshPathListCombo( void ) -{ - if( !g_pPathListCombo ) - return; +static void RefreshPathListCombo( void ){ + if ( !g_pPathListCombo ) { + return; + } - GList *combo_list = (GList*)NULL; + GList *combo_list = (GList*)NULL; - if( GetCurrentCam() ) { - combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getPositionObj()->getName() ); - for( int i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { - combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ); - } - } else { + if ( GetCurrentCam() ) { + combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getPositionObj()->getName() ); + for ( int i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { + combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ); + } + } + else { // add one empty string make gtk be quiet combo_list = g_list_append( combo_list, (gpointer)g_cNull ); - } + } - gtk_combo_set_popdown_strings( GTK_COMBO( g_pPathListCombo ), combo_list ); - g_list_free( combo_list ); + gtk_combo_set_popdown_strings( GTK_COMBO( g_pPathListCombo ), combo_list ); + g_list_free( combo_list ); } -static gint ci_pathlist_changed( GtkWidget *widget, gpointer data ) -{ - const char *str = gtk_entry_get_text( GTK_ENTRY(widget) ); +static gint ci_pathlist_changed( GtkWidget *widget, gpointer data ){ + const char *str = gtk_entry_get_text( GTK_ENTRY( widget ) ); - if( !str || !GetCurrentCam() ) - return TRUE; + if ( !str || !GetCurrentCam() ) { + return TRUE; + } int i; - for( i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { - if( !strcmp( str, GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ) ) - break; - } - - if( i >= 0 && i < GetCurrentCam()->GetCam()->numTargets() ) { - GetCurrentCam()->GetCam()->setActiveTarget( i ); - - g_iActiveTarget = i; - if( g_pPathType ) - gtk_label_set_text( g_pPathType, GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->typeStr() ); - } else { - g_iActiveTarget = -1; - if( g_pPathType ) + for ( i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { + if ( !strcmp( str, GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ) ) { + break; + } + } + + if ( i >= 0 && i < GetCurrentCam()->GetCam()->numTargets() ) { + GetCurrentCam()->GetCam()->setActiveTarget( i ); + + g_iActiveTarget = i; + if ( g_pPathType ) { + gtk_label_set_text( g_pPathType, GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->typeStr() ); + } + } + else { + g_iActiveTarget = -1; + if ( g_pPathType ) { gtk_label_set_text( g_pPathType, GetCurrentCam()->GetCam()->getPositionObj()->typeStr() ); - } + } + } - // start edit mode - if( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) - DoStartEdit( GetCurrentCam() ); + // start edit mode + if ( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) { + DoStartEdit( GetCurrentCam() ); + } - return TRUE; + return TRUE; } -static void RefreshEventList( void ) -{ +static void RefreshEventList( void ){ int i; char buf[128]; // Clear events list - gtk_clist_freeze( GTK_CLIST(g_pEventsList) ); - gtk_clist_clear( GTK_CLIST(g_pEventsList) ); + gtk_clist_freeze( GTK_CLIST( g_pEventsList ) ); + gtk_clist_clear( GTK_CLIST( g_pEventsList ) ); - if( GetCurrentCam() ) { + if ( GetCurrentCam() ) { // Fill events list - for( i = 0; i < GetCurrentCam()->GetCam()->numEvents(); i++ ) { + for ( i = 0; i < GetCurrentCam()->GetCam()->numEvents(); i++ ) { char rowbuf[3][128], *row[3]; // FIXME: sort by time? - sprintf( rowbuf[0], "%li", GetCurrentCam()->GetCam()->getEvent(i)->getTime() ); row[0] = rowbuf[0]; - strncpy( rowbuf[1], GetCurrentCam()->GetCam()->getEvent(i)->typeStr(), sizeof(rowbuf[0]) ); row[1] = rowbuf[1]; - strncpy( rowbuf[2], GetCurrentCam()->GetCam()->getEvent(i)->getParam(), sizeof(rowbuf[1]) ); row[2] = rowbuf[2]; - gtk_clist_append( GTK_CLIST(g_pEventsList), row ); + sprintf( rowbuf[0], "%li", GetCurrentCam()->GetCam()->getEvent( i )->getTime() ); row[0] = rowbuf[0]; + strncpy( rowbuf[1], GetCurrentCam()->GetCam()->getEvent( i )->typeStr(), sizeof( rowbuf[0] ) ); row[1] = rowbuf[1]; + strncpy( rowbuf[2], GetCurrentCam()->GetCam()->getEvent( i )->getParam(), sizeof( rowbuf[1] ) ); row[2] = rowbuf[2]; + gtk_clist_append( GTK_CLIST( g_pEventsList ), row ); } // Total duration might have changed @@ -351,370 +349,380 @@ static void RefreshEventList( void ) g_pTimeLine->upper = ( GetCurrentCam()->GetCam()->getTotalTime() * 1000 ); } - gtk_clist_thaw( GTK_CLIST(g_pEventsList) ); + gtk_clist_thaw( GTK_CLIST( g_pEventsList ) ); } -static gint ci_rename( GtkWidget *widget, gpointer data ) -{ +static gint ci_rename( GtkWidget *widget, gpointer data ){ GtkWidget *window, *w, *vbox, *hbox, *name; EMessageBoxReturn ret; - int loop = 1; + int loop = 1; - if( !GetCurrentCam() ) + if ( !GetCurrentCam() ) { return TRUE; + } // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Rename Path" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( window ), "Rename Path" ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize ( window ); + gtk_widget_realize( window ); // fill the window vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Name:" ); + w = gtk_label_new( "Name:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - name = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), name, FALSE, FALSE, 0 ); - gtk_widget_show( name ); + name = gtk_entry_new(); + gtk_box_pack_start( GTK_BOX( hbox ), name, FALSE, FALSE, 0 ); + gtk_widget_show( name ); - if( g_iActiveTarget < 0 ) - gtk_entry_set_text( GTK_ENTRY(name), GetCurrentCam()->GetCam()->getPositionObj()->getName() ); - else - gtk_entry_set_text( GTK_ENTRY(name), GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->getName() ); + if ( g_iActiveTarget < 0 ) { + gtk_entry_set_text( GTK_ENTRY( name ), GetCurrentCam()->GetCam()->getPositionObj()->getName() ); + } + else{ + gtk_entry_set_text( GTK_ENTRY( name ), GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->getName() ); + } - // -------------------------- // + // -------------------------- // - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + gtk_widget_show( w ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; // -------------------------- // - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); bool dialogError = TRUE; - while (dialogError) { + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(name) ); + if ( ret == eIDOK ) { + const char *str = gtk_entry_get_text( GTK_ENTRY( name ) ); - if( str && str[0] ) { + if ( str && str[0] ) { // Update the path - if( g_iActiveTarget < 0 ) + if ( g_iActiveTarget < 0 ) { GetCurrentCam()->GetCam()->getPositionObj()->setName( str ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->setName( str ); + } + else{ + GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->setName( str ); + } GetCurrentCam()->GetCam()->buildCamera(); // Rebuild the listbox RefreshPathListCombo(); - } else { + } + else { dialogError = TRUE; } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); - return TRUE; + return TRUE; } -static gint ci_add_target( GtkWidget *widget, gpointer data ) -{ +static gint ci_add_target( GtkWidget *widget, gpointer data ){ GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame, *name; GtkWidget *fixed, *interpolated, *spline; EMessageBoxReturn ret; - int loop = 1; + int loop = 1; GSList *targetTypeRadio = NULL; char buf[128]; - if( !GetCurrentCam() ) + if ( !GetCurrentCam() ) { return TRUE; + } // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Add Target" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( window ), "Add Target" ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize (window); + gtk_widget_realize( window ); // fill the window vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Name:" ); + w = gtk_label_new( "Name:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - name = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), name, TRUE, TRUE, 0 ); - gtk_widget_show( name ); + name = gtk_entry_new(); + gtk_box_pack_start( GTK_BOX( hbox ), name, TRUE, TRUE, 0 ); + gtk_widget_show( name ); sprintf( buf, "target%i", GetCurrentCam()->GetCam()->numTargets() + 1 ); - gtk_entry_set_text( GTK_ENTRY(name), buf ); + gtk_entry_set_text( GTK_ENTRY( name ), buf ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); + frame = gtk_frame_new( "Type" ); + gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); + gtk_widget_show( frame ); vbox2 = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 5 ); gtk_widget_show( vbox2 ); // -------------------------- // fixed = gtk_radio_button_new_with_label( targetTypeRadio, "Fixed" ); gtk_box_pack_start( GTK_BOX( vbox2 ), fixed, FALSE, FALSE, 3 ); - gtk_widget_show( fixed ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); + gtk_widget_show( fixed ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); interpolated = gtk_radio_button_new_with_label( targetTypeRadio, "Interpolated" ); gtk_box_pack_start( GTK_BOX( vbox2 ), interpolated, FALSE, FALSE, 3 ); - gtk_widget_show( interpolated ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); + gtk_widget_show( interpolated ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); spline = gtk_radio_button_new_with_label( targetTypeRadio, "Spline" ); gtk_box_pack_start( GTK_BOX( vbox2 ), spline, FALSE, FALSE, 3 ); - gtk_widget_show( spline ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); + gtk_widget_show( spline ); + targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); - // -------------------------- // + // -------------------------- // - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + gtk_widget_show( w ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; // -------------------------- // - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); bool dialogError = TRUE; - while (dialogError) { + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(name) ); + if ( ret == eIDOK ) { + const char *str = gtk_entry_get_text( GTK_ENTRY( name ) ); - if( str && str[0] ) { + if ( str && str[0] ) { int type; GList *li; - if( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) + if ( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) { type = 0; - else if( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) { type = 1; - else if( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) + } + else if ( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) { type = 2; + } // Add the target - GetCurrentCam()->GetCam()->addTarget( str, static_cast(type) ); + GetCurrentCam()->GetCam()->addTarget( str, static_cast( type ) ); // Rebuild the listbox RefreshPathListCombo(); // Select the last item in the listbox - li = g_list_last( GTK_LIST(GTK_COMBO(g_pPathListCombo)->list)->children ); - gtk_list_select_child( GTK_LIST(GTK_COMBO(g_pPathListCombo)->list), GTK_WIDGET (li->data) ); + li = g_list_last( GTK_LIST( GTK_COMBO( g_pPathListCombo )->list )->children ); + gtk_list_select_child( GTK_LIST( GTK_COMBO( g_pPathListCombo )->list ), GTK_WIDGET( li->data ) ); // If this was the first one, refresh the event list - if( GetCurrentCam()->GetCam()->numTargets() == 1 ) { + if ( GetCurrentCam()->GetCam()->numTargets() == 1 ) { RefreshEventList(); } // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_pEditModeAddRadioButton ), TRUE ); - } else { + } + else { dialogError = TRUE; } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); - return TRUE; + return TRUE; } static GtkWidget *g_pCamListCombo = NULL; static GtkLabel *g_pCamType = NULL; -void RefreshCamListCombo( void ) -{ - if( !g_pCamListCombo ) - return; +void RefreshCamListCombo( void ){ + if ( !g_pCamListCombo ) { + return; + } - GList *combo_list = (GList*)NULL; - CCamera *combo_cam = firstCam; - if( combo_cam ) { - while( combo_cam ) { + GList *combo_list = (GList*)NULL; + CCamera *combo_cam = firstCam; + if ( combo_cam ) { + while ( combo_cam ) { //combo_list = g_list_append( combo_list, (void *)combo_cam->GetCam()->getName() ); //if( combo_cam->HasBeenSaved() ) { - combo_list = g_list_append( combo_list, (void *)combo_cam->GetFileName() ); + combo_list = g_list_append( combo_list, (void *)combo_cam->GetFileName() ); /*} else { - char buf[128]; - sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); - combo_list = g_list_append( combo_list, (void *)buf ); + char buf[128]; + sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); + combo_list = g_list_append( combo_list, (void *)buf ); - //combo_list = g_list_append( combo_list, (void *)combo_cam->GetCam()->getName() ); // FIXME: this requires camera.dll to create unique names for new cams - }*/ + //combo_list = g_list_append( combo_list, (void *)combo_cam->GetCam()->getName() ); // FIXME: this requires camera.dll to create unique names for new cams + }*/ combo_cam = combo_cam->GetNext(); } - }else { + } + else { // add one empty string make gtk be quiet combo_list = g_list_append( combo_list, (gpointer)g_cNull ); } - gtk_combo_set_popdown_strings( GTK_COMBO( g_pCamListCombo ), combo_list ); - g_list_free( combo_list ); - - // select our current entry in the list - if( GetCurrentCam() ) { - // stop editing on the current cam - //GetCurrentCam()->GetCam()->stopEdit(); // FIXME: this crashed on creating new cameras, why is it here? - - GList *li = GTK_LIST( GTK_COMBO(g_pCamListCombo)->list)->children; - combo_cam = firstCam; - while( li && combo_cam ) { - if( combo_cam == GetCurrentCam() ) { - gtk_list_select_child( GTK_LIST( GTK_COMBO(g_pCamListCombo)->list ), GTK_WIDGET( li->data ) ); - break; - } - li = li->next; - combo_cam = combo_cam->GetNext(); - } - } - - RefreshPathListCombo(); + gtk_combo_set_popdown_strings( GTK_COMBO( g_pCamListCombo ), combo_list ); + g_list_free( combo_list ); + + // select our current entry in the list + if ( GetCurrentCam() ) { + // stop editing on the current cam + //GetCurrentCam()->GetCam()->stopEdit(); // FIXME: this crashed on creating new cameras, why is it here? + + GList *li = GTK_LIST( GTK_COMBO( g_pCamListCombo )->list )->children; + combo_cam = firstCam; + while ( li && combo_cam ) { + if ( combo_cam == GetCurrentCam() ) { + gtk_list_select_child( GTK_LIST( GTK_COMBO( g_pCamListCombo )->list ), GTK_WIDGET( li->data ) ); + break; + } + li = li->next; + combo_cam = combo_cam->GetNext(); + } + } + + RefreshPathListCombo(); } -static gint ci_camlist_changed( GtkWidget *widget, gpointer data ) -{ - const char *str = gtk_entry_get_text( GTK_ENTRY(widget) ); +static gint ci_camlist_changed( GtkWidget *widget, gpointer data ){ + const char *str = gtk_entry_get_text( GTK_ENTRY( widget ) ); - CCamera *combo_cam = firstCam; - while( str && combo_cam ) { - //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) + CCamera *combo_cam = firstCam; + while ( str && combo_cam ) { + //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) //if( combo_cam->HasBeenSaved() ) { - if( !strcmp( str, combo_cam->GetFileName() ) ) - break; + if ( !strcmp( str, combo_cam->GetFileName() ) ) { + break; + } /*} else { - char buf[128]; - sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); - if( !strcmp( str, buf ) ) - //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) - break; - }*/ - - combo_cam = combo_cam->GetNext(); - } + char buf[128]; + sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); + if( !strcmp( str, buf ) ) + //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) + break; + }*/ + + combo_cam = combo_cam->GetNext(); + } - SetCurrentCam( combo_cam ); + SetCurrentCam( combo_cam ); - if( g_pCamType ) { - if( GetCurrentCam() ) { + if ( g_pCamType ) { + if ( GetCurrentCam() ) { // Fill in our widgets fields for this camera char buf[128]; // Set Name - gtk_entry_set_text( GTK_ENTRY(g_pCamName), GetCurrentCam()->GetCam()->getName() ); + gtk_entry_set_text( GTK_ENTRY( g_pCamName ), GetCurrentCam()->GetCam()->getName() ); // Set type gtk_label_set_text( g_pCamType, GetCurrentCam()->GetCam()->getPositionObj()->typeStr() ); // Set duration sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getBaseTime() ); - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), buf ); + gtk_entry_set_text( GTK_ENTRY( g_pSecondsEntry ), buf ); sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getTotalTime() ); gtk_label_set_text( g_pCurrentTime, "0.00" ); @@ -722,15 +730,16 @@ static gint ci_camlist_changed( GtkWidget *widget, gpointer data ) gtk_adjustment_set_value( g_pTimeLine, 0.f ); g_pTimeLine->upper = GetCurrentCam()->GetCam()->getTotalTime() * 1000; - } else { + } + else { // Set Name - gtk_entry_set_text( GTK_ENTRY(g_pCamName), "" ); + gtk_entry_set_text( GTK_ENTRY( g_pCamName ), "" ); // Set type gtk_label_set_text( g_pCamType, "" ); // Set duration - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), "30.00" ); + gtk_entry_set_text( GTK_ENTRY( g_pSecondsEntry ), "30.00" ); gtk_label_set_text( g_pCurrentTime, "0.00" ); gtk_label_set_text( g_pTotalTime, "30.00" ); @@ -743,50 +752,51 @@ static gint ci_camlist_changed( GtkWidget *widget, gpointer data ) RefreshEventList(); } - RefreshPathListCombo(); + RefreshPathListCombo(); - // start edit mode - g_iActiveTarget = -1; - if( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) - DoStartEdit( GetCurrentCam() ); + // start edit mode + g_iActiveTarget = -1; + if ( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) { + DoStartEdit( GetCurrentCam() ); + } - return TRUE; + return TRUE; } enum camEventType { EVENT_NA = 0x00, - EVENT_WAIT, // - EVENT_TARGETWAIT, // - EVENT_SPEED, // - EVENT_TARGET, // char(name) - EVENT_SNAPTARGET, // - EVENT_FOV, // int(time), int(targetfov) - EVENT_CMD, // - EVENT_TRIGGER, // - EVENT_STOP, // - EVENT_CAMERA, // - EVENT_FADEOUT, // int(time) - EVENT_FADEIN, // int(time) - EVENT_FEATHER, // - EVENT_COUNT + EVENT_WAIT, // + EVENT_TARGETWAIT, // + EVENT_SPEED, // + EVENT_TARGET, // char(name) + EVENT_SNAPTARGET, // + EVENT_FOV, // int(time), int(targetfov) + EVENT_CMD, // + EVENT_TRIGGER, // + EVENT_STOP, // + EVENT_CAMERA, // + EVENT_FADEOUT, // int(time) + EVENT_FADEIN, // int(time) + EVENT_FEATHER, // + EVENT_COUNT }; // { requires parameters, enabled } const bool camEventFlags[][2] = { - { false, false }, - { false, true }, - { false, false }, - { false, false }, - { true, true }, - { false, false }, - { true, true }, - { false, false }, - { false, false }, - { false, true }, - { true, true }, - { true, true }, - { true, true }, - { false, true }, + { false, false }, + { false, true }, + { false, false }, + { false, false }, + { true, true }, + { false, false }, + { true, true }, + { false, false }, + { false, false }, + { false, true }, + { true, true }, + { true, true }, + { true, true }, + { false, true }, }; const char *camEventStr[] = { @@ -800,164 +810,165 @@ const char *camEventStr[] = { "Run Script", "Trigger", "Stop", - "Change to Camera (or ", + "Change to Camera (or ", "Fade Out ", "Fade In ", "Feather" }; -static gint ci_add( GtkWidget *widget, gpointer data ) -{ +static gint ci_add( GtkWidget *widget, gpointer data ){ GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame, *parameters; GtkWidget *eventWidget[EVENT_COUNT]; EMessageBoxReturn ret; - int i, loop = 1; + int i, loop = 1; GSList *eventTypeRadio = NULL; // char buf[128]; - if( !GetCurrentCam() ) + if ( !GetCurrentCam() ) { return TRUE; + } // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Add Event" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( window ), "Add Event" ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); + g_object_set_data( G_OBJECT( window ), "loop", &loop ); + g_object_set_data( G_OBJECT( window ), "ret", &ret ); - gtk_widget_realize (window); + gtk_widget_realize( window ); // fill the window vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_container_add( GTK_CONTAINER( window ), vbox ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); + frame = gtk_frame_new( "Type" ); + gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); + gtk_widget_show( frame ); vbox2 = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 5 ); gtk_widget_show( vbox2 ); // -------------------------- // - for( i = 1; i < EVENT_COUNT; i++ ) { + for ( i = 1; i < EVENT_COUNT; i++ ) { eventWidget[i] = gtk_radio_button_new_with_label( eventTypeRadio, camEventStr[i] ); gtk_box_pack_start( GTK_BOX( vbox2 ), eventWidget[i], FALSE, FALSE, 3 ); gtk_widget_show( eventWidget[i] ); eventTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( eventWidget[i] ) ); - if( camEventFlags[i][1] == false ) - gtk_widget_set_sensitive (eventWidget[i], FALSE); + if ( camEventFlags[i][1] == false ) { + gtk_widget_set_sensitive( eventWidget[i], FALSE ); + } } - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Parameters:" ); + w = gtk_label_new( "Parameters:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - parameters = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), parameters, TRUE, TRUE, 0 ); - gtk_widget_show( parameters ); + parameters = gtk_entry_new(); + gtk_box_pack_start( GTK_BOX( hbox ), parameters, TRUE, TRUE, 0 ); + gtk_widget_show( parameters ); - // -------------------------- // + // -------------------------- // - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); + gtk_widget_show( w ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); + gtk_widget_show( w ); ret = eIDCANCEL; // -------------------------- // - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); + gtk_window_set_position( GTK_WINDOW( window ),GTK_WIN_POS_CENTER ); + gtk_widget_show( window ); + gtk_grab_add( window ); bool dialogError = TRUE; - while (dialogError) { + while ( dialogError ) { loop = 1; - while (loop) - gtk_main_iteration (); - + while ( loop ) + gtk_main_iteration(); + dialogError = FALSE; - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(parameters) ); + if ( ret == eIDOK ) { + const char *str = gtk_entry_get_text( GTK_ENTRY( parameters ) ); - if( !camEventFlags[i][0] || ( str && str[0] ) ) { + if ( !camEventFlags[i][0] || ( str && str[0] ) ) { int type = 0; // GList *li; - for( type = 1; type < EVENT_COUNT; type++ ) { - if( gtk_toggle_button_get_active( (GtkToggleButton*)eventWidget[type] ) ) + for ( type = 1; type < EVENT_COUNT; type++ ) { + if ( gtk_toggle_button_get_active( (GtkToggleButton*)eventWidget[type] ) ) { break; + } } // Add the event - GetCurrentCam()->GetCam()->addEvent( static_cast(type), str, (long)(g_pTimeLine->value) ); + GetCurrentCam()->GetCam()->addEvent( static_cast( type ), str, (long)( g_pTimeLine->value ) ); // Refresh event list RefreshEventList(); - } else { + } + else { dialogError = TRUE; } } } - gtk_grab_remove (window); - gtk_widget_destroy (window); + gtk_grab_remove( window ); + gtk_widget_destroy( window ); - return TRUE; + return TRUE; } -static gint ci_del( GtkWidget *widget, gpointer data ) -{ +static gint ci_del( GtkWidget *widget, gpointer data ){ // TODO: add support to splines lib - if( GetCurrentCam() && GTK_CLIST(g_pEventsList)->focus_row >= 0 ) { - GetCurrentCam()->GetCam()->removeEvent( GTK_CLIST(g_pEventsList)->focus_row ); + if ( GetCurrentCam() && GTK_CLIST( g_pEventsList )->focus_row >= 0 ) { + GetCurrentCam()->GetCam()->removeEvent( GTK_CLIST( g_pEventsList )->focus_row ); // Refresh event list RefreshEventList(); } - return TRUE; + return TRUE; } -static gint ci_timeline_changed( GtkAdjustment *adjustment ) -{ +static gint ci_timeline_changed( GtkAdjustment *adjustment ){ char buf[128]; sprintf( buf, "%.2f", adjustment->value / 1000.f ); @@ -966,391 +977,390 @@ static gint ci_timeline_changed( GtkAdjustment *adjustment ) // FIXME: this will never work completely perfect. Startcamera calls buildcamera, which sets all events to 'nottriggered'. // So if you have a wait at the end of the path, this will go to nontriggered immediately when you go over it and the camera // will have no idea where on the track it should be. - if( GetCurrentCam() && gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(g_pTrackCamera) ) ) { + if ( GetCurrentCam() && gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( g_pTrackCamera ) ) ) { float fov; - vec3_t origin = { 0.0f, 0.0f, 0.0f }, dir = { 0.0f, 0.0f, 0.0f}, angles; + vec3_t origin = { 0.0f, 0.0f, 0.0f }, dir = { 0.0f, 0.0f, 0.0f}, angles; - GetCurrentCam()->GetCam()->startCamera( 0 ); + GetCurrentCam()->GetCam()->startCamera( 0 ); - GetCurrentCam()->GetCam()->getCameraInfo( (long)(adjustment->value), &origin[0], &dir[0], &fov ); - VectorSet( angles, asin (dir[2])*180/3.14159, atan2 (dir[1], dir[0])*180/3.14159, 0 ); - g_CameraTable.m_pfnSetCamera( origin, angles ); - } + GetCurrentCam()->GetCam()->getCameraInfo( (long)( adjustment->value ), &origin[0], &dir[0], &fov ); + VectorSet( angles, asin( dir[2] ) * 180 / 3.14159, atan2( dir[1], dir[0] ) * 180 / 3.14159, 0 ); + g_CameraTable.m_pfnSetCamera( origin, angles ); + } return TRUE; } -GtkWidget *CreateCameraInspectorDialog( void ) -{ - GtkWidget *window, *w, *vbox, *hbox, *table, *frame; +GtkWidget *CreateCameraInspectorDialog( void ){ + GtkWidget *window, *w, *vbox, *hbox, *table, *frame; - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Camera Inspector" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( ci_close ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); + // create the window + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( window ), "Camera Inspector" ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", GTK_SIGNAL_FUNC( ci_close ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); // gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pRadiantWnd ) ); + gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pRadiantWnd ) ); - // don't use show, as you don't want to have it displayed on startup ;-) - gtk_widget_realize( window ); + // don't use show, as you don't want to have it displayed on startup ;-) + gtk_widget_realize( window ); - // fill the window + // fill the window - // the table - // -------------------------- // + // the table + // -------------------------- // - table = gtk_table_new( 3, 2, FALSE ); - gtk_widget_show( table ); - gtk_container_add( GTK_CONTAINER( window ), table ); - gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); - gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); - gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + table = gtk_table_new( 3, 2, FALSE ); + gtk_widget_show( table ); + gtk_container_add( GTK_CONTAINER( window ), table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); - // the properties column + // the properties column // -------------------------- // vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "File:" ); + w = gtk_label_new( "File:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - g_pCamListCombo = gtk_combo_new(); - gtk_box_pack_start (GTK_BOX( hbox ), g_pCamListCombo, TRUE, TRUE, 0); - gtk_widget_show( g_pCamListCombo ); + g_pCamListCombo = gtk_combo_new(); + gtk_box_pack_start( GTK_BOX( hbox ), g_pCamListCombo, TRUE, TRUE, 0 ); + gtk_widget_show( g_pCamListCombo ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); w = gtk_label_new( "Name:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - g_pCamName = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), g_pCamName, FALSE, FALSE, 0 ); - gtk_widget_show( g_pCamName ); + g_pCamName = gtk_entry_new(); + gtk_box_pack_start( GTK_BOX( hbox ), g_pCamName, FALSE, FALSE, 0 ); + gtk_widget_show( g_pCamName ); - w = gtk_label_new( "Type: " ); + w = gtk_label_new( "Type: " ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - w = gtk_label_new( "" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); g_pCamType = GTK_LABEL( w ); - RefreshCamListCombo(); + RefreshCamListCombo(); - gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO(g_pCamListCombo)->entry ), FALSE ); - gtk_signal_connect( GTK_OBJECT(GTK_COMBO(g_pCamListCombo)->entry), "changed", GTK_SIGNAL_FUNC( ci_camlist_changed ), NULL ); + gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO( g_pCamListCombo )->entry ), FALSE ); + gtk_signal_connect( GTK_OBJECT( GTK_COMBO( g_pCamListCombo )->entry ), "changed", GTK_SIGNAL_FUNC( ci_camlist_changed ), NULL ); - // -------------------------- // + // -------------------------- // - frame = gtk_frame_new( "Path and Target editing" ); - gtk_widget_show( frame ); - gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + frame = gtk_frame_new( "Path and Target editing" ); + gtk_widget_show( frame ); + gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox ); - gtk_container_set_border_width( GTK_CONTAINER (vbox), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Edit:" ); + w = gtk_label_new( "Edit:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - g_pPathListCombo = gtk_combo_new(); - gtk_box_pack_start (GTK_BOX( hbox ), g_pPathListCombo, TRUE, TRUE, 0); - gtk_widget_show( g_pPathListCombo ); + g_pPathListCombo = gtk_combo_new(); + gtk_box_pack_start( GTK_BOX( hbox ), g_pPathListCombo, TRUE, TRUE, 0 ); + gtk_widget_show( g_pPathListCombo ); - RefreshPathListCombo(); + RefreshPathListCombo(); - gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO(g_pPathListCombo)->entry ), FALSE ); - gtk_signal_connect( GTK_OBJECT(GTK_COMBO(g_pPathListCombo)->entry), "changed", GTK_SIGNAL_FUNC( ci_pathlist_changed ), NULL ); + gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO( g_pPathListCombo )->entry ), FALSE ); + gtk_signal_connect( GTK_OBJECT( GTK_COMBO( g_pPathListCombo )->entry ), "changed", GTK_SIGNAL_FUNC( ci_pathlist_changed ), NULL ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); g_pEditModeEditRadioButton = gtk_radio_button_new_with_label( g_pEditTypeRadio, "Edit Points" ); gtk_box_pack_start( GTK_BOX( hbox ), g_pEditModeEditRadioButton, FALSE, FALSE, 3 ); - gtk_widget_show( g_pEditModeEditRadioButton ); - g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeEditRadioButton ) ); + gtk_widget_show( g_pEditModeEditRadioButton ); + g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeEditRadioButton ) ); gtk_signal_connect( GTK_OBJECT( g_pEditModeEditRadioButton ), "clicked", GTK_SIGNAL_FUNC( ci_editmode_edit ), NULL ); g_pEditModeAddRadioButton = gtk_radio_button_new_with_label( g_pEditTypeRadio, "Add Points" ); gtk_box_pack_start( GTK_BOX( hbox ), g_pEditModeAddRadioButton, FALSE, FALSE, 3 ); - gtk_widget_show( g_pEditModeAddRadioButton ); - g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeAddRadioButton ) ); + gtk_widget_show( g_pEditModeAddRadioButton ); + g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeAddRadioButton ) ); gtk_signal_connect( GTK_OBJECT( g_pEditModeAddRadioButton ), "clicked", GTK_SIGNAL_FUNC( ci_editmode_add ), NULL ); // see if we should use a different default - if( g_iEditMode == 1 ) { + if ( g_iEditMode == 1 ) { // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_pEditModeAddRadioButton ), TRUE ); } - w = gtk_label_new( "Type: " ); + w = gtk_label_new( "Type: " ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - w = gtk_label_new( "" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); g_pPathType = GTK_LABEL( w ); - // -------------------------- // + // -------------------------- // hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); w = gtk_button_new_with_label( "Rename..." ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_rename ), NULL ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Add Target..." ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_add_target ), NULL ); gtk_widget_show( w ); // not available in splines library /*w = gtk_button_new_with_label( "Delete Selected" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_delete_selected ), NULL ); - gtk_widget_show( w ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_delete_selected ), NULL ); + gtk_widget_show( w ); - w = gtk_button_new_with_label( "Select All" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_select_all ), NULL ); - gtk_widget_show( w );*/ + w = gtk_button_new_with_label( "Select All" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_select_all ), NULL ); + gtk_widget_show( w );*/ - // -------------------------- // + // -------------------------- // - frame = gtk_frame_new( "Time" ); - gtk_widget_show( frame ); - gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + frame = gtk_frame_new( "Time" ); + gtk_widget_show( frame ); + gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); vbox = gtk_vbox_new( FALSE, 5 ); gtk_container_add( GTK_CONTAINER( frame ), vbox ); - gtk_container_set_border_width( GTK_CONTAINER (vbox), 5 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); gtk_widget_show( vbox ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Length (seconds):" ); + w = gtk_label_new( "Length (seconds):" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - g_pSecondsEntry = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), g_pSecondsEntry, FALSE, FALSE, 0 ); - gtk_widget_show( g_pSecondsEntry ); + g_pSecondsEntry = gtk_entry_new(); + gtk_box_pack_start( GTK_BOX( hbox ), g_pSecondsEntry, FALSE, FALSE, 0 ); + gtk_widget_show( g_pSecondsEntry ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Current Time: " ); + w = gtk_label_new( "Current Time: " ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - w = gtk_label_new( "0.00" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "0.00" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); g_pCurrentTime = GTK_LABEL( w ); - w = gtk_label_new( " of " ); + w = gtk_label_new( " of " ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - w = gtk_label_new( "0.00" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); + w = gtk_label_new( "0.00" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); + gtk_widget_show( w ); g_pTotalTime = GTK_LABEL( w ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); g_pTimeLine = GTK_ADJUSTMENT( gtk_adjustment_new( 0, 0, 30000, 100, 250, 0 ) ); - gtk_signal_connect( GTK_OBJECT(g_pTimeLine), "value_changed", GTK_SIGNAL_FUNC( ci_timeline_changed ), NULL ); - w = gtk_hscale_new( g_pTimeLine ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_widget_show( w ); - gtk_scale_set_draw_value( GTK_SCALE( w ), FALSE ); + gtk_signal_connect( GTK_OBJECT( g_pTimeLine ), "value_changed", GTK_SIGNAL_FUNC( ci_timeline_changed ), NULL ); + w = gtk_hscale_new( g_pTimeLine ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_widget_show( w ); + gtk_scale_set_draw_value( GTK_SCALE( w ), FALSE ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - g_pTrackCamera = gtk_check_button_new_with_label( "Track Camera" ); - gtk_box_pack_start( GTK_BOX( hbox ), g_pTrackCamera, FALSE, FALSE, 0 ); - gtk_widget_show( g_pTrackCamera ); + g_pTrackCamera = gtk_check_button_new_with_label( "Track Camera" ); + gtk_box_pack_start( GTK_BOX( hbox ), g_pTrackCamera, FALSE, FALSE, 0 ); + gtk_widget_show( g_pTrackCamera ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_label_new( "Events:" ); + w = gtk_label_new( "Events:" ); gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); gtk_widget_show( w ); - // -------------------------- // + // -------------------------- // - hbox = gtk_hbox_new( FALSE, 5 ); + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); gtk_widget_show( hbox ); - w = gtk_scrolled_window_new( NULL, NULL ); - gtk_widget_set_usize( w, 0, 150 ); - gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( w ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_widget_show( w ); - - g_pEventsList = gtk_clist_new( 3 ); - gtk_container_add( GTK_CONTAINER(w), g_pEventsList); - //gtk_signal_connect( GTK_OBJECT(g_pEventsList), "select_row", GTK_SIGNAL_FUNC (proplist_select_row), NULL); - gtk_clist_set_selection_mode( GTK_CLIST(g_pEventsList), GTK_SELECTION_BROWSE ); - gtk_clist_column_titles_hide( GTK_CLIST(g_pEventsList) ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 0, TRUE ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 1, TRUE ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 2, TRUE ); + w = gtk_scrolled_window_new( NULL, NULL ); + gtk_widget_set_usize( w, 0, 150 ); + gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( w ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_widget_show( w ); + + g_pEventsList = gtk_clist_new( 3 ); + gtk_container_add( GTK_CONTAINER( w ), g_pEventsList ); + //gtk_signal_connect( GTK_OBJECT(g_pEventsList), "select_row", GTK_SIGNAL_FUNC (proplist_select_row), NULL); + gtk_clist_set_selection_mode( GTK_CLIST( g_pEventsList ), GTK_SELECTION_BROWSE ); + gtk_clist_column_titles_hide( GTK_CLIST( g_pEventsList ) ); + gtk_clist_set_column_auto_resize( GTK_CLIST( g_pEventsList ), 0, TRUE ); + gtk_clist_set_column_auto_resize( GTK_CLIST( g_pEventsList ), 1, TRUE ); + gtk_clist_set_column_auto_resize( GTK_CLIST( g_pEventsList ), 2, TRUE ); gtk_widget_show( g_pEventsList ); - vbox = gtk_vbox_new( FALSE, 5 ); + vbox = gtk_vbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( hbox ), vbox, FALSE, FALSE, 0 ); gtk_widget_show( vbox ); w = gtk_button_new_with_label( "Add..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_add ), NULL ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Del" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_del ), NULL ); gtk_widget_show( w ); - // -------------------------- // + // -------------------------- // - /*/ - | - | - | - */ + /*/ + | + | + | + * / - // the buttons column - // -------------------------- // + // the buttons column + // -------------------------- // - vbox = gtk_vbox_new( FALSE, 5 ); + vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); w = gtk_button_new_with_label( "New..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_new ), NULL ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Load..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_load ), NULL ); gtk_widget_show( w ); - // -------------------------- // + // -------------------------- // - vbox = gtk_vbox_new( FALSE, 5 ); + vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); w = gtk_button_new_with_label( "Save..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_save ), NULL ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Unload" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_unload ), NULL ); gtk_widget_show( w ); - - hbox = gtk_hbox_new( FALSE, 5 ); + + hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); gtk_widget_show( hbox ); - w = gtk_button_new_with_label( "Apply" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + w = gtk_button_new_with_label( "Apply" ); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_apply ), NULL ); gtk_widget_show( w ); w = gtk_button_new_with_label( "Preview" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_preview ), NULL ); gtk_widget_show( w ); - // -------------------------- // + // -------------------------- // - vbox = gtk_vbox_new( FALSE, 5 ); + vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); + gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 2, 3, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); hbox = gtk_hbox_new( FALSE, 5 ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); gtk_widget_show( hbox ); w = gtk_button_new_with_label( "Close" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_close ), NULL ); GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); gtk_widget_grab_default( w ); gtk_widget_show( w ); - // -------------------------- // + // -------------------------- // - return window; + return window; } diff --git a/contrib/camera/dialogs.h b/contrib/camera/dialogs.h index 4df27eae..9b8f9036 100644 --- a/contrib/camera/dialogs.h +++ b/contrib/camera/dialogs.h @@ -1,36 +1,36 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ struct TwinWidget { - GtkWidget* one; - GtkWidget* two; + GtkWidget* one; + GtkWidget* two; }; -void dialog_button_callback (GtkWidget *widget, gpointer data); -gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data); +void dialog_button_callback( GtkWidget *widget, gpointer data ); +gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ); //void dialog_button_callback_settex (GtkWidget *widget, gpointer data); void RefreshCamListCombo( void ); diff --git a/contrib/camera/dialogs_common.cpp b/contrib/camera/dialogs_common.cpp index 43a4e70e..f53da8d0 100644 --- a/contrib/camera/dialogs_common.cpp +++ b/contrib/camera/dialogs_common.cpp @@ -1,50 +1,48 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" -void dialog_button_callback (GtkWidget *widget, gpointer data) -{ +void dialog_button_callback( GtkWidget *widget, gpointer data ){ GtkWidget *parent; int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - + + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + ret = (int*)g_object_get_data( G_OBJECT( parent ), "ret" ); + *loop = 0; - *ret = gpointer_to_int (data); + *ret = gpointer_to_int( data ); } -gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ +gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); + + gtk_widget_hide( widget ); + loop = (int*)g_object_get_data( G_OBJECT( widget ), "loop" ); *loop = 0; return TRUE; diff --git a/contrib/camera/funchandlers.cpp b/contrib/camera/funchandlers.cpp index 2e9d17bb..4134a889 100644 --- a/contrib/camera/funchandlers.cpp +++ b/contrib/camera/funchandlers.cpp @@ -1,49 +1,47 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" extern GtkWidget *g_pEditModeAddRadioButton; -char* Q_realpath(const char *path, char *resolved_path, size_t size) -{ -#if defined(POSIX) - return realpath(path, resolved_path); -#elif defined(WIN32) - return _fullpath(resolved_path, path, size); +char* Q_realpath( const char *path, char *resolved_path, size_t size ){ +#if defined( POSIX ) + return realpath( path, resolved_path ); +#elif defined( WIN32 ) + return _fullpath( resolved_path, path, size ); #else #error "unsupported platform" #endif } -static void DoNewCamera( idCameraPosition::positionType type ) -{ +static void DoNewCamera( idCameraPosition::positionType type ){ CCamera *cam = AllocCam(); - if( cam ) { + if ( cam ) { char buf[128]; sprintf( buf, "camera%i", cam->GetCamNum() ); @@ -58,173 +56,182 @@ static void DoNewCamera( idCameraPosition::positionType type ) RefreshCamListCombo(); // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_pEditModeAddRadioButton ), TRUE ); // Show the camera inspector DoCameraInspector(); // Start edit mode (if not initiated by DoCameraInspector) - if( !g_bEditOn ) + if ( !g_bEditOn ) { DoStartEdit( GetCurrentCam() ); - } else { - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free cameras available.", "Create Camera Error", eMB_OK ); + } + } + else { + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free cameras available.", "Create Camera Error", eMB_OK ); } } -void DoNewFixedCamera() -{ +void DoNewFixedCamera(){ DoNewCamera( idCameraPosition::FIXED ); } -void DoNewInterpolatedCamera() -{ +void DoNewInterpolatedCamera(){ DoNewCamera( idCameraPosition::INTERPOLATED ); } -void DoNewSplineCamera() -{ +void DoNewSplineCamera(){ DoNewCamera( idCameraPosition::SPLINE ); } -void DoCameraInspector() -{ - gtk_widget_show( g_pCameraInspectorWnd ); +void DoCameraInspector(){ + gtk_widget_show( g_pCameraInspectorWnd ); } -void DoPreviewCamera() -{ - if( GetCurrentCam() ) { +void DoPreviewCamera(){ + if ( GetCurrentCam() ) { g_iPreviewRunning = 1; g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); } } -void DoLoadCamera() -{ - char basepath[PATH_MAX]; - - if( firstCam && firstCam->HasBeenSaved() ) - ExtractFilePath( firstCam->GetFileName(), basepath ); - else - strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); - - const gchar *filename = g_FuncTable.m_pfnFileDialog( (GtkWidget *)g_pRadiantWnd, TRUE, "Open Camera File", basepath, "camera"); - - if( filename ) - { - CCamera *cam = AllocCam(); - char fullpathtofile[PATH_MAX]; - - if( cam ) { - Q_realpath(filename, fullpathtofile, PATH_MAX); - - // see if this camera file was already loaded - CCamera *checkCam = firstCam->GetNext(); // not the first one as we just allocated it - while( checkCam ) { - if( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { - char error[PATH_MAX+64]; - FreeCam( cam ); - sprintf( error, "Camera file \'%s\' is already loaded", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); - //g_free( filename ); - return; - } - checkCam = checkCam->GetNext(); - } - - if( loadCamera( cam->GetCamNum(), fullpathtofile ) ) { +void DoLoadCamera(){ + char basepath[PATH_MAX]; + + if ( firstCam && firstCam->HasBeenSaved() ) { + ExtractFilePath( firstCam->GetFileName(), basepath ); + } + else{ + strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); + } + + const gchar *filename = g_FuncTable.m_pfnFileDialog( (GtkWidget *)g_pRadiantWnd, TRUE, "Open Camera File", basepath, "camera" ); + + if ( filename ) { + CCamera *cam = AllocCam(); + char fullpathtofile[PATH_MAX]; + + if ( cam ) { + Q_realpath( filename, fullpathtofile, PATH_MAX ); + + // see if this camera file was already loaded + CCamera *checkCam = firstCam->GetNext(); // not the first one as we just allocated it + while ( checkCam ) { + if ( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { + char error[PATH_MAX + 64]; + FreeCam( cam ); + sprintf( error, "Camera file \'%s\' is already loaded", fullpathtofile ); + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); + //g_free( filename ); + return; + } + checkCam = checkCam->GetNext(); + } + + if ( loadCamera( cam->GetCamNum(), fullpathtofile ) ) { cam->GetCam()->buildCamera(); - cam->SetFileName( filename, true ); - SetCurrentCam( cam ); - RefreshCamListCombo(); - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } else { - char error[PATH_MAX+64]; - FreeCam( cam ); - sprintf( error, "An error occured during the loading of \'%s\'", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); - } - - //g_free( filename ); - } else { - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free camera slots available", "Load error", eMB_OK ); - } + cam->SetFileName( filename, true ); + SetCurrentCam( cam ); + RefreshCamListCombo(); + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + } + else { + char error[PATH_MAX + 64]; + FreeCam( cam ); + sprintf( error, "An error occured during the loading of \'%s\'", fullpathtofile ); + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); + } + + //g_free( filename ); + } + else { + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free camera slots available", "Load error", eMB_OK ); + } } } void DoSaveCamera() { - char basepath[PATH_MAX]; + char basepath[PATH_MAX]; - if( !GetCurrentCam() ) - return; + if ( !GetCurrentCam() ) { + return; + } - if( GetCurrentCam()->GetFileName()[0] ) - ExtractFilePath( GetCurrentCam()->GetFileName(), basepath ); - else - strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); + if ( GetCurrentCam()->GetFileName()[0] ) { + ExtractFilePath( GetCurrentCam()->GetFileName(), basepath ); + } + else{ + strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); + } - const gchar *filename = g_FuncTable.m_pfnFileDialog( g_pRadiantWnd, FALSE, "Save Camera File", basepath, "camera"); + const gchar *filename = g_FuncTable.m_pfnFileDialog( g_pRadiantWnd, FALSE, "Save Camera File", basepath, "camera" ); - if( filename ) { - char fullpathtofile[PATH_MAX + 8]; + if ( filename ) { + char fullpathtofile[PATH_MAX + 8]; - Q_realpath(filename, fullpathtofile, PATH_MAX); + Q_realpath( filename, fullpathtofile, PATH_MAX ); // File dialog from windows (and maybe the gtk one from radiant) doesn't handle default extensions properly. // Add extension and check again if file exists - if( strcmp( fullpathtofile + (strlen(fullpathtofile) - 7), ".camera" ) ) { + if ( strcmp( fullpathtofile + ( strlen( fullpathtofile ) - 7 ), ".camera" ) ) { strcat( fullpathtofile, ".camera" ); - if( FileExists( fullpathtofile ) ) { - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "File already exists.\nOverwrite?", "Save Camera File", eMB_YESNO ) == eIDNO ) + if ( FileExists( fullpathtofile ) ) { + if ( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "File already exists.\nOverwrite?", "Save Camera File", eMB_YESNO ) == eIDNO ) { return; + } } } - // see if this camera file was already loaded - CCamera *checkCam = firstCam; - while( checkCam ) { - if( checkCam == GetCurrentCam() ) { - checkCam = checkCam->GetNext(); - if( !checkCam ) // we only have one camera file opened so no need to check further + // see if this camera file was already loaded + CCamera *checkCam = firstCam; + while ( checkCam ) { + if ( checkCam == GetCurrentCam() ) { + checkCam = checkCam->GetNext(); + if ( !checkCam ) { // we only have one camera file opened so no need to check further break; - } else if( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { - char error[PATH_MAX+64]; - sprintf( error, "Camera file \'%s\' is currently loaded by NetRadiant.\nPlease select a different filename.", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Save error", eMB_OK ); - return; - } - checkCam = checkCam->GetNext(); - } - - // FIXME: check for existing directory - - GetCurrentCam()->GetCam()->save( fullpathtofile ); + } + } + else if ( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { + char error[PATH_MAX + 64]; + sprintf( error, "Camera file \'%s\' is currently loaded by NetRadiant.\nPlease select a different filename.", fullpathtofile ); + g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Save error", eMB_OK ); + return; + } + checkCam = checkCam->GetNext(); + } + + // FIXME: check for existing directory + + GetCurrentCam()->GetCam()->save( fullpathtofile ); GetCurrentCam()->SetFileName( fullpathtofile, true ); RefreshCamListCombo(); - } + } } void DoUnloadCamera() { - if( !GetCurrentCam() ) - return; + if ( !GetCurrentCam() ) { + return; + } - if( !GetCurrentCam()->HasBeenSaved() ) { - char buf[PATH_MAX+64]; + if ( !GetCurrentCam()->HasBeenSaved() ) { + char buf[PATH_MAX + 64]; sprintf( buf, "Do you want to save the changes for camera '%s'?", GetCurrentCam()->GetCam()->getName() ); - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) + if ( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) { DoSaveCamera(); - } else if( GetCurrentCam()->HasBeenSaved() == 2 ) { - char buf[PATH_MAX+64]; + } + } + else if ( GetCurrentCam()->HasBeenSaved() == 2 ) { + char buf[PATH_MAX + 64]; sprintf( buf, "Do you want to save the changes made to camera file '%s'?", GetCurrentCam()->GetFileName() ); - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) + if ( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) { DoSaveCamera(); + } } - if( g_pCurrentEditCam ) { - DoStopEdit(); - g_pCurrentEditCam = NULL; - } + if ( g_pCurrentEditCam ) { + DoStopEdit(); + g_pCurrentEditCam = NULL; + } FreeCam( GetCurrentCam() ); SetCurrentCam( NULL ); @@ -234,38 +241,39 @@ void DoUnloadCamera() { CCamera *g_pCurrentEditCam = NULL; void DoStartEdit( CCamera *cam ) { - if( g_pCurrentEditCam ) { - DoStopEdit(); - g_pCurrentEditCam = NULL; - } + if ( g_pCurrentEditCam ) { + DoStopEdit(); + g_pCurrentEditCam = NULL; + } - if( cam ) { - g_bEditOn = true; + if ( cam ) { + g_bEditOn = true; - if( !Listener ) - Listener = new CListener; + if ( !Listener ) { + Listener = new CListener; + } - cam->GetCam()->startEdit( g_iActiveTarget < 0 ? true : false ); + cam->GetCam()->startEdit( g_iActiveTarget < 0 ? true : false ); - g_pCurrentEditCam = cam; + g_pCurrentEditCam = cam; - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + } } void DoStopEdit( void ) { - g_bEditOn = false; + g_bEditOn = false; - if( Listener ) { - delete Listener; - Listener = NULL; - } + if ( Listener ) { + delete Listener; + Listener = NULL; + } - if( g_pCurrentEditCam ) { - // stop editing on the current cam - g_pCurrentEditCam->GetCam()->stopEdit(); - g_pCurrentEditCam = NULL; + if ( g_pCurrentEditCam ) { + // stop editing on the current cam + g_pCurrentEditCam->GetCam()->stopEdit(); + g_pCurrentEditCam = NULL; - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + } } diff --git a/contrib/camera/funchandlers.h b/contrib/camera/funchandlers.h index 0c97f610..a268315b 100644 --- a/contrib/camera/funchandlers.h +++ b/contrib/camera/funchandlers.h @@ -1,28 +1,28 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ void DoNewFixedCamera(); void DoNewInterpolatedCamera(); @@ -34,4 +34,3 @@ void DoSaveCamera(); void DoUnloadCamera(); void DoStartEdit( CCamera *cam ); void DoStopEdit( void ); - diff --git a/contrib/camera/listener.cpp b/contrib/camera/listener.cpp index f3169b8d..b9f5fcf9 100644 --- a/contrib/camera/listener.cpp +++ b/contrib/camera/listener.cpp @@ -1,149 +1,148 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" -CListener::CListener() -{ +CListener::CListener(){ refCount = 1; m_bHooked = FALSE; - m_bLeftMBPressed = m_bRightMBPressed = m_bMiddleMBPressed = false; + m_bLeftMBPressed = m_bRightMBPressed = m_bMiddleMBPressed = false; - oldValid = false; + oldValid = false; - Register(); + Register(); } -CListener::~CListener() -{ +CListener::~CListener(){ UnRegister(); } -void CListener::Register() -{ +void CListener::Register(){ g_UITable.m_pfnHookWindow( this ); - g_pXYWndWrapper = g_UITable.m_pfnGetXYWndWrapper(); + g_pXYWndWrapper = g_UITable.m_pfnGetXYWndWrapper(); m_bHooked = TRUE; } -void CListener::UnRegister() -{ - if(m_bHooked) - { +void CListener::UnRegister(){ + if ( m_bHooked ) { g_UITable.m_pfnUnHookWindow( this ); - g_pXYWndWrapper= NULL; + g_pXYWndWrapper = NULL; m_bHooked = FALSE; } } -bool CListener::OnMouseMove( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - if( m_bLeftMBPressed && oldValid && g_iEditMode == 0 ) { - vec3_t click, delta; - - g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, click ); - - switch( m_vt ) { - case XY: - VectorSet( delta, click[0] - old_x, click[1] - old_y, 0 ); - old_x = click[0]; old_y = click[1]; - break; - case XZ: - VectorSet( delta, click[0] - old_x, 0, click[2] - old_y ); - old_x = click[0]; old_y = click[2]; - break; - case YZ: - VectorSet( delta, 0, click[1] - old_x, click[2] - old_y ); - old_x = click[1]; old_y = click[2]; - break; - } - - if( g_iActiveTarget < 0 ) - GetCurrentCam()->GetCam()->getPositionObj()->updateSelection( delta[0], delta[1], delta[2] ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->updateSelection( delta[0], delta[1], delta[2] ); +bool CListener::OnMouseMove( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); + + if ( m_bLeftMBPressed && oldValid && g_iEditMode == 0 ) { + vec3_t click, delta; + + g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, click ); + + switch ( m_vt ) { + case XY: + VectorSet( delta, click[0] - old_x, click[1] - old_y, 0 ); + old_x = click[0]; old_y = click[1]; + break; + case XZ: + VectorSet( delta, click[0] - old_x, 0, click[2] - old_y ); + old_x = click[0]; old_y = click[2]; + break; + case YZ: + VectorSet( delta, 0, click[1] - old_x, click[2] - old_y ); + old_x = click[1]; old_y = click[2]; + break; + } + + if ( g_iActiveTarget < 0 ) { + GetCurrentCam()->GetCam()->getPositionObj()->updateSelection( delta[0], delta[1], delta[2] ); + } + else{ + GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->updateSelection( delta[0], delta[1], delta[2] ); + } GetCurrentCam()->HasBeenModified(); - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - return true; - } + return true; + } - return false; + return false; } -bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bLeftMBPressed = true; - oldValid = true; - - vec3_t org, delta; - - g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, org ); - - switch( m_vt ) { - case XY: - old_x = org[0]; old_y = org[1]; org[2] = 64*1024; - VectorSet( delta, 0, 0, -1 ); - break; - case XZ: - old_x = org[0]; old_y = org[2]; org[1] = 64*1024; - VectorSet( delta, 0, -1, 0 ); - break; - case YZ: - old_x = org[1]; old_y = org[2]; org[0] = 64*1024; - VectorSet( delta, -1, 0, 0 ); - break; - } - - if( g_iEditMode == 0 ) { - if( g_iActiveTarget < 0 ) +bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); + + m_bLeftMBPressed = true; + oldValid = true; + + vec3_t org, delta; + + g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, org ); + + switch ( m_vt ) { + case XY: + old_x = org[0]; old_y = org[1]; org[2] = 64 * 1024; + VectorSet( delta, 0, 0, -1 ); + break; + case XZ: + old_x = org[0]; old_y = org[2]; org[1] = 64 * 1024; + VectorSet( delta, 0, -1, 0 ); + break; + case YZ: + old_x = org[1]; old_y = org[2]; org[0] = 64 * 1024; + VectorSet( delta, -1, 0, 0 ); + break; + } + + if ( g_iEditMode == 0 ) { + if ( g_iActiveTarget < 0 ) { GetCurrentCam()->GetCam()->getPositionObj()->selectPointByRay( org[0], org[1], org[2], delta[0], delta[1], delta[2], true ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->selectPointByRay( org[0], org[1], org[2], delta[0], delta[1], delta[2], true ); - } else if( g_iEditMode == 1 ) { + } + else{ + GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->selectPointByRay( org[0], org[1], org[2], delta[0], delta[1], delta[2], true ); + } + } + else if ( g_iEditMode == 1 ) { idVec3 *lastcoord; idCameraPosition *camera; - if( g_iActiveTarget < 0 ) { + if ( g_iActiveTarget < 0 ) { camera = GetCurrentCam()->GetCam()->getPositionObj(); - } else { - camera = GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget); + } + else { + camera = GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget ); } - if( camera->numPoints() ) { - lastcoord = camera->getPoint( camera->numPoints() -1 ); - switch( m_vt ) { + if ( camera->numPoints() ) { + lastcoord = camera->getPoint( camera->numPoints() - 1 ); + switch ( m_vt ) { case XY: camera->addPoint( org[0], org[1], lastcoord->z ); break; @@ -154,8 +153,9 @@ bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ) camera->addPoint( lastcoord->x, org[1], org[2] ); break; } - } else { - switch( m_vt ) { + } + else { + switch ( m_vt ) { case XY: camera->addPoint( org[0], org[1], 0 ); break; @@ -171,64 +171,61 @@ bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ) GetCurrentCam()->HasBeenModified(); } - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - return true; + return true; //return false; } -bool CListener::OnLButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); +bool CListener::OnLButtonUp( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); - m_bLeftMBPressed = false; - oldValid = false; + m_bLeftMBPressed = false; + oldValid = false; - if( g_iEditMode == 0 ) { - if( g_iActiveTarget < 0 ) + if ( g_iEditMode == 0 ) { + if ( g_iActiveTarget < 0 ) { GetCurrentCam()->GetCam()->getPositionObj()->deselectAll(); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->deselectAll(); + } + else{ + GetCurrentCam()->GetCam()->getActiveTarget( g_iActiveTarget )->deselectAll(); + } - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); + g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); } return false; } -bool CListener::OnRButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); +bool CListener::OnRButtonDown( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); - m_bRightMBPressed = true; + m_bRightMBPressed = true; return false; } -bool CListener::OnRButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); +bool CListener::OnRButtonUp( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); - m_bRightMBPressed = false; + m_bRightMBPressed = false; return false; } -bool CListener::OnMButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); +bool CListener::OnMButtonDown( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); - m_bMiddleMBPressed = true; + m_bMiddleMBPressed = true; return false; } -bool CListener::OnMButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); +bool CListener::OnMButtonUp( unsigned int nFlags, double x, double y ){ + SetViewType( g_pXYWndWrapper->GetViewType() ); - m_bMiddleMBPressed = false; + m_bMiddleMBPressed = false; return false; } diff --git a/contrib/camera/listener.h b/contrib/camera/listener.h index 72bf1fdb..13acd543 100644 --- a/contrib/camera/listener.h +++ b/contrib/camera/listener.h @@ -1,64 +1,73 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ -class CListener : public IWindowListener +class CListener : public IWindowListener { public: - bool OnMouseMove(guint32 nFlags, gdouble x, gdouble y); - bool OnLButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnMButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnRButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnLButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnMButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnRButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnKeyPressed(char *s) { return false; } - bool Paint() { return true; } - void Close() { } - - void UnRegister(); - void Register(); - CListener(); - virtual ~CListener(); +bool OnMouseMove( guint32 nFlags, gdouble x, gdouble y ); +bool OnLButtonDown( guint32 nFlags, gdouble x, gdouble y ); +bool OnMButtonDown( guint32 nFlags, gdouble x, gdouble y ); +bool OnRButtonDown( guint32 nFlags, gdouble x, gdouble y ); +bool OnLButtonUp( guint32 nFlags, gdouble x, gdouble y ); +bool OnMButtonUp( guint32 nFlags, gdouble x, gdouble y ); +bool OnRButtonUp( guint32 nFlags, gdouble x, gdouble y ); +bool OnKeyPressed( char *s ) { return false; } +bool Paint() { return true; } +void Close() { } - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } +void UnRegister(); +void Register(); +CListener(); +virtual ~CListener(); - void SetViewType( VIEWTYPE vt ) { if( m_vt != vt ) oldValid = false; m_vt = vt; } +void IncRef() { refCount++; } +void DecRef() { + refCount--; if ( refCount <= 0 ) { + delete this; + } +} + +void SetViewType( VIEWTYPE vt ) { + if ( m_vt != vt ) { + oldValid = false; + } + m_vt = vt; +} private: - IXYWndWrapper *g_pXYWndWrapper; +IXYWndWrapper *g_pXYWndWrapper; - bool m_bHooked; - int refCount; - VIEWTYPE m_vt; +bool m_bHooked; +int refCount; +VIEWTYPE m_vt; - // mouse button status - bool m_bLeftMBPressed, m_bRightMBPressed, m_bMiddleMBPressed; +// mouse button status +bool m_bLeftMBPressed, m_bRightMBPressed, m_bMiddleMBPressed; - // old mouse coordinates - bool oldValid; - gdouble old_x, old_y; +// old mouse coordinates +bool oldValid; +gdouble old_x, old_y; }; diff --git a/contrib/camera/misc.cpp b/contrib/camera/misc.cpp index 49148248..372dc7bc 100644 --- a/contrib/camera/misc.cpp +++ b/contrib/camera/misc.cpp @@ -1,102 +1,99 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" -void Sys_ERROR( char* text, ... ) -{ - va_list argptr; - char buf[32768]; +void Sys_ERROR( char* text, ... ){ + va_list argptr; + char buf[32768]; - va_start (argptr,text); - vsprintf (buf, text,argptr); - va_end (argptr); + va_start( argptr,text ); + vsprintf( buf, text,argptr ); + va_end( argptr ); - Sys_Printf("Camera::ERROR->%s", buf); + Sys_Printf( "Camera::ERROR->%s", buf ); } -char* UnixToDosPath( char* path ) -{ +char* UnixToDosPath( char* path ){ #ifndef WIN32 return path; #else - for(char* p = path; *p; p++) + for ( char* p = path; *p; p++ ) { - if(*p == '/') + if ( *p == '/' ) { *p = '\\'; + } } return path; #endif } -void ExtractFilePath( const char *path, char *dest ) -{ - const char *src; +void ExtractFilePath( const char *path, char *dest ){ + const char *src; - src = path + strlen(path) - 1; + src = path + strlen( path ) - 1; // // back up until a \ or the start // - while (src != path && *(src-1) != '/' && *(src-1) != '\\') - src--; + while ( src != path && *( src - 1 ) != '/' && *( src - 1 ) != '\\' ) + src--; - memcpy (dest, path, src-path); - dest[src-path] = 0; + memcpy( dest, path, src - path ); + dest[src - path] = 0; } -const char* ExtractFilename( const char* path ) -{ - char* p = strrchr(path, '/'); - if(!p) - { - p = strrchr(path, '\\'); +const char* ExtractFilename( const char* path ){ + char* p = strrchr( path, '/' ); + if ( !p ) { + p = strrchr( path, '\\' ); - if(!p) + if ( !p ) { return path; + } } return ++p; } -int Q_stricmp (const char *s1, const char *s2) { +int Q_stricmp( const char *s1, const char *s2 ) { return string_equal_nocase( s1, s2 ); } /* -============== -FileExists -============== -*/ -bool FileExists (const char *filename) -{ - FILE *f; + ============== + FileExists + ============== + */ +bool FileExists( const char *filename ){ + FILE *f; f = fopen( filename, "r" ); - if( !f ) + if ( !f ) { return false; + } fclose( f ); return true; } @@ -106,56 +103,53 @@ bool FileExists (const char *filename) // empty wrappers, don't really use them here // void Cbuf_AddText( const char *text ) {}; -void Cbuf_Execute (void) {}; +void Cbuf_Execute( void ) {}; // // Common // -void CDECL Com_Error( int level, const char *error, ... ) -{ - va_list argptr; - char buf[32768]; +void CDECL Com_Error( int level, const char *error, ... ){ + va_list argptr; + char buf[32768]; - va_start (argptr,error); - vsprintf (buf, error,argptr); - va_end (argptr); + va_start( argptr,error ); + vsprintf( buf, error,argptr ); + va_end( argptr ); - Sys_Printf("Camera::ERROR->%s", buf); + Sys_Printf( "Camera::ERROR->%s", buf ); } -void CDECL Com_Printf( const char* msg, ... ) -{ - va_list argptr; - char buf[32768]; +void CDECL Com_Printf( const char* msg, ... ){ + va_list argptr; + char buf[32768]; - va_start (argptr,msg); - vsprintf (buf, msg,argptr); - va_end (argptr); + va_start( argptr,msg ); + vsprintf( buf, msg,argptr ); + va_end( argptr ); - Sys_Printf("Camera::%s", buf); + Sys_Printf( "Camera::%s", buf ); } -void CDECL Com_DPrintf( const char* msg, ... ) -{ +void CDECL Com_DPrintf( const char* msg, ... ){ #ifdef _DEBUG - va_list argptr; - char buf[32768]; + va_list argptr; + char buf[32768]; - va_start (argptr,msg); - vsprintf (buf, msg,argptr); - va_end (argptr); + va_start( argptr,msg ); + vsprintf( buf, msg,argptr ); + va_end( argptr ); - Sys_Printf("Camera::%s", buf); + Sys_Printf( "Camera::%s", buf ); #endif } void *Com_Allocate( int bytes ) { - return( malloc( bytes ) ); + return( malloc( bytes ) ); } void Com_Dealloc( void *ptr ) { - free( ptr ); + free( ptr ); } // @@ -168,76 +162,76 @@ void Com_Dealloc( void *ptr ) { #endif int FS_Read( void *buffer, int len, fileHandle_t f ) { - return fread( buffer, len, 1, (FILE *)f ); + return fread( buffer, len, 1, (FILE *)f ); } int FS_Write( const void *buffer, int len, fileHandle_t h ) { - return fwrite( buffer, len, 1, (FILE *)h ); + return fwrite( buffer, len, 1, (FILE *)h ); } int FS_ReadFile( const char *qpath, void **buffer ) { - fileHandle_t h; - byte* buf; - int len; + fileHandle_t h; + byte* buf; + int len; - buf = NULL; + buf = NULL; - len = FS_FOpenFileRead( qpath, &h, qfalse ); + len = FS_FOpenFileRead( qpath, &h, qfalse ); - if( h == 0 ) { - if ( buffer ) { - *buffer = NULL; - } + if ( h == 0 ) { + if ( buffer ) { + *buffer = NULL; + } - return -1; - } + return -1; + } - buf = (byte *)Com_Allocate( len + 1 ); + buf = (byte *)Com_Allocate( len + 1 ); - *buffer = buf; + *buffer = buf; - FS_Read (buf, len, h); + FS_Read( buf, len, h ); - buf[len] = 0; - FS_FCloseFile( h ); + buf[len] = 0; + FS_FCloseFile( h ); - return len; + return len; } void FS_FreeFile( void *buffer ) { - Com_Dealloc( buffer ); + Com_Dealloc( buffer ); } int FS_FOpenFileRead( const char *filename, fileHandle_t *file, bool uniqueFILE ) { - FILE *fh; + FILE *fh; long len; - fh = fopen( filename, "rb" ); - *file = *(fileHandle_t *)&fh; + fh = fopen( filename, "rb" ); + *file = *(fileHandle_t *)&fh; - if( file ) - { - fseek (fh, 0, SEEK_END); - len = ftell (fh); - rewind (fh); - return len; + if ( file ) { + fseek( fh, 0, SEEK_END ); + len = ftell( fh ); + rewind( fh ); + return len; + } + else{ + return -1; } - else - return -1; } fileHandle_t FS_FOpenFileWrite( const char *filename ) { - FILE *fh; - fileHandle_t f; + FILE *fh; + fileHandle_t f; - memset( &f, 0, sizeof(f) ); + memset( &f, 0, sizeof( f ) ); - fh = fopen( filename, "wb" ); + fh = fopen( filename, "wb" ); - f = (fileHandle_t)fh; - return f; + f = (fileHandle_t)fh; + return f; } void FS_FCloseFile( fileHandle_t f ) { - fclose( (FILE *)f ); + fclose( (FILE *)f ); } diff --git a/contrib/camera/misc.h b/contrib/camera/misc.h index 913b7c4a..6e226d33 100644 --- a/contrib/camera/misc.h +++ b/contrib/camera/misc.h @@ -1,42 +1,42 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ void Sys_ERROR( char* text, ... ); char* UnixToDosPath( char* path ); void ExtractFilePath( const char *path, char *dest ); const char* ExtractFilename( const char* path ); -bool FileExists (const char *filename); -int Q_stricmp (const char *s1, const char *s2); +bool FileExists( const char *filename ); +int Q_stricmp( const char *s1, const char *s2 ); typedef int fileHandle_t; extern "C" { // command buffer void Cbuf_AddText( const char *text ); -void Cbuf_Execute (void); +void Cbuf_Execute( void ); // common #ifndef CDECL @@ -64,13 +64,13 @@ void FS_FCloseFile( fileHandle_t f ); } // vectors -#define DotProduct4(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]+(x)[3]*(y)[3]) -#define VectorSubtract4(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2],(c)[3]=(a)[3]-(b)[3]) -#define VectorAdd4(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2],(c)[3]=(a)[3]+(b)[3]) -#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3]) -#define VectorScale4(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s),(o)[3]=(v)[3]*(s)) -#define VectorMA4(v, s, b, o) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s),(o)[3]=(v)[3]+(b)[3]*(s)) +#define DotProduct4( x,y ) ( ( x )[0] * ( y )[0] + ( x )[1] * ( y )[1] + ( x )[2] * ( y )[2] + ( x )[3] * ( y )[3] ) +#define VectorSubtract4( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2],( c )[3] = ( a )[3] - ( b )[3] ) +#define VectorAdd4( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2],( c )[3] = ( a )[3] + ( b )[3] ) +#define VectorCopy4( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) +#define VectorScale4( v, s, o ) ( ( o )[0] = ( v )[0] * ( s ),( o )[1] = ( v )[1] * ( s ),( o )[2] = ( v )[2] * ( s ),( o )[3] = ( v )[3] * ( s ) ) +#define VectorMA4( v, s, b, o ) ( ( o )[0] = ( v )[0] + ( b )[0] * ( s ),( o )[1] = ( v )[1] + ( b )[1] * ( s ),( o )[2] = ( v )[2] + ( b )[2] * ( s ),( o )[3] = ( v )[3] + ( b )[3] * ( s ) ) -#define Vector4Copy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3]) +#define Vector4Copy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) -#define SnapVector(v) {v[0]=(int)v[0];v[1]=(int)v[1];v[2]=(int)v[2];} +#define SnapVector( v ) {v[0] = (int)v[0]; v[1] = (int)v[1]; v[2] = (int)v[2]; } diff --git a/contrib/camera/renderer.cpp b/contrib/camera/renderer.cpp index 08e6664e..ac270836 100644 --- a/contrib/camera/renderer.cpp +++ b/contrib/camera/renderer.cpp @@ -1,44 +1,45 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ #include "camera.h" CRenderer::CRenderer() { - refCount = 1; + refCount = 1; - m_bHooked = FALSE; - - Register(); - Initialize(); + m_bHooked = FALSE; + + Register(); + Initialize(); } CRenderer::~CRenderer() { - if( m_bHooked ) - UnRegister(); + if ( m_bHooked ) { + UnRegister(); + } } void CRenderer::Register() { @@ -48,7 +49,7 @@ void CRenderer::Register() { } void CRenderer::UnRegister() { - if( g_QglTable.m_nSize ) { + if ( g_QglTable.m_nSize ) { g_QglTable.m_pfnUnHookGL2DWindow( this ); g_QglTable.m_pfnUnHookGL3DWindow( this ); } @@ -61,27 +62,27 @@ void CRenderer::Initialize() { void CRenderer::Draw2D( VIEWTYPE vt ) { - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); + g_QglTable.m_pfn_qglPushAttrib( GL_ALL_ATTRIB_BITS ); g_QglTable.m_pfn_qglPushMatrix(); - switch(vt) - { - case XY: - break; - case XZ: - g_QglTable.m_pfn_qglRotatef(270.0f, 1.0f, 0.0f, 0.0f); - break; - case YZ: - g_QglTable.m_pfn_qglRotatef(270.0f, 1.0f, 0.0f, 0.0f); - g_QglTable.m_pfn_qglRotatef(270.0f, 0.0f, 0.0f, 1.0f); - break; - } - - CCamera *cam = firstCam; - while( cam ) { - cam->GetCam()->draw( ((Listener && cam == g_pCurrentEditCam) ? true : false) ); - cam = cam->GetNext(); - } + switch ( vt ) + { + case XY: + break; + case XZ: + g_QglTable.m_pfn_qglRotatef( 270.0f, 1.0f, 0.0f, 0.0f ); + break; + case YZ: + g_QglTable.m_pfn_qglRotatef( 270.0f, 1.0f, 0.0f, 0.0f ); + g_QglTable.m_pfn_qglRotatef( 270.0f, 0.0f, 0.0f, 1.0f ); + break; + } + + CCamera *cam = firstCam; + while ( cam ) { + cam->GetCam()->draw( ( ( Listener && cam == g_pCurrentEditCam ) ? true : false ) ); + cam = cam->GetNext(); + } g_QglTable.m_pfn_qglPopMatrix(); g_QglTable.m_pfn_qglPopAttrib(); @@ -94,47 +95,48 @@ void CRenderer::Draw3D() { static long msecs; static long current; - if( g_iPreviewRunning ) { - if( g_iPreviewRunning == 1 ) { + if ( g_iPreviewRunning ) { + if ( g_iPreviewRunning == 1 ) { start = Q_QGetTickCount(); GetCurrentCam()->GetCam()->startCamera( start ); cycle = GetCurrentCam()->GetCam()->getTotalTime(); - msecs = (long)(cycle * 1000); + msecs = (long)( cycle * 1000 ); current = start; g_iPreviewRunning = 2; } - if( current < start + msecs ) { + if ( current < start + msecs ) { float fov; - vec3_t origin = {0.0f, 0.0f, 0.0f}, dir = {0.0f, 0.0f, 0.0f}, angles; + vec3_t origin = {0.0f, 0.0f, 0.0f}, dir = {0.0f, 0.0f, 0.0f}, angles; GetCurrentCam()->GetCam()->getCameraInfo( current, &origin[0], &dir[0], &fov ); - VectorSet( angles, asin (dir[2])*180/3.14159, atan2 (dir[1], dir[0])*180/3.14159, 0 ); + VectorSet( angles, asin( dir[2] ) * 180 / 3.14159, atan2( dir[1], dir[0] ) * 180 / 3.14159, 0 ); g_CameraTable.m_pfnSetCamera( origin, angles ); current = Q_QGetTickCount(); - } else { + } + else { g_iPreviewRunning = 0; GetCurrentCam()->GetCam()->setRunning( false ); g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); } } - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); + g_QglTable.m_pfn_qglPushAttrib( GL_ALL_ATTRIB_BITS ); - CCamera *cam = firstCam; - while( cam ) { - cam->GetCam()->draw( ((Listener && cam == g_pCurrentEditCam) ? true : false) ); - cam = cam->GetNext(); - } + CCamera *cam = firstCam; + while ( cam ) { + cam->GetCam()->draw( ( ( Listener && cam == g_pCurrentEditCam ) ? true : false ) ); + cam = cam->GetNext(); + } - if( g_iPreviewRunning ) { + if ( g_iPreviewRunning ) { int x, y, width, height, i; float degInRad; g_CameraTable.m_pfnGetCamWindowExtents( &x, &y, &width, &height ); // setup orthographic projection mode - g_QglTable.m_pfn_qglMatrixMode(GL_PROJECTION); + g_QglTable.m_pfn_qglMatrixMode( GL_PROJECTION ); g_QglTable.m_pfn_qglLoadIdentity(); g_QglTable.m_pfn_qglDisable( GL_DEPTH_TEST ); g_QglTable.m_pfn_qglOrtho( 0, (float)width, 0, (float)height, -100, 100 ); @@ -150,24 +152,24 @@ void CRenderer::Draw3D() { g_QglTable.m_pfn_qglEnd(); g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - for( i = 0; i < 360; i += 60 ) { - degInRad = i * (3.14159265358979323846/180.f); - g_QglTable.m_pfn_qglVertex2f( 18 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); + for ( i = 0; i < 360; i += 60 ) { + degInRad = i * ( 3.14159265358979323846 / 180.f ); + g_QglTable.m_pfn_qglVertex2f( 18 + cos( degInRad ) * 5, 18 + sin( degInRad ) * 5 ); } g_QglTable.m_pfn_qglEnd(); - degInRad = (360-((current - start) % 360)) * (3.14159265358979323846/180.f); + degInRad = ( 360 - ( ( current - start ) % 360 ) ) * ( 3.14159265358979323846 / 180.f ); g_QglTable.m_pfn_qglBegin( GL_LINES ); g_QglTable.m_pfn_qglVertex2f( 18, 18 ); - g_QglTable.m_pfn_qglVertex2f( 18 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); + g_QglTable.m_pfn_qglVertex2f( 18 + cos( degInRad ) * 5, 18 + sin( degInRad ) * 5 ); g_QglTable.m_pfn_qglVertex2f( 32, 18 ); - g_QglTable.m_pfn_qglVertex2f( 32 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); + g_QglTable.m_pfn_qglVertex2f( 32 + cos( degInRad ) * 5, 18 + sin( degInRad ) * 5 ); g_QglTable.m_pfn_qglEnd(); g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - for( i = 0; i < 360; i += 60 ) { - degInRad = i * (3.14159265358979323846/180.f); - g_QglTable.m_pfn_qglVertex2f( 32 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); + for ( i = 0; i < 360; i += 60 ) { + degInRad = i * ( 3.14159265358979323846 / 180.f ); + g_QglTable.m_pfn_qglVertex2f( 32 + cos( degInRad ) * 5, 18 + sin( degInRad ) * 5 ); } g_QglTable.m_pfn_qglEnd(); @@ -179,5 +181,5 @@ void CRenderer::Draw3D() { g_QglTable.m_pfn_qglEnd(); } - g_QglTable.m_pfn_qglPopAttrib(); + g_QglTable.m_pfn_qglPopAttrib(); } diff --git a/contrib/camera/renderer.h b/contrib/camera/renderer.h index c73d84d4..b84680ba 100644 --- a/contrib/camera/renderer.h +++ b/contrib/camera/renderer.h @@ -1,46 +1,50 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ + Camera plugin for GtkRadiant + Copyright (C) 2002 Splash Damage Ltd. + */ class CRenderer : public IGL2DWindow, public IGL3DWindow { public: - CRenderer(); - virtual ~CRenderer(); +CRenderer(); +virtual ~CRenderer(); protected: - int refCount; +int refCount; public: - void Register(); - void UnRegister(); - void Initialize(); - void Draw2D( VIEWTYPE vt ); - void Draw3D(); - - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } - - bool m_bHooked; +void Register(); +void UnRegister(); +void Initialize(); +void Draw2D( VIEWTYPE vt ); +void Draw3D(); + +void IncRef() { refCount++; } +void DecRef() { + refCount--; if ( refCount <= 0 ) { + delete this; + } +} + +bool m_bHooked; }; diff --git a/contrib/gtkgensurf/bitmap.cpp b/contrib/gtkgensurf/bitmap.cpp index 038d93a2..2ca7e6b4 100644 --- a/contrib/gtkgensurf/bitmap.cpp +++ b/contrib/gtkgensurf/bitmap.cpp @@ -1,434 +1,448 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include #include #include "gensurf.h" -void GenerateBitmapMapping () -{ - double value; - double C0, C1; - double x, y; - int i, j; - int O00,O01,O10,O11; - int r0, r1, c0, c1; - int color; - unsigned char *colors; - - if (!gbmp.colors) - return; - - colors = gbmp.colors; - - for (j=0; j<=NV; j++) - { - y = (double)(j*(gbmp.height-1))/(double)NV; - r0 = (int)floor(y); - r1 = (int)ceil(y); - for (i=0; i<=NH; i++) - { - x = (double)(i*(gbmp.width-1))/(double)NH; - c0 = (int)floor(x); - c1 = (int)ceil(x); - O00 = r0*gbmp.width + c0; - O01 = r0*gbmp.width + c1; - O10 = r1*gbmp.width + c0; - O11 = r1*gbmp.width + c1; - C0 = (double)colors[O00] + (double)(colors[O01]-colors[O00])*(x-(double)c0); - C1 = (double)colors[O10] + (double)(colors[O11]-colors[O10])*(x-(double)c0); - color = (int)(C0 + (C1-C0)*(y-r0)); - - value = CalculateSnapValue(gbmp.black_value + color*((gbmp.white_value-gbmp.black_value)/255.)); - - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] = value; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] = value; - break; - default: - xyz[i][j].p[2] = value; - } - } - } +void GenerateBitmapMapping(){ + double value; + double C0, C1; + double x, y; + int i, j; + int O00,O01,O10,O11; + int r0, r1, c0, c1; + int color; + unsigned char *colors; + + if ( !gbmp.colors ) { + return; + } + + colors = gbmp.colors; + + for ( j = 0; j <= NV; j++ ) + { + y = (double)( j * ( gbmp.height - 1 ) ) / (double)NV; + r0 = (int)floor( y ); + r1 = (int)ceil( y ); + for ( i = 0; i <= NH; i++ ) + { + x = (double)( i * ( gbmp.width - 1 ) ) / (double)NH; + c0 = (int)floor( x ); + c1 = (int)ceil( x ); + O00 = r0 * gbmp.width + c0; + O01 = r0 * gbmp.width + c1; + O10 = r1 * gbmp.width + c0; + O11 = r1 * gbmp.width + c1; + C0 = (double)colors[O00] + (double)( colors[O01] - colors[O00] ) * ( x - (double)c0 ); + C1 = (double)colors[O10] + (double)( colors[O11] - colors[O10] ) * ( x - (double)c0 ); + color = (int)( C0 + ( C1 - C0 ) * ( y - r0 ) ); + + value = CalculateSnapValue( gbmp.black_value + color * ( ( gbmp.white_value - gbmp.black_value ) / 255. ) ); + + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + xyz[i][j].p[1] = value; + break; + case PLANE_YZ0: + case PLANE_YZ1: + xyz[i][j].p[0] = value; + break; + default: + xyz[i][j].p[2] = value; + } + } + } } -static unsigned char* OpenBitmapFile () -{ -#define INVALID_FORMAT do{\ - fprintf(stderr,"%s:%d: Error file '%s' is malformed.\n",__FILE__,__LINE__,gbmp.name);\ - fclose(fp);\ - return NULL;\ -}while(0); - - int32_t bmWidth; - int32_t bmHeight; - uint16_t bmPlanes; - uint16_t bmBitsPixel; - uint8_t m1,m2; - uint32_t sizeimage; - int16_t res1,res2; - int32_t filesize, pixoff; - int32_t bmisize, compression; - int32_t xscale, yscale; - int32_t colors, impcol; - uint32_t m_bytesRead = 0; - unsigned char *image; - FILE *fp; - - fp = fopen (gbmp.name, "rb"); - if (fp == NULL) - { - fprintf(stderr,"Error: Invalid filename '%s'\n",gbmp.name); - return NULL; - } - - long rc; - rc = fread(&m1, 1, 1, fp); - m_bytesRead++; - if (rc == -1) - INVALID_FORMAT; - - rc = fread(&m2, 1, 1, fp); - m_bytesRead++; - if ((m1 != 'B') || (m2 != 'M')) - INVALID_FORMAT; - - rc = fread((uint32_t*)&(filesize),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(res1),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(res2),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(pixoff),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(bmisize),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t *)&(bmWidth),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(bmHeight),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(bmPlanes),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(bmBitsPixel),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(compression),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(sizeimage),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(xscale),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(yscale),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(colors),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(impcol),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - if (bmBitsPixel != 8) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "This is not an 8-bit image. GenSurf can't use it.", - "Bitmap", eMB_OK, eMB_ICONWARNING); - fclose(fp); - return NULL; - } - - if (colors == 0) - colors = 1 << bmBitsPixel; - - if (bmBitsPixel != 24) - { - int i; - for (i = 0; i < colors; i++) - { - unsigned char r ,g, b, dummy; - - rc = fread(&b, 1, 1, fp); - m_bytesRead++; - if (rc!=1) - { - INVALID_FORMAT; - } - - rc = fread(&g, 1, 1, fp); - m_bytesRead++; - if (rc!=1) - { - INVALID_FORMAT; - } - - rc = fread(&r, 1, 1, fp); - m_bytesRead++; - if (rc != 1) - { - INVALID_FORMAT; - } - - rc = fread(&dummy, 1, 1, fp); - m_bytesRead++; - if (rc != 1) - { - INVALID_FORMAT; - } - } - } - - if ((long)m_bytesRead > pixoff) - { - INVALID_FORMAT; - } - - while ((long)m_bytesRead < pixoff) - { - char dummy; - fread(&dummy,1,1,fp); - m_bytesRead++; - } - - int w = bmWidth; - int h = bmHeight; - - // set the output params - image = (unsigned char*)malloc(w*h); - - if (image != NULL) - { - unsigned char* outbuf = image; - long row = 0; - long rowOffset = 0; - - if (compression == 0) // BI_RGB - { - for (row = 0; row < bmHeight; row++) - { - // which row are we working on? - rowOffset = (long unsigned)row*w; - - { - // pixels are packed as 1 , 4 or 8 bit vals. need to unpack them - int bit_count = 0; - unsigned long mask = (1 << bmBitsPixel) - 1; - unsigned char inbyte = 0; - - for (int col=0;col> bit_count) & mask; - - // lookup the color from the colormap - stuff it in our buffer - // swap red and blue - *(outbuf + rowOffset + col) = pix; - } - - // read DWORD padding - while ((m_bytesRead-pixoff)&3) - { - char dummy; - if (fread(&dummy,1,1,fp)!=1) - { - free(image); - INVALID_FORMAT; - } - m_bytesRead++; - } - } - } - } - else // compression != 0 - { - int i, x = 0; - unsigned char c, c1 = 0, *pp; - row = 0; - pp = outbuf; - - if (bmBitsPixel == 8) - { - while (row < bmHeight) - { - c = getc(fp); - - if (c) - { - // encoded mode - c1 = getc(fp); - for (i = 0; i < c; x++, i++) - { - *pp = c1; pp++; - } - } - else - { - // c==0x00, escape codes - c = getc(fp); - - if (c == 0x00) // end of line - { - row++; - x = 0; - pp = outbuf + row*bmWidth; - } - else if (c == 0x01) - break; // end of pic - else if (c == 0x02) // delta - { - c = getc(fp); - x += c; - c = getc(fp); - row += c; - pp = outbuf + x + row*bmWidth; - } - else // absolute mode - { - for (i = 0; i < c; x++, i++) - { - c1 = getc(fp); - *pp = c1; pp++; - } - - if (c & 1) - getc(fp); // odd length run: read an extra pad byte - } - } - } - } - else if (bmBitsPixel == 4) - { - while (row < bmHeight) - { - c = getc(fp); - - if (c) - { - // encoded mode - c1 = getc(fp); - for (i = 0; i < c; x++, i++) - { - *pp = (i&1) ? (c1 & 0x0f) : ((c1>>4)&0x0f); pp++; - } - } - else - { - // c==0x00, escape codes - c = getc(fp); - - if (c == 0x00) // end of line - { - row++; - x = 0; - pp = outbuf + bmHeight*bmWidth; - } - else if (c == 0x01) - break; // end of pic - else if (c == 0x02) // delta - { - c = getc(fp); - x += c; - c = getc(fp); - row += c; - pp = outbuf + x + row*bmWidth; - } - else // absolute mode - { - for (i = 0; i < c; x++, i++) - { - if ((i&1) == 0) - c1 = getc(fp); - *pp = (i&1) ? (c1 & 0x0f) : ((c1>>4)&0x0f); pp++; - } - - if (((c&3) == 1) || ((c&3) == 2)) - getc(fp); // odd length run: read an extra pad byte - } - } - } - } - } - } - fclose(fp); - - gbmp.width = w; - gbmp.height = h; - if(gbmp.colors) - free(gbmp.colors); - gbmp.colors = image; - return image; +static unsigned char* OpenBitmapFile(){ +#define INVALID_FORMAT do { \ + fprintf( stderr,"%s:%d: Error file '%s' is malformed.\n",__FILE__,__LINE__,gbmp.name ); \ + fclose( fp ); \ + return NULL; \ +} while ( 0 ); + + int32_t bmWidth; + int32_t bmHeight; + uint16_t bmPlanes; + uint16_t bmBitsPixel; + uint8_t m1,m2; + uint32_t sizeimage; + int16_t res1,res2; + int32_t filesize, pixoff; + int32_t bmisize, compression; + int32_t xscale, yscale; + int32_t colors, impcol; + uint32_t m_bytesRead = 0; + unsigned char *image; + FILE *fp; + + fp = fopen( gbmp.name, "rb" ); + if ( fp == NULL ) { + fprintf( stderr,"Error: Invalid filename '%s'\n",gbmp.name ); + return NULL; + } + + long rc; + rc = fread( &m1, 1, 1, fp ); + m_bytesRead++; + if ( rc == -1 ) { + INVALID_FORMAT; + } + + rc = fread( &m2, 1, 1, fp ); + m_bytesRead++; + if ( ( m1 != 'B' ) || ( m2 != 'M' ) ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( filesize ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint16_t*)&( res1 ),2,1,fp ); m_bytesRead += 2; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint16_t*)&( res2 ),2,1,fp ); m_bytesRead += 2; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( pixoff ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( bmisize ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t *)&( bmWidth ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( bmHeight ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint16_t*)&( bmPlanes ),2,1,fp ); m_bytesRead += 2; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint16_t*)&( bmBitsPixel ),2,1,fp ); m_bytesRead += 2; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( compression ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( sizeimage ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( xscale ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( yscale ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( colors ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( (uint32_t*)&( impcol ),4,1,fp ); m_bytesRead += 4; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + if ( bmBitsPixel != 8 ) { + g_FuncTable.m_pfnMessageBox( g_pWnd, "This is not an 8-bit image. GenSurf can't use it.", + "Bitmap", eMB_OK, eMB_ICONWARNING ); + fclose( fp ); + return NULL; + } + + if ( colors == 0 ) { + colors = 1 << bmBitsPixel; + } + + if ( bmBitsPixel != 24 ) { + int i; + for ( i = 0; i < colors; i++ ) + { + unsigned char r,g, b, dummy; + + rc = fread( &b, 1, 1, fp ); + m_bytesRead++; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( &g, 1, 1, fp ); + m_bytesRead++; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( &r, 1, 1, fp ); + m_bytesRead++; + if ( rc != 1 ) { + INVALID_FORMAT; + } + + rc = fread( &dummy, 1, 1, fp ); + m_bytesRead++; + if ( rc != 1 ) { + INVALID_FORMAT; + } + } + } + + if ( (long)m_bytesRead > pixoff ) { + INVALID_FORMAT; + } + + while ( (long)m_bytesRead < pixoff ) + { + char dummy; + fread( &dummy,1,1,fp ); + m_bytesRead++; + } + + int w = bmWidth; + int h = bmHeight; + + // set the output params + image = (unsigned char*)malloc( w * h ); + + if ( image != NULL ) { + unsigned char* outbuf = image; + long row = 0; + long rowOffset = 0; + + if ( compression == 0 ) { // BI_RGB + for ( row = 0; row < bmHeight; row++ ) + { + // which row are we working on? + rowOffset = (long unsigned)row * w; + + { + // pixels are packed as 1 , 4 or 8 bit vals. need to unpack them + int bit_count = 0; + unsigned long mask = ( 1 << bmBitsPixel ) - 1; + unsigned char inbyte = 0; + + for ( int col = 0; col < w; col++ ) + { + int pix = 0; + + // if we need another byte + if ( bit_count <= 0 ) { + bit_count = 8; + if ( fread( &inbyte,1,1,fp ) != 1 ) { + free( image ); + INVALID_FORMAT; + } + m_bytesRead++; + } + + // keep track of where we are in the bytes + bit_count -= bmBitsPixel; + pix = ( inbyte >> bit_count ) & mask; + + // lookup the color from the colormap - stuff it in our buffer + // swap red and blue + *( outbuf + rowOffset + col ) = pix; + } + + // read DWORD padding + while ( ( m_bytesRead - pixoff ) & 3 ) + { + char dummy; + if ( fread( &dummy,1,1,fp ) != 1 ) { + free( image ); + INVALID_FORMAT; + } + m_bytesRead++; + } + } + } + } + else // compression != 0 + { + int i, x = 0; + unsigned char c, c1 = 0, *pp; + row = 0; + pp = outbuf; + + if ( bmBitsPixel == 8 ) { + while ( row < bmHeight ) + { + c = getc( fp ); + + if ( c ) { + // encoded mode + c1 = getc( fp ); + for ( i = 0; i < c; x++, i++ ) + { + *pp = c1; pp++; + } + } + else + { + // c==0x00, escape codes + c = getc( fp ); + + if ( c == 0x00 ) { // end of line + row++; + x = 0; + pp = outbuf + row * bmWidth; + } + else if ( c == 0x01 ) { + break; // end of pic + } + else if ( c == 0x02 ) { // delta + c = getc( fp ); + x += c; + c = getc( fp ); + row += c; + pp = outbuf + x + row * bmWidth; + } + else // absolute mode + { + for ( i = 0; i < c; x++, i++ ) + { + c1 = getc( fp ); + *pp = c1; pp++; + } + + if ( c & 1 ) { + getc( fp ); // odd length run: read an extra pad byte + } + } + } + } + } + else if ( bmBitsPixel == 4 ) { + while ( row < bmHeight ) + { + c = getc( fp ); + + if ( c ) { + // encoded mode + c1 = getc( fp ); + for ( i = 0; i < c; x++, i++ ) + { + *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); pp++; + } + } + else + { + // c==0x00, escape codes + c = getc( fp ); + + if ( c == 0x00 ) { // end of line + row++; + x = 0; + pp = outbuf + bmHeight * bmWidth; + } + else if ( c == 0x01 ) { + break; // end of pic + } + else if ( c == 0x02 ) { // delta + c = getc( fp ); + x += c; + c = getc( fp ); + row += c; + pp = outbuf + x + row * bmWidth; + } + else // absolute mode + { + for ( i = 0; i < c; x++, i++ ) + { + if ( ( i & 1 ) == 0 ) { + c1 = getc( fp ); + } + *pp = ( i & 1 ) ? ( c1 & 0x0f ) : ( ( c1 >> 4 ) & 0x0f ); pp++; + } + + if ( ( ( c & 3 ) == 1 ) || ( ( c & 3 ) == 2 ) ) { + getc( fp ); // odd length run: read an extra pad byte + } + } + } + } + } + } + } + fclose( fp ); + + gbmp.width = w; + gbmp.height = h; + if ( gbmp.colors ) { + free( gbmp.colors ); + } + gbmp.colors = image; + return image; } -bool OpenBitmap () -{ +bool OpenBitmap(){ - OpenBitmapFile (); + OpenBitmapFile(); - if (!gbmp.colors) - { - char Text[256]; + if ( !gbmp.colors ) { + char Text[256]; - sprintf (Text, "Error opening %s", gbmp.name); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "Bitmap", eMB_OK, eMB_ICONWARNING); - strcpy (gbmp.name, ""); - } + sprintf( Text, "Error opening %s", gbmp.name ); + g_FuncTable.m_pfnMessageBox( g_pWnd, Text, "Bitmap", eMB_OK, eMB_ICONWARNING ); + strcpy( gbmp.name, "" ); + } - if (g_pWnd) - { - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), gbmp.name); - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_reload")), - strlen (gbmp.name) ? TRUE : FALSE); + if ( g_pWnd ) { + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ), gbmp.name ); + gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_reload" ) ), + strlen( gbmp.name ) ? TRUE : FALSE ); - UpdatePreview (true); - } + UpdatePreview( true ); + } - return (gbmp.colors != NULL); + return ( gbmp.colors != NULL ); } diff --git a/contrib/gtkgensurf/dec.cpp b/contrib/gtkgensurf/dec.cpp index cc9083de..158a4302 100644 --- a/contrib/gtkgensurf/dec.cpp +++ b/contrib/gtkgensurf/dec.cpp @@ -1,21 +1,21 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #define SINGLE #ifdef SINGLE @@ -33,50 +33,51 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA typedef struct { float error; - int node; + int node; } TRITABLE; double dh, dv; -int NVP1; - -#define Absolute(a) ((a) >= 0.0 ? (a) : -(a)) - -void MakeDecimatedMap(int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri) -{ - int compare(TRITABLE *, TRITABLE *); - int Bisect(NODE *, int, int, int); - void CalcAngles(NODE *, int *, float *); - void EdgeOnSide(int *, int *, int *); - int tricall(int, NODE *, int *, TRI **, TRI **, const char *); - int CheckBorders(int *,int,NODE *,int *,TRI **); - - float biggesterror; - int i, j, N; - int j0, j1, j2; - int NumNodesToSave; - int NumNodesUsed; +int NVP1; + +#define Absolute( a ) ( ( a ) >= 0.0 ? ( a ) : -( a ) ) + +void MakeDecimatedMap( int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri ){ + int compare( TRITABLE *, TRITABLE * ); + int Bisect( NODE *, int, int, int ); + void CalcAngles( NODE *, int *, float * ); + void EdgeOnSide( int *, int *, int * ); + int tricall( int, NODE *, int *, TRI * *, TRI * *, const char * ); + int CheckBorders( int *,int,NODE *,int *,TRI * * ); + + float biggesterror; + int i, j, N; + int j0, j1, j2; + int NumNodesToSave; + int NumNodesUsed; NODE *Node; TRI *Tri; TRITABLE *TriTable; - if(Decimate <= 0) return; - /* - ghCursorCurrent = LoadCursor(NULL,IDC_WAIT); - SetCursor(ghCursorCurrent); - */ - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - NVP1 = NV+1; - - NumNodes[0] = (NH+1)*(NVP1); - *pNode = (NODE *) malloc(NumNodes[0] * sizeof(NODE)); + if ( Decimate <= 0 ) { + return; + } + /* + ghCursorCurrent = LoadCursor(NULL,IDC_WAIT); + SetCursor(ghCursorCurrent); + */ + dh = ( Hur - Hll ) / NH; + dv = ( Vur - Vll ) / NV; + NVP1 = NV + 1; + + NumNodes[0] = ( NH + 1 ) * ( NVP1 ); + *pNode = (NODE *) malloc( NumNodes[0] * sizeof( NODE ) ); Node = *pNode; - memset(Node,0,NumNodes[0]*sizeof(NODE)); + memset( Node,0,NumNodes[0] * sizeof( NODE ) ); // Copy [NH][NV] vertex array to our working node array - for(i=0,N=0; i<=NH; i++) + for ( i = 0,N = 0; i <= NH; i++ ) { - for(j=0; j<=NV; j++, N++) + for ( j = 0; j <= NV; j++, N++ ) { Node[N].p[0] = (float)xyz[i][j].p[0]; Node[N].p[1] = (float)xyz[i][j].p[1]; @@ -87,14 +88,14 @@ void MakeDecimatedMap(int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri) // Start things off with the corner values Node[ 0].used = 1; Node[NV].used = 1; - Node[NH*NVP1].used = 1; - Node[NH*NVP1+NV].used = 1; + Node[NH * NVP1].used = 1; + Node[NH * NVP1 + NV].used = 1; NumNodesUsed = 4; - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); + tricall( NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY" ); Tri = *pTri; // Which coordinates are we triangulating on? - switch(Plane) + switch ( Plane ) { case PLANE_XZ0: case PLANE_XZ1: @@ -116,161 +117,181 @@ void MakeDecimatedMap(int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri) // TriTable stores the largest error in a triangle and the node where that // error occurs - TriTable = (TRITABLE *) malloc(NH*NV*2 * sizeof(TRITABLE)); - NumNodesToSave = min(NumNodes[0], (int)(0.01*(100-Decimate)*(NumNodes[0]-NumNodesUsed)+NumNodesUsed)); + TriTable = (TRITABLE *) malloc( NH * NV * 2 * sizeof( TRITABLE ) ); + NumNodesToSave = min( NumNodes[0], (int)( 0.01 * ( 100 - Decimate ) * ( NumNodes[0] - NumNodesUsed ) + NumNodesUsed ) ); - while(NumNodesUsed < NumNodesToSave) + while ( NumNodesUsed < NumNodesToSave ) { - for(i=0; i TriTable[Node[i].tri].error) - { - TriTable[Node[i].tri].error = (float)(Absolute(Node[i].error)); + if ( Node[i].used ) { + continue; + } + if ( Absolute( Node[i].error ) > TriTable[Node[i].tri].error ) { + TriTable[Node[i].tri].error = (float)( Absolute( Node[i].error ) ); TriTable[Node[i].tri].node = i; } } - qsort( (void *)TriTable, (size_t)(NumTris[0]), sizeof(TRITABLE), (int (*)(const void *, const void *))compare ); - for(i=0; i 0.5*biggesterror; i++) + qsort( (void *)TriTable, (size_t)( NumTris[0] ), sizeof( TRITABLE ), ( int ( * )( const void *, const void * ) )compare ); + for ( i = 0; i < NumTris[0] && NumNodesUsed < NumNodesToSave && TriTable[i].error > 0.5 * biggesterror; i++ ) { - if(Node[TriTable[i].node].used) continue; // shouldn't happen + if ( Node[TriTable[i].node].used ) { + continue; // shouldn't happen + } NumNodesUsed++; Node[TriTable[i].node].used++; } - free(Tri); - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); + free( Tri ); + tricall( NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY" ); Tri = *pTri; // Sliver-check along borders. Since borders are often linear, the errors // along borders will often be zero, so no new points will be added. This // tends to produce long, thin brushes. For all border triangles, check // that minimum angle isn't less than SLIVER_ANGLE. If it is, add another // vertex. - while(CheckBorders(&NumNodesUsed,NumNodes[0],Node,NumTris,pTri) > 0) + while ( CheckBorders( &NumNodesUsed,NumNodes[0],Node,NumTris,pTri ) > 0 ) { } Tri = *pTri; } } - free(TriTable); + free( TriTable ); // One last time (because we're pessimistic), check border triangles // CheckBorders(&NumNodesUsed,NumNodes[0],Node,NumTris,pTri); // Tri = *pTri; // Check that all fixed points are exact. If not, add them to the mix. // First check to see if we have any fixed points that aren't already used. - for(i=0, N=0; i 0.5) - { + if ( Absolute( Node[i].error ) > 0.5 ) { NumNodesUsed++; Node[i].used++; - free(Tri); - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); + free( Tri ); + tricall( NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY" ); Tri = *pTri; } } @@ -279,9 +300,8 @@ void MakeDecimatedMap(int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri) // Swap node orders for surfaces facing down, north or west so that // they are counterclockwise when facing the surface - if((Plane == PLANE_XY1) || (Plane == PLANE_XZ0) || (Plane == PLANE_YZ1) ) - { - for(i=0; i= R) && (v[1] >= R) ) - { + if ( ( v[0] >= R ) && ( v[1] >= R ) ) { edge[0] = 0; border[0] = 1; } - if( (v[1] >= R) && (v[2] >= R) ) - { + if ( ( v[1] >= R ) && ( v[2] >= R ) ) { edge[0] = 1; border[0] = 1; } - if( (v[2] >= R) && (v[0] >= R) ) - { + if ( ( v[2] >= R ) && ( v[0] >= R ) ) { edge[0] = 2; border[0] = 1; } - if(border[0] >= 0) - { + if ( border[0] >= 0 ) { k0 = edge[0]; - k1 = (k0+1) % 3; - N = Absolute(v[k0] - v[k1]); - Ndv = (float)(N*dv); + k1 = ( k0 + 1 ) % 3; + N = Absolute( v[k0] - v[k1] ); + Ndv = (float)( N * dv ); } - if( ((v[0] % NVP1) == 0) && ((v[1] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[0] - v[1])*dh)) return; + if ( ( ( v[0] % NVP1 ) == 0 ) && ( ( v[1] % NVP1 ) == 0 ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[0] - v[1] ) * dh ) ) { + return; + } + } edge[0] = 0; border[0] = 2; return; } - if( ((v[1] % NVP1) == 0) && ((v[2] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[1] - v[2])*dh)) return; + if ( ( ( v[1] % NVP1 ) == 0 ) && ( ( v[2] % NVP1 ) == 0 ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[1] - v[2] ) * dh ) ) { + return; + } + } edge[0] = 1; border[0] = 2; return; } - if( ((v[2] % NVP1) == 0) && ((v[0] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[2] - v[0])*dh)) return; + if ( ( ( v[2] % NVP1 ) == 0 ) && ( ( v[0] % NVP1 ) == 0 ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[2] - v[0] ) * dh ) ) { + return; + } + } edge[0] = 2; border[0] = 2; return; } - if( ((v[0] % NVP1) == NV) && ((v[1] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[0] - v[1])*dh)) return; + if ( ( ( v[0] % NVP1 ) == NV ) && ( ( v[1] % NVP1 ) == NV ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[0] - v[1] ) * dh ) ) { + return; + } + } edge[0] = 0; border[0] = 3; return; } - if( ((v[1] % NVP1) == NV) && ((v[2] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[1] - v[2])*dh)) return; + if ( ( ( v[1] % NVP1 ) == NV ) && ( ( v[2] % NVP1 ) == NV ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[1] - v[2] ) * dh ) ) { + return; + } + } edge[0] = 1; border[0] = 3; return; } - if( ((v[2] % NVP1) == NV) && ((v[0] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[2] - v[0])*dh)) return; + if ( ( ( v[2] % NVP1 ) == NV ) && ( ( v[0] % NVP1 ) == NV ) ) { + if ( border[0] >= 0 ) { + if ( Ndv > ( Absolute( v[2] - v[0] ) * dh ) ) { + return; + } + } edge[0] = 2; border[0] = 3; return; @@ -592,15 +670,14 @@ void EdgeOnSide(int *v, int *edge, int *border) return; } -void CalcAngles(NODE *node, int *v, float *angle) -{ +void CalcAngles( NODE *node, int *v, float *angle ){ int i, j, k; vec l; vec x0, x1, x2, y0, y1, y2; vec2 vv[3]; vec dot; - switch(Plane) + switch ( Plane ) { case PLANE_XZ0: case PLANE_XZ1: @@ -623,100 +700,104 @@ void CalcAngles(NODE *node, int *v, float *angle) y1 = node[v[1]].p[j]; y2 = node[v[2]].p[j]; - vv[0][0] = x1-x0; - vv[0][1] = y1-y0; - vv[1][0] = x2-x1; - vv[1][1] = y2-y1; - vv[2][0] = x0-x2; - vv[2][1] = y0-y2; + vv[0][0] = x1 - x0; + vv[0][1] = y1 - y0; + vv[1][0] = x2 - x1; + vv[1][1] = y2 - y1; + vv[2][0] = x0 - x2; + vv[2][1] = y0 - y2; - for(k=0; k<3; k++) + for ( k = 0; k < 3; k++ ) { - l = (vec)(sqrt( vv[k][0]*vv[k][0] + vv[k][1]*vv[k][1] )); - if(l > 0.) - { + l = (vec)( sqrt( vv[k][0] * vv[k][0] + vv[k][1] * vv[k][1] ) ); + if ( l > 0. ) { vv[k][0] /= l; vv[k][1] /= l; } } - dot = -(vv[0][0]*vv[2][0] + vv[0][1]*vv[2][1]); - angle[0] = (float)(acos(dot)); - dot = -(vv[1][0]*vv[0][0] + vv[1][1]*vv[0][1]); - angle[1] = (float)(acos(dot)); - dot = -(vv[2][0]*vv[1][0] + vv[2][1]*vv[1][1]); - angle[2] = (float)(acos(dot)); + dot = -( vv[0][0] * vv[2][0] + vv[0][1] * vv[2][1] ); + angle[0] = (float)( acos( dot ) ); + dot = -( vv[1][0] * vv[0][0] + vv[1][1] * vv[0][1] ); + angle[1] = (float)( acos( dot ) ); + dot = -( vv[2][0] * vv[1][0] + vv[2][1] * vv[1][1] ); + angle[2] = (float)( acos( dot ) ); } //================================================================= -int Bisect(NODE *node, int border, int j0, int j1) -{ +int Bisect( NODE *node, int border, int j0, int j1 ){ int k; - switch(border) + switch ( border ) { case 0: - k = (j0+j1)/2; + k = ( j0 + j1 ) / 2; break; case 1: - k = (j0+j1)/2; + k = ( j0 + j1 ) / 2; break; case 2: - k = (int)((j0+j1)/(2*NVP1)) * NVP1; + k = (int)( ( j0 + j1 ) / ( 2 * NVP1 ) ) * NVP1; break; case 3: - k = (int)((j0+j1+2)/(2*NVP1)) * NVP1 - 1; + k = (int)( ( j0 + j1 + 2 ) / ( 2 * NVP1 ) ) * NVP1 - 1; break; } - return( ((k != j0) && (k != j1)) ? k : 0 ); + return( ( ( k != j0 ) && ( k != j1 ) ) ? k : 0 ); } //================================================================= -int compare(TRITABLE *t1, TRITABLE *t2) -{ - if(t1->error > t2->error) return -1; - if(t1->error < t2->error) return 1; +int compare( TRITABLE *t1, TRITABLE *t2 ){ + if ( t1->error > t2->error ) { + return -1; + } + if ( t1->error < t2->error ) { + return 1; + } return 0; } -void MakeBrushes(int NumTris, NODE *Node, TRI *Tri,bool surf, - int offset,char *texture0, char *texture1, char *texture2) -{ +void MakeBrushes( int NumTris, NODE *Node, TRI *Tri,bool surf, + int offset,char *texture0, char *texture1, char *texture2 ){ extern double backface; - BRUSH brush; - int contents; - int i, j; - float Steep; - vec3_t PlaneNormal,SurfNormal; - bool CheckAngle; - vec3_t t[2]; + BRUSH brush; + int contents; + int i, j; + float Steep; + vec3_t PlaneNormal,SurfNormal; + bool CheckAngle; + vec3_t t[2]; // if texture2 is identical to texture0, there's no need to // check surface angle - if(!g_strcasecmp(texture0,texture2) || !strlen(texture2)) + if ( !g_strcasecmp( texture0,texture2 ) || !strlen( texture2 ) ) { CheckAngle = FALSE; + } else { CheckAngle = TRUE; - Steep = (float)cos((double)SlantAngle/57.2957795); - switch(Plane) + Steep = (float)cos( (double)SlantAngle / 57.2957795 ); + switch ( Plane ) { - case PLANE_XY0: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_XY1: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]=-1.;break; - case PLANE_XZ0: PlaneNormal[0]= 0.;PlaneNormal[1]= 1.;PlaneNormal[2]= 1.;break; - case PLANE_XZ1: PlaneNormal[0]= 0.;PlaneNormal[1]=-1.;PlaneNormal[2]= 1.;break; - case PLANE_YZ0: PlaneNormal[0]= 1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_YZ1: PlaneNormal[0]=-1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; + case PLANE_XY0: PlaneNormal[0] = 0.; PlaneNormal[1] = 0.; PlaneNormal[2] = 1.; break; + case PLANE_XY1: PlaneNormal[0] = 0.; PlaneNormal[1] = 0.; PlaneNormal[2] = -1.; break; + case PLANE_XZ0: PlaneNormal[0] = 0.; PlaneNormal[1] = 1.; PlaneNormal[2] = 1.; break; + case PLANE_XZ1: PlaneNormal[0] = 0.; PlaneNormal[1] = -1.; PlaneNormal[2] = 1.; break; + case PLANE_YZ0: PlaneNormal[0] = 1.; PlaneNormal[1] = 0.; PlaneNormal[2] = 1.; break; + case PLANE_YZ1: PlaneNormal[0] = -1.; PlaneNormal[1] = 0.; PlaneNormal[2] = 1.; break; } } contents = 0; - if(surf) - { - if(UseDetail) contents += CONTENTS_DETAIL; - if(UseLadder) contents += CONTENTS_LADDER; + if ( surf ) { + if ( UseDetail ) { + contents += CONTENTS_DETAIL; + } + if ( UseLadder ) { + contents += CONTENTS_LADDER; + } } OpenFuncGroup(); - for(i=0; i= max(Node[q[0]].p[j1],Node[q[2]].p[j1])) continue; - if(Tri[k].min[j2] >= max(Node[q[0]].p[j2],Node[q[2]].p[j2])) continue; - if(Tri[k].max[j1] <= min(Node[q[0]].p[j1],Node[q[2]].p[j1])) continue; - if(Tri[k].max[j2] <= min(Node[q[0]].p[j2],Node[q[2]].p[j2])) continue; + if ( Tri[k].min[j1] >= max( Node[q[0]].p[j1],Node[q[2]].p[j1] ) ) { + continue; + } + if ( Tri[k].min[j2] >= max( Node[q[0]].p[j2],Node[q[2]].p[j2] ) ) { + continue; + } + if ( Tri[k].max[j1] <= min( Node[q[0]].p[j1],Node[q[2]].p[j1] ) ) { + continue; + } + if ( Tri[k].max[j2] <= min( Node[q[0]].p[j2],Node[q[2]].p[j2] ) ) { + continue; + } - for(h0=0; h0<4 && OK; h0++) + for ( h0 = 0; h0 < 4 && OK; h0++ ) { - h1 = (h0+1)%4; - for(t=0; t<3 && OK; t++) + h1 = ( h0 + 1 ) % 4; + for ( t = 0; t < 3 && OK; t++ ) { - s[t] = side(Node[q[h0]].p[j1],Node[q[h0]].p[j2], - Node[q[h1]].p[j1],Node[q[h1]].p[j2], - Node[Tri[k].v[t]].p[j1],Node[Tri[k].v[t]].p[j2]); + s[t] = side( Node[q[h0]].p[j1],Node[q[h0]].p[j2], + Node[q[h1]].p[j1],Node[q[h1]].p[j2], + Node[Tri[k].v[t]].p[j1],Node[Tri[k].v[t]].p[j2] ); + } + if ( ( s[1] > 0 || s[2] > 0 ) && s[0] < 0 ) { + OK = 0; + } + if ( ( s[2] > 0 || s[0] > 0 ) && s[1] < 0 ) { + OK = 0; + } + if ( ( s[0] > 0 || s[1] > 0 ) && s[2] < 0 ) { + OK = 0; } - if((s[1] > 0 || s[2] > 0) && s[0] < 0) OK=0; - if((s[2] > 0 || s[0] > 0) && s[1] < 0) OK=0; - if((s[0] > 0 || s[1] > 0) && s[2] < 0) OK=0; } } - if(!OK) continue; - switch(Plane) + if ( !OK ) { + continue; + } + switch ( Plane ) { case PLANE_XZ0: case PLANE_XZ1: @@ -1152,10 +1252,10 @@ void MapOut(int NumNodes,int NumTris, NODE *Node, TRI *Tri) brush.face[1].v[2][1] = (float)backface; brush.face[1].v[2][2] = Node[q[2]].p[2]; - for(k0=0; k0= 0) - { - if(!Node[j].used) // Shouldn't be used, but... - { + EdgeOnSide( Tri[i].v,&k0,&border ); + if ( border < 0 ) { + continue; + } + CalcAngles( Node, Tri[i].v, angle ); + k1 = ( k0 + 1 ) % 3; + if ( ( angle[k0] < SLIVER_ANGLE ) || ( angle[k1] < SLIVER_ANGLE ) ) { + j = Bisect( Node, border, Tri[i].v[k0], Tri[i].v[k1] ); + if ( j >= 0 ) { + if ( !Node[j].used ) { // Shouldn't be used, but... NumNodesUsed[0]++; Node[j].used++; } } } } - if(NumNodesUsed[0] > N) - { - free(*pTri); - tricall(NumNodes, Node, NumTris, NULL, pTri, "cnzBNPY"); + if ( NumNodesUsed[0] > N ) { + free( *pTri ); + tricall( NumNodes, Node, NumTris, NULL, pTri, "cnzBNPY" ); Tri = *pTri; } - return (NumNodesUsed[0] - N); + return ( NumNodesUsed[0] - N ); } diff --git a/contrib/gtkgensurf/face.cpp b/contrib/gtkgensurf/face.cpp index b1e6c6e8..77ce7dec 100644 --- a/contrib/gtkgensurf/face.cpp +++ b/contrib/gtkgensurf/face.cpp @@ -1,52 +1,50 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include #include "gensurf.h" #define MAX_FACES 128 // Maximum number of faces on a brush -#define MAX_POINTS_ON_WINDING 64 -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 +#define MAX_POINTS_ON_WINDING 64 +#define SIDE_FRONT 0 +#define SIDE_ON 2 +#define SIDE_BACK 1 +#define SIDE_CROSS -2 //vec3 vec3_origin = {0,0,0}; -void PlaneFromPoints (float *p0, float *p1, float *p2, PLANE *plane) -{ +void PlaneFromPoints( float *p0, float *p1, float *p2, PLANE *plane ){ vec3 t1, t2; - vec length; - - VectorSubtract (p0, p1, t1); - VectorSubtract (p2, p1, t2); - plane->normal[0] = t1[1]*t2[2] - t1[2]*t2[1]; - plane->normal[1] = t1[2]*t2[0] - t1[0]*t2[2]; - plane->normal[2] = t1[0]*t2[1] - t1[1]*t2[0]; - - length = (vec)(sqrt(plane->normal[0]*plane->normal[0] + - plane->normal[1]*plane->normal[1] + - plane->normal[2]*plane->normal[2] )); - if (length == 0) - { - VectorClear(plane->normal); + vec length; + + VectorSubtract( p0, p1, t1 ); + VectorSubtract( p2, p1, t2 ); + plane->normal[0] = t1[1] * t2[2] - t1[2] * t2[1]; + plane->normal[1] = t1[2] * t2[0] - t1[0] * t2[2]; + plane->normal[2] = t1[0] * t2[1] - t1[1] * t2[0]; + + length = (vec)( sqrt( plane->normal[0] * plane->normal[0] + + plane->normal[1] * plane->normal[1] + + plane->normal[2] * plane->normal[2] ) ); + if ( length == 0 ) { + VectorClear( plane->normal ); } else { @@ -54,170 +52,170 @@ void PlaneFromPoints (float *p0, float *p1, float *p2, PLANE *plane) plane->normal[1] /= length; plane->normal[2] /= length; } - plane->dist = DotProduct (p0, plane->normal); + plane->dist = DotProduct( p0, plane->normal ); } /* -void VectorMA (vec3 va, vec scale, vec3 vb, vec3 vc) -{ - vc[0] = va[0] + scale*vb[0]; - vc[1] = va[1] + scale*vb[1]; - vc[2] = va[2] + scale*vb[2]; -} - -void CrossProduct (vec3 v1, vec3 v2, vec3 cross) -{ - cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; - cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; - cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; -} -*/ + void VectorMA (vec3 va, vec scale, vec3 vb, vec3 vc) + { + vc[0] = va[0] + scale*vb[0]; + vc[1] = va[1] + scale*vb[1]; + vc[2] = va[2] + scale*vb[2]; + } + + void CrossProduct (vec3 v1, vec3 v2, vec3 cross) + { + cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; + cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; + cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; + } + */ /* -============= -AllocWinding -============= -*/ -MY_WINDING *AllocWinding (int points) -{ - MY_WINDING *w; - int s; - - s = sizeof(vec)*3*points + sizeof(int); - w = (MY_WINDING*)malloc (s); - memset (w, 0, s); + ============= + AllocWinding + ============= + */ +MY_WINDING *AllocWinding( int points ){ + MY_WINDING *w; + int s; + + s = sizeof( vec ) * 3 * points + sizeof( int ); + w = (MY_WINDING*)malloc( s ); + memset( w, 0, s ); return w; } /* -vec VectorNormalize (vec3 in, vec3 out) -{ - vec length, ilength; - - length = (vec)(sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2])); - if (length == 0) - { - VectorClear (out); - return 0; - } - - ilength = (vec)1.0/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; - - return length; -} -*/ + vec VectorNormalize (vec3 in, vec3 out) + { + vec length, ilength; + + length = (vec)(sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2])); + if (length == 0) + { + VectorClear (out); + return 0; + } + + ilength = (vec)1.0/length; + out[0] = in[0]*ilength; + out[1] = in[1]*ilength; + out[2] = in[2]*ilength; + + return length; + } + */ /* -================= -BaseWindingForPlane -================= -*/ -MY_WINDING *BaseWindingForPlane (vec3 normal, vec dist) -{ - int i, x; - vec max, v; - vec3 org, vright, vup; + ================= + BaseWindingForPlane + ================= + */ +MY_WINDING *BaseWindingForPlane( vec3 normal, vec dist ){ + int i, x; + vec max, v; + vec3 org, vright, vup; MY_WINDING *w; // find the major axis max = -BOGUS_RANGE; x = -1; - for (i=0 ; i<3; i++) + for ( i = 0 ; i < 3; i++ ) { - v = (vec)(fabs(normal[i])); - if (v > max) - { + v = (vec)( fabs( normal[i] ) ); + if ( v > max ) { x = i; max = v; } } - if (x==-1) x = 2; - - VectorCopy(vec3_origin,vup); - switch (x) + if ( x == -1 ) { + x = 2; + } + + VectorCopy( vec3_origin,vup ); + switch ( x ) { case 0: case 1: vup[2] = 1; - break; + break; case 2: vup[0] = 1; - break; + break; } - v = DotProduct (vup, normal); - VectorMA (vup, -v, normal, vup); - VectorNormalize (vup, vup); - - VectorScale (normal, dist, org); - - CrossProduct (vup, normal, vright); - - VectorScale (vup, 65536, vup); - VectorScale (vright, 65536, vright); + v = DotProduct( vup, normal ); + VectorMA( vup, -v, normal, vup ); + VectorNormalize( vup, vup ); + + VectorScale( normal, dist, org ); + + CrossProduct( vup, normal, vright ); + + VectorScale( vup, 65536, vup ); + VectorScale( vright, 65536, vright ); // project a really big axis aligned box onto the plane - w = AllocWinding (4); - - VectorSubtract (org, vright, w->p[0]); - VectorAdd (w->p[0], vup, w->p[0]); - - VectorAdd (org, vright, w->p[1]); - VectorAdd (w->p[1], vup, w->p[1]); - - VectorAdd (org, vright, w->p[2]); - VectorSubtract (w->p[2], vup, w->p[2]); - - VectorSubtract (org, vright, w->p[3]); - VectorSubtract (w->p[3], vup, w->p[3]); - + w = AllocWinding( 4 ); + + VectorSubtract( org, vright, w->p[0] ); + VectorAdd( w->p[0], vup, w->p[0] ); + + VectorAdd( org, vright, w->p[1] ); + VectorAdd( w->p[1], vup, w->p[1] ); + + VectorAdd( org, vright, w->p[2] ); + VectorSubtract( w->p[2], vup, w->p[2] ); + + VectorSubtract( org, vright, w->p[3] ); + VectorSubtract( w->p[3], vup, w->p[3] ); + w->numpoints = 4; - - return w; + + return w; } -void FreeWinding (MY_WINDING *w) -{ - if (*(unsigned *)w == 0xdeaddead) +void FreeWinding( MY_WINDING *w ){ + if ( *(unsigned *)w == 0xdeaddead ) { // Error ("FreeWinding: freed a freed winding"); return; + } *(unsigned *)w = 0xdeaddead; - free (w); + free( w ); } /* -============= -ChopWindingInPlace -============= -*/ -void ChopWindingInPlace (MY_WINDING **inout, vec3 normal, vec dist, vec epsilon) -{ + ============= + ChopWindingInPlace + ============= + */ +void ChopWindingInPlace( MY_WINDING **inout, vec3 normal, vec dist, vec epsilon ){ MY_WINDING *in; - vec dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - static vec dot; // VC 4.2 optimizer bug if not static - int i, j; + vec dists[MAX_POINTS_ON_WINDING + 4]; + int sides[MAX_POINTS_ON_WINDING + 4]; + int counts[3]; + static vec dot; // VC 4.2 optimizer bug if not static + int i, j; vec *p1, *p2; - vec3 mid; + vec3 mid; MY_WINDING *f; - int maxpts; + int maxpts; in = *inout; counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - for (i=0 ; inumpoints ; i++) + for ( i = 0 ; i < in->numpoints ; i++ ) { - dot = DotProduct (in->p[i], normal); + dot = DotProduct( in->p[i], normal ); dot -= dist; dists[i] = dot; - if (dot > epsilon) + if ( dot > epsilon ) { sides[i] = SIDE_FRONT; - else if (dot < -epsilon) + } + else if ( dot < -epsilon ) { sides[i] = SIDE_BACK; + } else { sides[i] = SIDE_ON; @@ -226,88 +224,89 @@ void ChopWindingInPlace (MY_WINDING **inout, vec3 normal, vec dist, vec epsilon) } sides[i] = sides[0]; dists[i] = dists[0]; - - if (!counts[0]) - { - FreeWinding(in); + + if ( !counts[0] ) { + FreeWinding( in ); *inout = NULL; return; } - if (!counts[1]) - return; // inout stays the same + if ( !counts[1] ) { + return; // inout stays the same - maxpts = in->numpoints+4; // cant use counts[0]+2 because - // of fp grouping errors + } + maxpts = in->numpoints + 4; // cant use counts[0]+2 because + // of fp grouping errors + + f = AllocWinding( maxpts ); - f = AllocWinding (maxpts); - - for (i=0 ; inumpoints ; i++) + for ( i = 0 ; i < in->numpoints ; i++ ) { p1 = in->p[i]; - - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_ON ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; continue; } - - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, f->p[f->numpoints]); + + if ( sides[i] == SIDE_FRONT ) { + VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; } - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; - - // generate a split point - p2 = in->p[(i+1)%in->numpoints]; - - dot = dists[i] / (dists[i]-dists[i+1]); - for (j=0 ; j<3 ; j++) - { // avoid round off error when possible - if (normal[j] == 1) + } + + // generate a split point + p2 = in->p[( i + 1 ) % in->numpoints]; + + dot = dists[i] / ( dists[i] - dists[i + 1] ); + for ( j = 0 ; j < 3 ; j++ ) + { // avoid round off error when possible + if ( normal[j] == 1 ) { mid[j] = dist; - else if (normal[j] == -1) + } + else if ( normal[j] == -1 ) { mid[j] = -dist; - else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + } + else{ + mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); + } } - - VectorCopy (mid, f->p[f->numpoints]); + + VectorCopy( mid, f->p[f->numpoints] ); f->numpoints++; } - + // if (f->numpoints > maxpts) // Error ("ClipWinding: points exceeded estimate"); // if (f->numpoints > MAX_POINTS_ON_WINDING) // Error ("ClipWinding: MAX_POINTS_ON_WINDING"); - FreeWinding(in); + FreeWinding( in ); *inout = f; } -void UseFaceBounds() -{ - LPVOID vp; - float Dot, BestDot; - float planepts[3][3]; - int BestFace; - int i, j; - int NumFaces; - vec3 SurfNormal; - vec3 vmin,vmax; - PLANE plane[MAX_FACES*2]; - PLANE pface; +void UseFaceBounds(){ + LPVOID vp; + float Dot, BestDot; + float planepts[3][3]; + int BestFace; + int i, j; + int NumFaces; + vec3 SurfNormal; + vec3 vmin,vmax; + PLANE plane[MAX_FACES * 2]; + PLANE pface; MY_WINDING *w; - switch(Plane) + switch ( Plane ) { case PLANE_XY1: SurfNormal[0] = 0.0; SurfNormal[1] = 0.0; - SurfNormal[2] =-1.0; + SurfNormal[2] = -1.0; break; case PLANE_XZ0: SurfNormal[0] = 0.0; @@ -316,7 +315,7 @@ void UseFaceBounds() break; case PLANE_XZ1: SurfNormal[0] = 0.0; - SurfNormal[1] =-1.0; + SurfNormal[1] = -1.0; SurfNormal[2] = 0.0; break; case PLANE_YZ0: @@ -325,7 +324,7 @@ void UseFaceBounds() SurfNormal[2] = 0.0; break; case PLANE_YZ1: - SurfNormal[0] =-1.0; + SurfNormal[0] = -1.0; SurfNormal[1] = 0.0; SurfNormal[2] = 0.0; break; @@ -337,15 +336,15 @@ void UseFaceBounds() #if 0 i = g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - vp = g_FuncTable.m_pfnGetSelectedBrushHandle(0); - NumFaces = g_FuncTable.m_pfnGetFaceCount(vp); + vp = g_FuncTable.m_pfnGetSelectedBrushHandle( 0 ); + NumFaces = g_FuncTable.m_pfnGetFaceCount( vp ); BestFace = -1; BestDot = 0.0; - for(i=0; im_v1[0]; planepts[0][1] = QERFaceData->m_v1[1]; planepts[0][2] = QERFaceData->m_v1[2]; @@ -356,97 +355,108 @@ void UseFaceBounds() planepts[2][1] = QERFaceData->m_v3[1]; planepts[2][2] = QERFaceData->m_v3[2]; - PlaneFromPoints (planepts[0], planepts[1], planepts[2], &plane[2*i]); - VectorSubtract (vec3_origin, plane[2*i].normal, plane[2*i+1].normal); - plane[2*i+1].dist = -plane[2*i].dist; + PlaneFromPoints( planepts[0], planepts[1], planepts[2], &plane[2 * i] ); + VectorSubtract( vec3_origin, plane[2 * i].normal, plane[2 * i + 1].normal ); + plane[2 * i + 1].dist = -plane[2 * i].dist; - Dot = DotProduct(plane[2*i].normal,SurfNormal); - if(Dot > BestDot) - { + Dot = DotProduct( plane[2 * i].normal,SurfNormal ); + if ( Dot > BestDot ) { BestDot = Dot; BestFace = i; - if(strlen(QERFaceData->m_TextureName)) - strcpy(Texture[Game][0],QERFaceData->m_TextureName); + if ( strlen( QERFaceData->m_TextureName ) ) { + strcpy( Texture[Game][0],QERFaceData->m_TextureName ); + } } } - for(i=0; im_TextureName)) - { - if(strcmp(Texture[Game][0],QERFaceData->m_TextureName)) - strcpy(Texture[Game][1],QERFaceData->m_TextureName); + if ( i == BestFace ) { + continue; + } + _QERFaceData* QERFaceData = g_FuncTable.m_pfnGetFaceData( vp,i ); + if ( strlen( QERFaceData->m_TextureName ) ) { + if ( strcmp( Texture[Game][0],QERFaceData->m_TextureName ) ) { + strcpy( Texture[Game][1],QERFaceData->m_TextureName ); + } } } g_FuncTable.m_pfnReleaseSelectedBrushHandles(); - w = BaseWindingForPlane (plane[BestFace*2].normal, plane[BestFace*2].dist); + w = BaseWindingForPlane( plane[BestFace * 2].normal, plane[BestFace * 2].dist ); - for (i=0 ; ip[0][0]; vmin[1] = vmax[1] = w->p[0][1]; vmin[2] = vmax[2] = w->p[0][2]; - for(j=1; jnumpoints; j++) + for ( j = 1; j < w->numpoints; j++ ) { - vmin[0] = min(vmin[0],w->p[j][0]); - vmin[1] = min(vmin[1],w->p[j][1]); - vmin[2] = min(vmin[2],w->p[j][2]); - vmax[0] = max(vmax[0],w->p[j][0]); - vmax[1] = max(vmax[1],w->p[j][1]); - vmax[2] = max(vmax[2],w->p[j][2]); + vmin[0] = min( vmin[0],w->p[j][0] ); + vmin[1] = min( vmin[1],w->p[j][1] ); + vmin[2] = min( vmin[2],w->p[j][2] ); + vmax[0] = max( vmax[0],w->p[j][0] ); + vmax[1] = max( vmax[1],w->p[j][1] ); + vmax[2] = max( vmax[2],w->p[j][2] ); } - FreeWinding(w); + FreeWinding( w ); - VectorCopy(plane[BestFace*2].normal,pface.normal); - pface.dist = plane[BestFace*2].dist; - switch(Plane) + VectorCopy( plane[BestFace * 2].normal,pface.normal ); + pface.dist = plane[BestFace * 2].dist; + switch ( Plane ) { case PLANE_XZ0: case PLANE_XZ1: - if(pface.normal[1] == 0.) return; + if ( pface.normal[1] == 0. ) { + return; + } Hll = vmin[0]; Hur = vmax[0]; Vll = vmin[2]; Vur = vmax[2]; - Z00 = (pface.dist - pface.normal[0]*Hll - pface.normal[2]*Vll)/pface.normal[1]; - Z01 = (pface.dist - pface.normal[0]*Hll - pface.normal[2]*Vur)/pface.normal[1]; - Z10 = (pface.dist - pface.normal[0]*Hur - pface.normal[2]*Vll)/pface.normal[1]; - Z11 = (pface.dist - pface.normal[0]*Hur - pface.normal[2]*Vur)/pface.normal[1]; + Z00 = ( pface.dist - pface.normal[0] * Hll - pface.normal[2] * Vll ) / pface.normal[1]; + Z01 = ( pface.dist - pface.normal[0] * Hll - pface.normal[2] * Vur ) / pface.normal[1]; + Z10 = ( pface.dist - pface.normal[0] * Hur - pface.normal[2] * Vll ) / pface.normal[1]; + Z11 = ( pface.dist - pface.normal[0] * Hur - pface.normal[2] * Vur ) / pface.normal[1]; break; case PLANE_YZ0: case PLANE_YZ1: - if(pface.normal[0] == 0.) return; + if ( pface.normal[0] == 0. ) { + return; + } Hll = vmin[1]; Hur = vmax[1]; Vll = vmin[2]; Vur = vmax[2]; - Z00 = (pface.dist - pface.normal[1]*Hll - pface.normal[2]*Vll)/pface.normal[0]; - Z01 = (pface.dist - pface.normal[1]*Hll - pface.normal[2]*Vur)/pface.normal[0]; - Z10 = (pface.dist - pface.normal[1]*Hur - pface.normal[2]*Vll)/pface.normal[0]; - Z11 = (pface.dist - pface.normal[1]*Hur - pface.normal[2]*Vur)/pface.normal[0]; + Z00 = ( pface.dist - pface.normal[1] * Hll - pface.normal[2] * Vll ) / pface.normal[0]; + Z01 = ( pface.dist - pface.normal[1] * Hll - pface.normal[2] * Vur ) / pface.normal[0]; + Z10 = ( pface.dist - pface.normal[1] * Hur - pface.normal[2] * Vll ) / pface.normal[0]; + Z11 = ( pface.dist - pface.normal[1] * Hur - pface.normal[2] * Vur ) / pface.normal[0]; break; default: - if(pface.normal[2] == 0.) return; + if ( pface.normal[2] == 0. ) { + return; + } Hll = vmin[0]; Hur = vmax[0]; Vll = vmin[1]; Vur = vmax[1]; - Z00 = (pface.dist - pface.normal[0]*Hll - pface.normal[1]*Vll)/pface.normal[2]; - Z01 = (pface.dist - pface.normal[0]*Hll - pface.normal[1]*Vur)/pface.normal[2]; - Z10 = (pface.dist - pface.normal[0]*Hur - pface.normal[1]*Vll)/pface.normal[2]; - Z11 = (pface.dist - pface.normal[0]*Hur - pface.normal[1]*Vur)/pface.normal[2]; + Z00 = ( pface.dist - pface.normal[0] * Hll - pface.normal[1] * Vll ) / pface.normal[2]; + Z01 = ( pface.dist - pface.normal[0] * Hll - pface.normal[1] * Vur ) / pface.normal[2]; + Z10 = ( pface.dist - pface.normal[0] * Hur - pface.normal[1] * Vll ) / pface.normal[2]; + Z11 = ( pface.dist - pface.normal[0] * Hur - pface.normal[1] * Vur ) / pface.normal[2]; } #endif } diff --git a/contrib/gtkgensurf/font.cpp b/contrib/gtkgensurf/font.cpp index c31741d4..35004bfd 100644 --- a/contrib/gtkgensurf/font.cpp +++ b/contrib/gtkgensurf/font.cpp @@ -1,25 +1,25 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // // Texture Font -// +// // Taken from LeoCAD (www.leocad.org) and used in GtkGenSurf // with permission from the author. // @@ -30,241 +30,247 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "gensurf.h" static const unsigned char data[2048] = { - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 31, 255, 231, 159, 153, 63, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 207, 255, 231, 159, 153, 63, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 207, 255, 231, 255, 159, 63, 255, 255, 255, 255, - 7, 78, 252, 240, 145, 135, 3, 71, 38, 158, 153, 51, 19, 227, 196, 255, - 243, 140, 121, 230, 140, 51, 207, 51, 198, 156, 153, 57, 99, 204, 152, 255, - 255, 204, 51, 111, 158, 121, 206, 121, 230, 153, 153, 60, 115, 206, 60, 255, - 31, 204, 51, 127, 158, 121, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, - 199, 204, 51, 127, 158, 1, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, - 243, 204, 51, 127, 158, 249, 207, 121, 230, 153, 153, 60, 115, 206, 60, 255, - 243, 204, 51, 111, 158, 249, 207, 121, 230, 153, 153, 57, 115, 206, 60, 255, - 243, 140, 121, 230, 140, 115, 206, 51, 230, 153, 153, 51, 115, 206, 60, 255, - 7, 73, 252, 240, 145, 7, 207, 71, 230, 153, 153, 39, 115, 206, 60, 255, - 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 57, 255, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 131, 255, 255, 252, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 227, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 201, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 156, 255, - 15, 79, 252, 200, 196, 96, 32, 79, 62, 252, 15, 15, 159, 192, 156, 255, - 103, 142, 121, 198, 112, 206, 57, 79, 62, 60, 15, 15, 159, 207, 156, 255, - 243, 204, 51, 207, 120, 254, 57, 207, 156, 57, 103, 102, 206, 231, 156, 255, - 243, 204, 51, 207, 124, 252, 57, 207, 156, 25, 230, 112, 206, 231, 156, 255, - 243, 204, 51, 207, 252, 224, 57, 207, 156, 25, 230, 121, 206, 243, 156, 255, - 243, 204, 51, 207, 252, 199, 57, 207, 201, 211, 242, 240, 228, 249, 156, 255, - 243, 204, 51, 207, 252, 207, 57, 207, 201, 195, 112, 230, 228, 249, 156, 255, - 103, 142, 121, 198, 124, 206, 121, 198, 227, 231, 57, 207, 241, 252, 201, 255, - 15, 79, 252, 200, 252, 224, 227, 200, 227, 231, 57, 207, 241, 192, 227, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 159, 15, 30, 252, 57, 224, 225, 128, 131, 7, 255, 254, 128, 127, 240, 255, - 135, 231, 204, 249, 57, 255, 252, 159, 57, 115, 126, 252, 60, 63, 231, 255, - 159, 247, 236, 249, 56, 127, 254, 159, 57, 115, 126, 252, 124, 158, 207, 255, - 159, 255, 252, 249, 56, 127, 254, 207, 57, 115, 62, 249, 124, 158, 207, 255, - 159, 255, 252, 121, 56, 112, 254, 207, 57, 115, 62, 249, 60, 207, 255, 255, - 159, 127, 62, 60, 57, 103, 224, 231, 131, 115, 158, 243, 128, 207, 255, 255, - 159, 63, 255, 57, 249, 103, 206, 231, 57, 7, 158, 243, 60, 207, 255, 255, - 159, 159, 255, 153, 249, 103, 206, 231, 57, 127, 206, 231, 124, 206, 255, 255, - 159, 207, 255, 25, 240, 103, 206, 243, 57, 127, 14, 224, 124, 158, 207, 255, - 159, 231, 239, 249, 185, 103, 206, 243, 57, 127, 230, 207, 124, 158, 207, 255, - 159, 231, 207, 249, 57, 103, 206, 243, 57, 63, 231, 207, 60, 63, 231, 255, - 159, 7, 28, 252, 121, 240, 224, 243, 131, 135, 231, 207, 128, 127, 240, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 7, 126, 128, 3, 124, 240, 249, 156, 63, 231, 57, 255, 252, 57, 159, 255, - 231, 124, 254, 243, 63, 231, 249, 156, 63, 231, 60, 255, 252, 57, 159, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 63, 103, 62, 255, 248, 56, 158, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 63, 39, 63, 255, 248, 56, 156, 255, - 231, 115, 254, 243, 207, 255, 249, 156, 63, 135, 63, 255, 112, 56, 152, 255, - 231, 115, 192, 3, 206, 255, 1, 156, 63, 199, 63, 255, 112, 56, 153, 255, - 231, 115, 254, 243, 207, 193, 249, 156, 63, 135, 63, 255, 36, 57, 147, 255, - 231, 115, 254, 243, 207, 207, 249, 156, 63, 39, 63, 255, 36, 57, 131, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 57, 103, 62, 255, 140, 57, 135, 255, - 231, 121, 254, 243, 159, 199, 249, 156, 57, 231, 60, 255, 140, 57, 143, 255, - 231, 124, 254, 243, 63, 199, 249, 156, 147, 231, 57, 255, 220, 57, 159, 255, - 7, 126, 128, 243, 127, 208, 249, 156, 199, 231, 51, 192, 220, 57, 159, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 63, 252, 128, 63, 252, 128, 63, 28, 128, 249, 204, 79, 254, 39, 63, 255, - 159, 249, 60, 159, 249, 60, 159, 249, 249, 249, 204, 79, 158, 39, 63, 255, - 207, 243, 124, 206, 243, 124, 206, 243, 249, 249, 156, 103, 158, 103, 158, 255, - 207, 243, 124, 206, 243, 124, 206, 255, 249, 249, 156, 231, 156, 243, 204, 255, - 231, 231, 124, 230, 231, 124, 158, 255, 249, 249, 156, 231, 12, 243, 225, 255, - 231, 231, 60, 231, 231, 60, 63, 252, 249, 249, 60, 243, 12, 243, 243, 255, - 231, 231, 128, 231, 231, 128, 255, 249, 249, 249, 60, 243, 105, 249, 243, 255, - 231, 231, 252, 103, 230, 60, 255, 243, 249, 249, 124, 251, 97, 248, 225, 255, - 207, 243, 252, 207, 240, 124, 254, 243, 249, 249, 124, 248, 97, 248, 204, 255, - 207, 243, 252, 207, 241, 124, 206, 243, 249, 249, 124, 248, 243, 124, 158, 255, - 159, 249, 252, 159, 241, 124, 158, 249, 249, 115, 254, 252, 243, 60, 63, 255, - 63, 252, 252, 63, 228, 252, 60, 252, 249, 7, 255, 252, 243, 60, 63, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 243, 19, 192, 255, 252, 255, 255, 127, 14, 127, 248, 15, 252, 247, 227, 231, - 243, 243, 207, 255, 252, 255, 153, 127, 102, 62, 243, 227, 241, 193, 201, 243, - 231, 249, 231, 255, 252, 255, 60, 127, 242, 156, 231, 249, 231, 148, 201, 249, - 207, 252, 243, 255, 204, 124, 126, 126, 254, 156, 231, 57, 230, 148, 201, 252, - 207, 252, 243, 255, 204, 60, 255, 60, 255, 156, 231, 156, 204, 244, 99, 254, - 31, 254, 249, 255, 252, 159, 255, 57, 127, 158, 231, 204, 204, 244, 63, 255, - 31, 254, 252, 255, 252, 207, 255, 51, 63, 159, 231, 204, 204, 193, 159, 255, - 63, 127, 254, 255, 252, 159, 255, 57, 159, 207, 207, 204, 204, 151, 207, 248, - 63, 127, 254, 255, 252, 63, 255, 156, 159, 159, 231, 204, 228, 151, 103, 242, - 63, 63, 255, 255, 255, 127, 126, 158, 255, 159, 231, 25, 241, 148, 115, 242, - 63, 159, 127, 230, 204, 252, 60, 159, 159, 159, 231, 249, 255, 148, 121, 242, - 63, 31, 64, 230, 204, 252, 153, 159, 159, 159, 231, 227, 255, 193, 252, 248, - 255, 255, 63, 255, 231, 255, 255, 255, 255, 159, 231, 15, 252, 247, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 243, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 248, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 63, 254, 255, 195, 255, 255, 255, 255, 3, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 255, 153, 255, 255, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 255, 153, 255, 243, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 204, 60, 255, 243, 255, 255, 243, 252, 0, 255, 255, 255, 255, 255, - 63, 254, 204, 60, 255, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 63, 254, 225, 60, 255, 243, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 31, 126, 128, 60, 127, 128, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 159, 228, 225, 60, 193, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 207, 240, 204, 60, 255, 243, 255, 255, 243, 124, 128, 255, 255, 255, 255, 255, - 207, 249, 204, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 207, 240, 255, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 31, 242, 255, 60, 255, 255, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 255, 255, 255, 60, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 153, 255, 255, 255, 0, 242, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 153, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 195, 255, 255, 255, 255, 3, 252, 255, 255, 255, 255, 255, 255 + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 207, 255, 255, 159, 255, 31, 255, 231, 159, 153, 63, 255, 255, 255, 255, + 255, 207, 255, 255, 159, 255, 207, 255, 231, 159, 153, 63, 255, 255, 255, 255, + 255, 207, 255, 255, 159, 255, 207, 255, 231, 255, 159, 63, 255, 255, 255, 255, + 7, 78, 252, 240, 145, 135, 3, 71, 38, 158, 153, 51, 19, 227, 196, 255, + 243, 140, 121, 230, 140, 51, 207, 51, 198, 156, 153, 57, 99, 204, 152, 255, + 255, 204, 51, 111, 158, 121, 206, 121, 230, 153, 153, 60, 115, 206, 60, 255, + 31, 204, 51, 127, 158, 121, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, + 199, 204, 51, 127, 158, 1, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, + 243, 204, 51, 127, 158, 249, 207, 121, 230, 153, 153, 60, 115, 206, 60, 255, + 243, 204, 51, 111, 158, 249, 207, 121, 230, 153, 153, 57, 115, 206, 60, 255, + 243, 140, 121, 230, 140, 115, 206, 51, 230, 153, 153, 51, 115, 206, 60, 255, + 7, 73, 252, 240, 145, 7, 207, 71, 230, 153, 153, 39, 115, 206, 60, 255, + 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 57, 255, 255, 249, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 131, 255, 255, 252, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 227, 255, + 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 201, 255, + 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 156, 255, + 15, 79, 252, 200, 196, 96, 32, 79, 62, 252, 15, 15, 159, 192, 156, 255, + 103, 142, 121, 198, 112, 206, 57, 79, 62, 60, 15, 15, 159, 207, 156, 255, + 243, 204, 51, 207, 120, 254, 57, 207, 156, 57, 103, 102, 206, 231, 156, 255, + 243, 204, 51, 207, 124, 252, 57, 207, 156, 25, 230, 112, 206, 231, 156, 255, + 243, 204, 51, 207, 252, 224, 57, 207, 156, 25, 230, 121, 206, 243, 156, 255, + 243, 204, 51, 207, 252, 199, 57, 207, 201, 211, 242, 240, 228, 249, 156, 255, + 243, 204, 51, 207, 252, 207, 57, 207, 201, 195, 112, 230, 228, 249, 156, 255, + 103, 142, 121, 198, 124, 206, 121, 198, 227, 231, 57, 207, 241, 252, 201, 255, + 15, 79, 252, 200, 252, 224, 227, 200, 227, 231, 57, 207, 241, 192, 227, 255, + 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, + 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, + 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, + 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 159, 15, 30, 252, 57, 224, 225, 128, 131, 7, 255, 254, 128, 127, 240, 255, + 135, 231, 204, 249, 57, 255, 252, 159, 57, 115, 126, 252, 60, 63, 231, 255, + 159, 247, 236, 249, 56, 127, 254, 159, 57, 115, 126, 252, 124, 158, 207, 255, + 159, 255, 252, 249, 56, 127, 254, 207, 57, 115, 62, 249, 124, 158, 207, 255, + 159, 255, 252, 121, 56, 112, 254, 207, 57, 115, 62, 249, 60, 207, 255, 255, + 159, 127, 62, 60, 57, 103, 224, 231, 131, 115, 158, 243, 128, 207, 255, 255, + 159, 63, 255, 57, 249, 103, 206, 231, 57, 7, 158, 243, 60, 207, 255, 255, + 159, 159, 255, 153, 249, 103, 206, 231, 57, 127, 206, 231, 124, 206, 255, 255, + 159, 207, 255, 25, 240, 103, 206, 243, 57, 127, 14, 224, 124, 158, 207, 255, + 159, 231, 239, 249, 185, 103, 206, 243, 57, 127, 230, 207, 124, 158, 207, 255, + 159, 231, 207, 249, 57, 103, 206, 243, 57, 63, 231, 207, 60, 63, 231, 255, + 159, 7, 28, 252, 121, 240, 224, 243, 131, 135, 231, 207, 128, 127, 240, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 7, 126, 128, 3, 124, 240, 249, 156, 63, 231, 57, 255, 252, 57, 159, 255, + 231, 124, 254, 243, 63, 231, 249, 156, 63, 231, 60, 255, 252, 57, 159, 255, + 231, 121, 254, 243, 159, 207, 249, 156, 63, 103, 62, 255, 248, 56, 158, 255, + 231, 121, 254, 243, 159, 207, 249, 156, 63, 39, 63, 255, 248, 56, 156, 255, + 231, 115, 254, 243, 207, 255, 249, 156, 63, 135, 63, 255, 112, 56, 152, 255, + 231, 115, 192, 3, 206, 255, 1, 156, 63, 199, 63, 255, 112, 56, 153, 255, + 231, 115, 254, 243, 207, 193, 249, 156, 63, 135, 63, 255, 36, 57, 147, 255, + 231, 115, 254, 243, 207, 207, 249, 156, 63, 39, 63, 255, 36, 57, 131, 255, + 231, 121, 254, 243, 159, 207, 249, 156, 57, 103, 62, 255, 140, 57, 135, 255, + 231, 121, 254, 243, 159, 199, 249, 156, 57, 231, 60, 255, 140, 57, 143, 255, + 231, 124, 254, 243, 63, 199, 249, 156, 147, 231, 57, 255, 220, 57, 159, 255, + 7, 126, 128, 243, 127, 208, 249, 156, 199, 231, 51, 192, 220, 57, 159, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 63, 252, 128, 63, 252, 128, 63, 28, 128, 249, 204, 79, 254, 39, 63, 255, + 159, 249, 60, 159, 249, 60, 159, 249, 249, 249, 204, 79, 158, 39, 63, 255, + 207, 243, 124, 206, 243, 124, 206, 243, 249, 249, 156, 103, 158, 103, 158, 255, + 207, 243, 124, 206, 243, 124, 206, 255, 249, 249, 156, 231, 156, 243, 204, 255, + 231, 231, 124, 230, 231, 124, 158, 255, 249, 249, 156, 231, 12, 243, 225, 255, + 231, 231, 60, 231, 231, 60, 63, 252, 249, 249, 60, 243, 12, 243, 243, 255, + 231, 231, 128, 231, 231, 128, 255, 249, 249, 249, 60, 243, 105, 249, 243, 255, + 231, 231, 252, 103, 230, 60, 255, 243, 249, 249, 124, 251, 97, 248, 225, 255, + 207, 243, 252, 207, 240, 124, 254, 243, 249, 249, 124, 248, 97, 248, 204, 255, + 207, 243, 252, 207, 241, 124, 206, 243, 249, 249, 124, 248, 243, 124, 158, 255, + 159, 249, 252, 159, 241, 124, 158, 249, 249, 115, 254, 252, 243, 60, 63, 255, + 63, 252, 252, 63, 228, 252, 60, 252, 249, 7, 255, 252, 243, 60, 63, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 243, 19, 192, 255, 252, 255, 255, 127, 14, 127, 248, 15, 252, 247, 227, 231, + 243, 243, 207, 255, 252, 255, 153, 127, 102, 62, 243, 227, 241, 193, 201, 243, + 231, 249, 231, 255, 252, 255, 60, 127, 242, 156, 231, 249, 231, 148, 201, 249, + 207, 252, 243, 255, 204, 124, 126, 126, 254, 156, 231, 57, 230, 148, 201, 252, + 207, 252, 243, 255, 204, 60, 255, 60, 255, 156, 231, 156, 204, 244, 99, 254, + 31, 254, 249, 255, 252, 159, 255, 57, 127, 158, 231, 204, 204, 244, 63, 255, + 31, 254, 252, 255, 252, 207, 255, 51, 63, 159, 231, 204, 204, 193, 159, 255, + 63, 127, 254, 255, 252, 159, 255, 57, 159, 207, 207, 204, 204, 151, 207, 248, + 63, 127, 254, 255, 252, 63, 255, 156, 159, 159, 231, 204, 228, 151, 103, 242, + 63, 63, 255, 255, 255, 127, 126, 158, 255, 159, 231, 25, 241, 148, 115, 242, + 63, 159, 127, 230, 204, 252, 60, 159, 159, 159, 231, 249, 255, 148, 121, 242, + 63, 31, 64, 230, 204, 252, 153, 159, 159, 159, 231, 227, 255, 193, 252, 248, + 255, 255, 63, 255, 231, 255, 255, 255, 255, 159, 231, 15, 252, 247, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 243, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 248, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 63, 254, 255, 195, 255, 255, 255, 255, 3, 252, 147, 255, 255, 255, 255, 255, + 159, 252, 255, 153, 255, 255, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, + 159, 252, 255, 153, 255, 243, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, + 159, 252, 204, 60, 255, 243, 255, 255, 243, 252, 0, 255, 255, 255, 255, 255, + 63, 254, 204, 60, 255, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, + 63, 254, 225, 60, 255, 243, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, + 31, 126, 128, 60, 127, 128, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, + 159, 228, 225, 60, 193, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, + 207, 240, 204, 60, 255, 243, 255, 255, 243, 124, 128, 255, 255, 255, 255, 255, + 207, 249, 204, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, + 207, 240, 255, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, + 31, 242, 255, 60, 255, 255, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, + 255, 255, 255, 60, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 153, 255, 255, 255, 0, 242, 252, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 153, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 195, 255, 255, 255, 255, 3, 252, 255, 255, 255, 255, 255, 255 }; -typedef struct +typedef struct { - unsigned char width; - float left, right, top, bottom; + unsigned char width; + float left, right, top, bottom; } LC_TXFVERT; static LC_TXFVERT glyphs[93]; static GLuint texture; -void texfont_init () -{ - if (texture != 0) - return; +void texfont_init(){ + if ( texture != 0 ) { + return; + } - int i, j, x, y; - float inv = 1.0f/128; - const char *charlines[16] = { - "abcdefghijklmn", "opqrstuvwxyz0", "123456789ABC", "DEFGHIJKLMN", - "OPQRSTUVWX", "YZ,.!;:<>/?{}@$%", "&*()-+=_[] #" }; - unsigned char lefts[7][17] = { - { 1, 11, 21, 30, 40, 50, 56, 66, 76, 80, 84, 93, 97, 111, 121 }, - { 1, 11, 21, 31, 38, 47, 53, 63, 72, 86, 94, 103, 111, 120 }, - { 1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 94, 106, 118, }, - { 1, 13, 24, 34, 47, 59, 64, 73, 84, 94, 108, 120 }, - { 1, 14, 25, 38, 50, 61, 71, 83, 94, 109, 120 }, - { 1, 12, 22, 26, 30, 35, 39, 43, 52, 61, 65, 75, 81, 87, 103, 112, 125 }, - { 3, 14, 23, 28, 33, 38, 47, 56, 65, 70, 75, 79, 88 } }; - // tops = 1 20 39 58 77 96 112 (+16) - memset(glyphs, 0, sizeof(glyphs)); + int i, j, x, y; + float inv = 1.0f / 128; + const char *charlines[16] = { + "abcdefghijklmn", "opqrstuvwxyz0", "123456789ABC", "DEFGHIJKLMN", + "OPQRSTUVWX", "YZ,.!;:<>/?{}@$%", "&*()-+=_[] #" + }; + unsigned char lefts[7][17] = { + { 1, 11, 21, 30, 40, 50, 56, 66, 76, 80, 84, 93, 97, 111, 121 }, + { 1, 11, 21, 31, 38, 47, 53, 63, 72, 86, 94, 103, 111, 120 }, + { 1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 94, 106, 118, }, + { 1, 13, 24, 34, 47, 59, 64, 73, 84, 94, 108, 120 }, + { 1, 14, 25, 38, 50, 61, 71, 83, 94, 109, 120 }, + { 1, 12, 22, 26, 30, 35, 39, 43, 52, 61, 65, 75, 81, 87, 103, 112, 125 }, + { 3, 14, 23, 28, 33, 38, 47, 56, 65, 70, 75, 79, 88 } + }; + // tops = 1 20 39 58 77 96 112 (+16) + memset( glyphs, 0, sizeof( glyphs ) ); - // ASCII 32-125 - for (i = 32; i < 126; i++) - for (x = 0; x < 7; x++) - for (y = 0; charlines[x][y]; y++) - if (charlines[x][y] == i) - { - glyphs[i-32].width = lefts[x][y+1] - lefts[x][y]; - glyphs[i-32].left = (float)lefts[x][y]*inv; - glyphs[i-32].right = (float)(lefts[x][y+1])*inv; + // ASCII 32-125 + for ( i = 32; i < 126; i++ ) + for ( x = 0; x < 7; x++ ) + for ( y = 0; charlines[x][y]; y++ ) + if ( charlines[x][y] == i ) { + glyphs[i - 32].width = lefts[x][y + 1] - lefts[x][y]; + glyphs[i - 32].left = (float)lefts[x][y] * inv; + glyphs[i - 32].right = (float)( lefts[x][y + 1] ) * inv; - if (x != 6) - glyphs[i-32].top = (float)(1 + 19*x); - else - glyphs[i-32].top = 112; - glyphs[i-32].bottom = glyphs[i-32].top + 16; - glyphs[i-32].top *= inv; - glyphs[i-32].bottom *= inv; - } + if ( x != 6 ) { + glyphs[i - 32].top = (float)( 1 + 19 * x ); + } + else{ + glyphs[i - 32].top = 112; + } + glyphs[i - 32].bottom = glyphs[i - 32].top + 16; + glyphs[i - 32].top *= inv; + glyphs[i - 32].bottom *= inv; + } - g_GLTable.m_pfn_qglGenTextures (1, &texture); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, texture); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_GEN_S); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_GEN_T); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - // g_GLTable.m_pfn_qglPixelStorei (GL_UNPACK_ALIGNMENT, 1); + g_GLTable.m_pfn_qglGenTextures( 1, &texture ); + g_GLTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, texture ); + g_GLTable.m_pfn_qglDisable( GL_TEXTURE_GEN_S ); + g_GLTable.m_pfn_qglDisable( GL_TEXTURE_GEN_T ); + g_GLTable.m_pfn_qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + g_GLTable.m_pfn_qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + g_GLTable.m_pfn_qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + g_GLTable.m_pfn_qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + // g_GLTable.m_pfn_qglPixelStorei (GL_UNPACK_ALIGNMENT, 1); - unsigned char *buf = (unsigned char*)malloc (128*128); - memset (buf, 255, 128*128); + unsigned char *buf = (unsigned char*)malloc( 128 * 128 ); + memset( buf, 255, 128 * 128 ); - for (i = 0; i < 2048; i++) - for (j = 0; j < 8; j++) - if ((data[i] & (1 << j)) != 0) - buf[i*8+j] = 0; + for ( i = 0; i < 2048; i++ ) + for ( j = 0; j < 8; j++ ) + if ( ( data[i] & ( 1 << j ) ) != 0 ) { + buf[i * 8 + j] = 0; + } - g_GLTable.m_pfn_qglTexImage2D (GL_TEXTURE_2D, 0, GL_INTENSITY4, 128, 128, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, buf); - free (buf); + g_GLTable.m_pfn_qglTexImage2D( GL_TEXTURE_2D, 0, GL_INTENSITY4, 128, 128, 0, + GL_LUMINANCE, GL_UNSIGNED_BYTE, buf ); + free( buf ); } -void texfont_write (const char *text, int l, int t) -{ - if (texture == 0) - return; +void texfont_write( const char *text, int l, int t ){ + if ( texture == 0 ) { + return; + } - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, texture); - g_GLTable.m_pfn_qglEnable (GL_TEXTURE_2D); - // g_GLTable.m_pfn_qglTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - g_GLTable.m_pfn_qglAlphaFunc (GL_GREATER, 0.0625); - g_GLTable.m_pfn_qglEnable (GL_ALPHA_TEST); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, texture ); + g_GLTable.m_pfn_qglEnable( GL_TEXTURE_2D ); + // g_GLTable.m_pfn_qglTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + g_GLTable.m_pfn_qglAlphaFunc( GL_GREATER, 0.0625 ); + g_GLTable.m_pfn_qglEnable( GL_ALPHA_TEST ); - g_GLTable.m_pfn_qglBegin (GL_QUADS); - for (const char* p = text; *p; p++) - { - if (*p < 32 || *p > 125) - continue; - if (glyphs[*p-32].width == 0) - continue; + g_GLTable.m_pfn_qglBegin( GL_QUADS ); + for ( const char* p = text; *p; p++ ) + { + if ( *p < 32 || *p > 125 ) { + continue; + } + if ( glyphs[*p - 32].width == 0 ) { + continue; + } - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].left, glyphs[*p-32].top); - g_GLTable.m_pfn_qglVertex2i (l, t); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].left, glyphs[*p-32].bottom); - g_GLTable.m_pfn_qglVertex2i (l, t-16); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].right, glyphs[*p-32].bottom); - g_GLTable.m_pfn_qglVertex2i (l + glyphs[*p-32].width, t-16); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].right, glyphs[*p-32].top); - g_GLTable.m_pfn_qglVertex2i (l + glyphs[*p-32].width, t); - l += glyphs[*p-32].width; - } - g_GLTable.m_pfn_qglEnd (); + g_GLTable.m_pfn_qglTexCoord2f( glyphs[*p - 32].left, glyphs[*p - 32].top ); + g_GLTable.m_pfn_qglVertex2i( l, t ); + g_GLTable.m_pfn_qglTexCoord2f( glyphs[*p - 32].left, glyphs[*p - 32].bottom ); + g_GLTable.m_pfn_qglVertex2i( l, t - 16 ); + g_GLTable.m_pfn_qglTexCoord2f( glyphs[*p - 32].right, glyphs[*p - 32].bottom ); + g_GLTable.m_pfn_qglVertex2i( l + glyphs[*p - 32].width, t - 16 ); + g_GLTable.m_pfn_qglTexCoord2f( glyphs[*p - 32].right, glyphs[*p - 32].top ); + g_GLTable.m_pfn_qglVertex2i( l + glyphs[*p - 32].width, t ); + l += glyphs[*p - 32].width; + } + g_GLTable.m_pfn_qglEnd(); - g_GLTable.m_pfn_qglDisable (GL_ALPHA_TEST); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_2D); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, 0); + g_GLTable.m_pfn_qglDisable( GL_ALPHA_TEST ); + g_GLTable.m_pfn_qglDisable( GL_TEXTURE_2D ); + g_GLTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, 0 ); } diff --git a/contrib/gtkgensurf/gendlgs.cpp b/contrib/gtkgensurf/gendlgs.cpp index dcda98a8..bfaf9849 100644 --- a/contrib/gtkgensurf/gendlgs.cpp +++ b/contrib/gtkgensurf/gendlgs.cpp @@ -1,21 +1,21 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include @@ -31,10 +31,10 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define TEXTURE_TAB 4 //#define BUFF_SIZE 32768 -#define ENABLE_WIDGET(name,enable) \ - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), (name))), (enable)) -#define CHECK_WIDGET(name,check) \ - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), name)), check) +#define ENABLE_WIDGET( name,enable ) \ + gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), ( name ) ) ), ( enable ) ) +#define CHECK_WIDGET( name,check ) \ + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), name ) ), check ) static GtkWidget *game_radios[NUMGAMES]; static GtkWidget *wave_radios[5]; @@ -45,2191 +45,2156 @@ static int WasDetail; static GtkTooltips *tooltips; static int FirstPassComplete = 0; -void About (GtkWidget *parent) -{ +void About( GtkWidget *parent ){ /* - char *icon_xpm[] = { -"32 32 4 1", -" c None", -". c #000000", -"+ c #FFFFFF", -"@ c #838183", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"...............++...............", -".............++++++.............", -"............++@+++@+............", -"..........+++..++..+++..........", -"........++.+.++..++.+.@+........", -".......+..+..+.++.+..+..++......", -".....++..++.+..++..+.++..++.....", -"...++..++...+.+..+.++..++..++...", -"..++.+.++....++..++....++.+..+..", -".+.+..+..++....++....++..++.+.+.", -"..+++....+.++++++++++.+....+++..", -"....++.@@+++++.++.++++@++.++....", -"......+++++++......++@+++++.....", -".......+++.+.++..++.+..++.......", -".........++..+.++.+..++.........", -"...........++..++..++...........", -".............++..+.+............", -"..............+..+@.............", -"...............@@...............", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................" -}; -*/ - // leo: I'm too lazy to create a nice about box + char *icon_xpm[] = { + "32 32 4 1", + " c None", + ". c #000000", + "+ c #FFFFFF", + "@ c #838183", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................", + "...............++...............", + ".............++++++.............", + "............++@+++@+............", + "..........+++..++..+++..........", + "........++.+.++..++.+.@+........", + ".......+..+..+.++.+..+..++......", + ".....++..++.+..++..+.++..++.....", + "...++..++...+.+..+.++..++..++...", + "..++.+.++....++..++....++.+..+..", + ".+.+..+..++....++....++..++.+.+.", + "..+++....+.++++++++++.+....+++..", + "....++.@@+++++.++.++++@++.++....", + "......+++++++......++@+++++.....", + ".......+++.+.++..++.+..++.......", + ".........++..+.++.+..++.........", + "...........++..++..++...........", + ".............++..+.+............", + "..............+..+@.............", + "...............@@...............", + "................................", + "................................", + "................................", + "................................", + "................................", + "................................" + }; + */ + // leo: I'm too lazy to create a nice about box // ^Fishman - I am lazy too :P. - g_FuncTable.m_pfnMessageBox (parent, "GtkGenSurf 1.05\n\n" - "Original version\n" - "David Hyde (rascal@vicksburg.com)\n\n" - "Porting\n" - "Leonardo Zide (leo@lokigames.com)\n\n" - "Enhancements\n" - "Pablo Zurita (pablo@qeradiant.com)\n" - "Hydra (hydra@hydras-world.com)", - "About GtkGenSurf", eMB_OK); + g_FuncTable.m_pfnMessageBox( parent, "GtkGenSurf 1.05\n\n" + "Original version\n" + "David Hyde (rascal@vicksburg.com)\n\n" + "Porting\n" + "Leonardo Zide (leo@lokigames.com)\n\n" + "Enhancements\n" + "Pablo Zurita (pablo@qeradiant.com)\n" + "Hydra (hydra@hydras-world.com)", + "About GtkGenSurf", eMB_OK ); } // ============================================================================= // main dialog -static void SetupControls () -{ - switch (current_tab) - { - case GENERAL_TAB: - break; - - case EXTENTS_TAB: - if (Game != QUAKE3) - { - gtk_widget_hide (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches"))); - ENABLE_WIDGET ("use_patches", FALSE); - } - else - { - gtk_widget_show (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches"))); - ENABLE_WIDGET ("use_patches", TRUE); - } - - if (Game == QUAKE3 && UsePatches != 0) - { - ENABLE_WIDGET ("decimate", FALSE); - } - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "snap_text")), "Snap to grid:"); // ^Fishman - Snap to grid. - break; - - case BITMAP_TAB: - if (WaveType != WAVE_BITMAP) - { - ENABLE_WIDGET ("bmp_file", FALSE); - ENABLE_WIDGET ("bmp_file_browse", FALSE); - ENABLE_WIDGET ("bmp_black", FALSE); - ENABLE_WIDGET ("bmp_white", FALSE); - ENABLE_WIDGET ("bmp_text1", FALSE); - ENABLE_WIDGET ("bmp_text2", FALSE); - ENABLE_WIDGET ("bmp_text3", FALSE); - ENABLE_WIDGET ("bmp_reload", FALSE); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "bmp_note")), - "These options are disabled unless \"From Bitmap\"\n" - "is selected as the Waveform on the General tab."); - } - else - { - ENABLE_WIDGET ("bmp_file", TRUE); - ENABLE_WIDGET ("bmp_file_browse", TRUE); - ENABLE_WIDGET ("bmp_black", TRUE); - ENABLE_WIDGET ("bmp_white", TRUE); - ENABLE_WIDGET ("bmp_text1", TRUE); - ENABLE_WIDGET ("bmp_text2", TRUE); - ENABLE_WIDGET ("bmp_text3", TRUE); - ENABLE_WIDGET ("bmp_reload", strlen(gbmp.name) != 0); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "bmp_note")), - "GenSurf works only with 8-bit bitmaps. Color indices are\n" - "mapped to values for each vertex. Generally, gray scale\n" - "images are stored with black as color 0, white as color 255."); - } - break; - - case FIXPOINTS_TAB: - ENABLE_WIDGET ("fix_value", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_value_text", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_free", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_range", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_range_text", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_rate", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_rate_text", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - break; - - case TEXTURE_TAB: - ENABLE_WIDGET ("texture2", (UsePatches == 0)); - ENABLE_WIDGET ("texture3", (UsePatches == 0)); - ENABLE_WIDGET ("tex_slant", (UsePatches == 0)); - ENABLE_WIDGET ("detail", (UsePatches == 0)); - if (Game != QUAKE3 ) +static void SetupControls(){ + switch ( current_tab ) + { + case GENERAL_TAB: + break; + + case EXTENTS_TAB: + if ( Game != QUAKE3 ) { + gtk_widget_hide( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "use_patches" ) ) ); + ENABLE_WIDGET( "use_patches", FALSE ); + } + else + { + gtk_widget_show( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "use_patches" ) ) ); + ENABLE_WIDGET( "use_patches", TRUE ); + } + + if ( Game == QUAKE3 && UsePatches != 0 ) { + ENABLE_WIDGET( "decimate", FALSE ); + } + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "snap_text" ) ), "Snap to grid:" ); // ^Fishman - Snap to grid. + break; + + case BITMAP_TAB: + if ( WaveType != WAVE_BITMAP ) { + ENABLE_WIDGET( "bmp_file", FALSE ); + ENABLE_WIDGET( "bmp_file_browse", FALSE ); + ENABLE_WIDGET( "bmp_black", FALSE ); + ENABLE_WIDGET( "bmp_white", FALSE ); + ENABLE_WIDGET( "bmp_text1", FALSE ); + ENABLE_WIDGET( "bmp_text2", FALSE ); + ENABLE_WIDGET( "bmp_text3", FALSE ); + ENABLE_WIDGET( "bmp_reload", FALSE ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_note" ) ), + "These options are disabled unless \"From Bitmap\"\n" + "is selected as the Waveform on the General tab." ); + } + else { - ENABLE_WIDGET ("terrain_ent", FALSE); // ^Fishman - Adds terrain key to func_group. - ENABLE_WIDGET ("hint", (UsePatches == 0)); + ENABLE_WIDGET( "bmp_file", TRUE ); + ENABLE_WIDGET( "bmp_file_browse", TRUE ); + ENABLE_WIDGET( "bmp_black", TRUE ); + ENABLE_WIDGET( "bmp_white", TRUE ); + ENABLE_WIDGET( "bmp_text1", TRUE ); + ENABLE_WIDGET( "bmp_text2", TRUE ); + ENABLE_WIDGET( "bmp_text3", TRUE ); + ENABLE_WIDGET( "bmp_reload", strlen( gbmp.name ) != 0 ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_note" ) ), + "GenSurf works only with 8-bit bitmaps. Color indices are\n" + "mapped to values for each vertex. Generally, gray scale\n" + "images are stored with black as color 0, white as color 255." ); } - break; - } - - switch (WaveType) - { - case WAVE_HCYLINDER: - case WAVE_VCYLINDER: - ENABLE_WIDGET ("amplitude", TRUE); - ENABLE_WIDGET ("wavelength", TRUE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - break; - case WAVE_BITMAP: - ENABLE_WIDGET ("amplitude", FALSE); - ENABLE_WIDGET ("wavelength", FALSE); - ENABLE_WIDGET ("z00", FALSE); - ENABLE_WIDGET ("z01", FALSE); - ENABLE_WIDGET ("z10", FALSE); - ENABLE_WIDGET ("z11", FALSE); - ENABLE_WIDGET ("linearborder", FALSE); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - break; - case WAVE_ROUGH_ONLY: - ENABLE_WIDGET ("amplitude", FALSE); - ENABLE_WIDGET ("wavelength", FALSE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - break; - default: - ENABLE_WIDGET ("amplitude", TRUE); - ENABLE_WIDGET ("wavelength", TRUE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - } - - switch (Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Z:"); - break; - case PLANE_YZ0: - case PLANE_YZ1: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Z:"); - break; - default: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Y:"); - break; - } + break; + + case FIXPOINTS_TAB: + ENABLE_WIDGET( "fix_value", ( NumVerticesSelected != 0 ) ); + ENABLE_WIDGET( "fix_value_text", ( NumVerticesSelected != 0 ) ); + ENABLE_WIDGET( "fix_free", ( NumVerticesSelected != 0 ) ); + ENABLE_WIDGET( "fix_range", ( ( NumVerticesSelected != 0 ) && ( WaveType != WAVE_ROUGH_ONLY ) ) ); + ENABLE_WIDGET( "fix_range_text", ( ( NumVerticesSelected != 0 ) && ( WaveType != WAVE_ROUGH_ONLY ) ) ); + ENABLE_WIDGET( "fix_rate", ( ( NumVerticesSelected != 0 ) && ( WaveType != WAVE_ROUGH_ONLY ) ) ); + ENABLE_WIDGET( "fix_rate_text", ( ( NumVerticesSelected != 0 ) && ( WaveType != WAVE_ROUGH_ONLY ) ) ); + break; + + case TEXTURE_TAB: + ENABLE_WIDGET( "texture2", ( UsePatches == 0 ) ); + ENABLE_WIDGET( "texture3", ( UsePatches == 0 ) ); + ENABLE_WIDGET( "tex_slant", ( UsePatches == 0 ) ); + ENABLE_WIDGET( "detail", ( UsePatches == 0 ) ); + if ( Game != QUAKE3 ) { + ENABLE_WIDGET( "terrain_ent", FALSE ); // ^Fishman - Adds terrain key to func_group. + ENABLE_WIDGET( "hint", ( UsePatches == 0 ) ); + } + break; + } + + switch ( WaveType ) + { + case WAVE_HCYLINDER: + case WAVE_VCYLINDER: + ENABLE_WIDGET( "amplitude", TRUE ); + ENABLE_WIDGET( "wavelength", TRUE ); + ENABLE_WIDGET( "z00", TRUE ); + ENABLE_WIDGET( "z01", TRUE ); + ENABLE_WIDGET( "z10", TRUE ); + ENABLE_WIDGET( "z11", TRUE ); + ENABLE_WIDGET( "linearborder", TRUE ); + ENABLE_WIDGET( "go", TRUE ); + break; + case WAVE_BITMAP: + ENABLE_WIDGET( "amplitude", FALSE ); + ENABLE_WIDGET( "wavelength", FALSE ); + ENABLE_WIDGET( "z00", FALSE ); + ENABLE_WIDGET( "z01", FALSE ); + ENABLE_WIDGET( "z10", FALSE ); + ENABLE_WIDGET( "z11", FALSE ); + ENABLE_WIDGET( "linearborder", FALSE ); + ENABLE_WIDGET( "go", ( gbmp.colors != NULL ? TRUE : FALSE ) ); + break; + case WAVE_ROUGH_ONLY: + ENABLE_WIDGET( "amplitude", FALSE ); + ENABLE_WIDGET( "wavelength", FALSE ); + ENABLE_WIDGET( "z00", TRUE ); + ENABLE_WIDGET( "z01", TRUE ); + ENABLE_WIDGET( "z10", TRUE ); + ENABLE_WIDGET( "z11", TRUE ); + ENABLE_WIDGET( "linearborder", TRUE ); + ENABLE_WIDGET( "go", TRUE ); + break; + default: + ENABLE_WIDGET( "amplitude", TRUE ); + ENABLE_WIDGET( "wavelength", TRUE ); + ENABLE_WIDGET( "z00", TRUE ); + ENABLE_WIDGET( "z01", TRUE ); + ENABLE_WIDGET( "z10", TRUE ); + ENABLE_WIDGET( "z11", TRUE ); + ENABLE_WIDGET( "linearborder", TRUE ); + ENABLE_WIDGET( "go", TRUE ); + } + + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmin_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmax_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmin_text" ) ), "Z:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmax_text" ) ), "Z:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nh_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nv_text" ) ), "Z:" ); + break; + case PLANE_YZ0: + case PLANE_YZ1: + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmin_text" ) ), "Y:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmax_text" ) ), "Y:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmin_text" ) ), "Z:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmax_text" ) ), "Z:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nh_text" ) ), "Y:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nv_text" ) ), "Z:" ); + break; + default: + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmin_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "hmax_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmin_text" ) ), "Y:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "vmax_text" ) ), "Y:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nh_text" ) ), "X:" ); + gtk_label_set_text( GTK_LABEL( g_object_get_data( G_OBJECT( g_pWnd ), "nv_text" ) ), "Y:" ); + break; + } } // SetDlgValues fills in text boxes and initializes other input controls -static void SetDlgValues (int tab) -{ - char Text[256]; - char RForm[16] = "%.5g"; - int i; - - switch (tab) - { - case GENERAL_TAB: - // Hell if I know why, but in the release build the 2nd pass thru the - // set_sensitive loop for game_radios crashes. No need to do this more - // than once anyhow. - if (!FirstPassComplete) - { - for (i = 0; i < NUMGAMES; i++) - gtk_widget_set_sensitive (game_radios[i], (i == Game ? TRUE : FALSE)); - for (i = 0; i < 6; i++) - gtk_widget_set_sensitive (plane_radios[i], (i == Plane ? TRUE : FALSE)); - } - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (game_radios[Game]), TRUE); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (plane_radios[Plane]), TRUE); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wave_radios[WaveType]), TRUE); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "random")), - RandomSeed); - sprintf (Text, RForm, WaveLength); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")), Text); - sprintf (Text, RForm, Amplitude); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")), Text); - sprintf (Text, RForm, Roughness); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "roughness")), Text); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "main_antialiasing")), Antialiasing); - break; - - case EXTENTS_TAB: - sprintf (Text,RForm,Hll); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "hmin")), Text); - sprintf (Text,RForm,Vll); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "vmin")), Text); - sprintf (Text,RForm,Hur); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "hmax")), Text); - sprintf (Text,RForm,Vur); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "vmax")), Text); - sprintf (Text,RForm,Z00); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z00")), Text); - sprintf (Text,RForm,Z01); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z01")), Text); - sprintf (Text,RForm,Z10); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z10")), Text); - sprintf (Text,RForm,Z11); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z11")), Text); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nh")), NH); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nv")), NV); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "sp")), SP); // ^Fishman - Snap to grid. - - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "linearborder")), FixBorders); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "use_patches")), UsePatches); - gtk_adjustment_set_value (GTK_ADJUSTMENT (g_object_get_data (G_OBJECT (g_pWnd), "decimate_adj")), - Decimate); - - if (Game == QUAKE3 && UsePatches) - { - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), FALSE); - - if (NH % 2) - { - NH++; - if (NH > MAX_ROWS) NH -= 2; - SetDlgValues (current_tab); - } - - if (NV % 2) - { - NV++; - if (NV > MAX_ROWS) NV -= 2; - SetDlgValues (current_tab); - } - if (NH % 2 ) NH++; - if (NH < 2 ) NH = 2; - if (NH > MAX_ROWS) NH = MAX_ROWS; - if (NV % 2 ) NV++; - if (NV < 2 ) NV = 2; - if (NV > MAX_ROWS) NV = MAX_ROWS; - - gpointer spin = g_object_get_data (G_OBJECT (g_pWnd), "nh"); - GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 2; - gtk_adjustment_changed (adj); - spin = g_object_get_data (G_OBJECT (g_pWnd), "nv"); - adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 2; - gtk_adjustment_changed (adj); - } - else - { - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), TRUE); - - gpointer spin = g_object_get_data (G_OBJECT (g_pWnd), "nh"); - GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 1; - gtk_adjustment_changed (adj); - spin = g_object_get_data (G_OBJECT (g_pWnd), "nv"); - adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 1; - gtk_adjustment_changed (adj); - } - - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nh")), NH); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nv")), NV); - - break; - - case BITMAP_TAB: - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), gbmp.name); - sprintf(Text,"%g",gbmp.black_value); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_black")), Text); - sprintf(Text,"%g",gbmp.white_value); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_white")), Text); - break; - - case FIXPOINTS_TAB: - break; - - case TEXTURE_TAB: - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture1")), Texture[Game][0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture2")), Texture[Game][1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture3")), Texture[Game][2]); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "tex_slant")), - SlantAngle); - sprintf(Text,RForm,TexOffset[0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texoffsetx")), Text); - sprintf(Text,RForm,TexOffset[1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texoffsety")), Text); - sprintf(Text,RForm,TexScale[0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texscalex")), Text); - sprintf(Text,RForm,TexScale[1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texscaley")), Text); - CHECK_WIDGET ("detail", UseDetail); - - if (Game==QUAKE3) - { - ENABLE_WIDGET ("hint", FALSE); - AddHints=0; - } - else - ENABLE_WIDGET ("hint", TRUE); - CHECK_WIDGET ("hint", AddHints); - - /* - if (Game==SIN) - { - // ArghRad doesn't currently support SiN - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); - } - */ - - if(Game==QUAKE3) - { - /* - // ArghRad sun is inapplicable (so far) - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - // No ladders in Q3 - EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pk3 file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"PK3:"); - */ - } +static void SetDlgValues( int tab ){ + char Text[256]; + char RForm[16] = "%.5g"; + int i; -/*trix if(Game==HERETIC2) - { - // ArghRad doesn't currently support Heretic2 - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pak file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Pak:"); - } */ - /* - if(Game==HALFLIFE) - { - // A bunch of controls aren't applicable to HL - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use wad file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Wad:"); - SetDlgItemText(hwndDisplay,DLG_HINT,"Hint brushes"); + switch ( tab ) + { + case GENERAL_TAB: + // Hell if I know why, but in the release build the 2nd pass thru the + // set_sensitive loop for game_radios crashes. No need to do this more + // than once anyhow. + if ( !FirstPassComplete ) { + for ( i = 0; i < NUMGAMES; i++ ) + gtk_widget_set_sensitive( game_radios[i], ( i == Game ? TRUE : FALSE ) ); + for ( i = 0; i < 6; i++ ) + gtk_widget_set_sensitive( plane_radios[i], ( i == Plane ? TRUE : FALSE ) ); } + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( game_radios[Game] ), TRUE ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( plane_radios[Plane] ), TRUE ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( wave_radios[WaveType] ), TRUE ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "random" ) ), + RandomSeed ); + sprintf( Text, RForm, WaveLength ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "wavelength" ) ), Text ); + sprintf( Text, RForm, Amplitude ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "amplitude" ) ), Text ); + sprintf( Text, RForm, Roughness ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "roughness" ) ), Text ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data + ( G_OBJECT( g_pWnd ), "main_antialiasing" ) ), Antialiasing ); + break; - if(Game==GENESIS3D) + case EXTENTS_TAB: + sprintf( Text,RForm,Hll ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "hmin" ) ), Text ); + sprintf( Text,RForm,Vll ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "vmin" ) ), Text ); + sprintf( Text,RForm,Hur ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "hmax" ) ), Text ); + sprintf( Text,RForm,Vur ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "vmax" ) ), Text ); + sprintf( Text,RForm,Z00 ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "z00" ) ), Text ); + sprintf( Text,RForm,Z01 ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "z01" ) ), Text ); + sprintf( Text,RForm,Z10 ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "z10" ) ), Text ); + sprintf( Text,RForm,Z11 ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "z11" ) ), Text ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "nh" ) ), NH ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "nv" ) ), NV ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "sp" ) ), SP ); // ^Fishman - Snap to grid. + + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data + ( G_OBJECT( g_pWnd ), "linearborder" ) ), FixBorders ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data + ( G_OBJECT( g_pWnd ), "use_patches" ) ), UsePatches ); + gtk_adjustment_set_value( GTK_ADJUSTMENT( g_object_get_data( G_OBJECT( g_pWnd ), "decimate_adj" ) ), + Decimate ); + + if ( Game == QUAKE3 && UsePatches ) { + gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "decimate" ) ), FALSE ); + + if ( NH % 2 ) { + NH++; + if ( NH > MAX_ROWS ) { + NH -= 2; + } + SetDlgValues( current_tab ); + } + + if ( NV % 2 ) { + NV++; + if ( NV > MAX_ROWS ) { + NV -= 2; + } + SetDlgValues( current_tab ); + } + if ( NH % 2 ) { + NH++; + } + if ( NH < 2 ) { + NH = 2; + } + if ( NH > MAX_ROWS ) { + NH = MAX_ROWS; + } + if ( NV % 2 ) { + NV++; + } + if ( NV < 2 ) { + NV = 2; + } + if ( NV > MAX_ROWS ) { + NV = MAX_ROWS; + } + + gpointer spin = g_object_get_data( G_OBJECT( g_pWnd ), "nh" ); + GtkAdjustment *adj = gtk_spin_button_get_adjustment( GTK_SPIN_BUTTON( spin ) ); + adj->lower = 2; + gtk_adjustment_changed( adj ); + spin = g_object_get_data( G_OBJECT( g_pWnd ), "nv" ); + adj = gtk_spin_button_get_adjustment( GTK_SPIN_BUTTON( spin ) ); + adj->lower = 2; + gtk_adjustment_changed( adj ); + } + else { - // No Q2-type compilers support Genesis3D (including ArghRad) - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); + gtk_widget_set_sensitive( GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "decimate" ) ), TRUE ); + + gpointer spin = g_object_get_data( G_OBJECT( g_pWnd ), "nh" ); + GtkAdjustment *adj = gtk_spin_button_get_adjustment( GTK_SPIN_BUTTON( spin ) ); + adj->lower = 1; + gtk_adjustment_changed( adj ); + spin = g_object_get_data( G_OBJECT( g_pWnd ), "nv" ); + adj = gtk_spin_button_get_adjustment( GTK_SPIN_BUTTON( spin ) ); + adj->lower = 1; + gtk_adjustment_changed( adj ); } - */ - break; - } - SetupControls (); + + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "nh" ) ), NH ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "nv" ) ), NV ); + + break; + + case BITMAP_TAB: + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ), gbmp.name ); + sprintf( Text,"%g",gbmp.black_value ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_black" ) ), Text ); + sprintf( Text,"%g",gbmp.white_value ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_white" ) ), Text ); + break; + + case FIXPOINTS_TAB: + break; + + case TEXTURE_TAB: + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texture1" ) ), Texture[Game][0] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texture2" ) ), Texture[Game][1] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texture3" ) ), Texture[Game][2] ); + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "tex_slant" ) ), + SlantAngle ); + sprintf( Text,RForm,TexOffset[0] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texoffsetx" ) ), Text ); + sprintf( Text,RForm,TexOffset[1] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texoffsety" ) ), Text ); + sprintf( Text,RForm,TexScale[0] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texscalex" ) ), Text ); + sprintf( Text,RForm,TexScale[1] ); + gtk_entry_set_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "texscaley" ) ), Text ); + CHECK_WIDGET( "detail", UseDetail ); + + if ( Game == QUAKE3 ) { + ENABLE_WIDGET( "hint", FALSE ); + AddHints = 0; + } + else{ + ENABLE_WIDGET( "hint", TRUE ); + } + CHECK_WIDGET( "hint", AddHints ); + + /* + if (Game==SIN) + { + // ArghRad doesn't currently support SiN + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); + SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); + SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); + } + */ + + if ( Game == QUAKE3 ) { + /* + // ArghRad sun is inapplicable (so far) + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); + // No ladders in Q3 + EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); + SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pk3 file"); + SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"PK3:"); + */ + } + +/*trix if(Game==HERETIC2) + { + // ArghRad doesn't currently support Heretic2 + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); + + SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pak file"); + SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Pak:"); + } */ + /* + if(Game==HALFLIFE) + { + // A bunch of controls aren't applicable to HL + EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); + + SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use wad file"); + SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Wad:"); + SetDlgItemText(hwndDisplay,DLG_HINT,"Hint brushes"); + } + + if(Game==GENESIS3D) + { + // No Q2-type compilers support Genesis3D (including ArghRad) + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); + EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); + ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); + + SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); + SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); + } + */ + break; + } + SetupControls(); } -static void ReadDlgValues (int tab) -{ - // char Text[256]; - // int i; - - switch (tab) - { - case GENERAL_TAB: - gpointer spin; - Roughness = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "roughness")))); - WaveLength = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")))); - Amplitude = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")))); - spin = g_object_get_data (G_OBJECT (g_pWnd), "random"); - RandomSeed = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (spin)); - break; - - case EXTENTS_TAB: - SP = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "sp")))); - NH = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "nh")))); - NV = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "nv")))); - - if (Game == QUAKE3 && UsePatches != 0) - { - if (NH % 2 ) NH++; - if (NH < 2 ) NH = 2; - if (NH > MAX_ROWS) NH = MAX_ROWS; - if (NV % 2 ) NV++; - if (NV < 2 ) NV = 2; - if (NV > MAX_ROWS) NV = MAX_ROWS; - } - break; +static void ReadDlgValues( int tab ){ + // char Text[256]; + // int i; + + switch ( tab ) + { + case GENERAL_TAB: + gpointer spin; + Roughness = atof( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "roughness" ) ) ) ); + WaveLength = atof( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "wavelength" ) ) ) ); + Amplitude = atof( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "amplitude" ) ) ) ); + spin = g_object_get_data( G_OBJECT( g_pWnd ), "random" ); + RandomSeed = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON( spin ) ); + break; + + case EXTENTS_TAB: + SP = atoi( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "sp" ) ) ) ); + NH = atoi( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "nh" ) ) ) ); + NV = atoi( gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "nv" ) ) ) ); + + if ( Game == QUAKE3 && UsePatches != 0 ) { + if ( NH % 2 ) { + NH++; + } + if ( NH < 2 ) { + NH = 2; + } + if ( NH > MAX_ROWS ) { + NH = MAX_ROWS; + } + if ( NV % 2 ) { + NV++; + } + if ( NV < 2 ) { + NV = 2; + } + if ( NV > MAX_ROWS ) { + NV = MAX_ROWS; + } + } + break; #if 0 - case BITMAP_TAB: - - if (WaveType == WAVE_BITMAP) - { - GetDlgItemText(hwnd,DLG_BMP_FILE,gbmp.name,sizeof(gbmp.name)); - CheckValidDIB(hwnd); - GetDlgItemText(hwnd,DLG_BMP_BLACK,Text,sizeof(Text)); - gbmp.black_value = atof(Text); - GetDlgItemText(hwnd,DLG_BMP_WHITE,Text,sizeof(Text)); - gbmp.white_value = atof(Text); - UpdatePreview(TRUE); - } - break; - - case FIXPOINTS_TAB: - GetDlgItemText(hwnd,DLG_FIX_VALUE,Text,sizeof(Text)); - temp.fixed_value = atoi(Text); - GetDlgItemText(hwnd,DLG_FIX_RANGE,Text,sizeof(Text)); - temp.range = atoi(Text); - GetDlgItemText(hwnd,DLG_FIX_RATE, Text,sizeof(Text)); - temp.rate = atof(Text); - for(k=0; k MAX_ROWS) - { - sprintf (Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (NV < 1 || NV > MAX_ROWS) - { - sprintf (Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (Hll >= Hur) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (Vll >= Vur) - { - g_FuncTable.m_pfnMessageBox (g_pWnd,"The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (!strlen (Texture[Game][0])) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "You must supply a texture name.", "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } +static void main_go( GtkWidget *widget, gpointer data ){ + GtkWidget *notebook = GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "notebook" ) ); + char Text[256]; + + ReadDlgValues( current_tab ); + if ( NH < 1 || NH > MAX_ROWS ) { + sprintf( Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS ); + g_FuncTable.m_pfnMessageBox( g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING ); + gtk_notebook_set_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); + return; + } + + if ( NV < 1 || NV > MAX_ROWS ) { + sprintf( Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS ); + g_FuncTable.m_pfnMessageBox( g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING ); + gtk_notebook_set_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); + return; + } + + if ( Hll >= Hur ) { + g_FuncTable.m_pfnMessageBox( g_pWnd, "The \"lower-left\" values must be less than " + "the corresponding \"upper-right\" values in " + "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); + gtk_notebook_set_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); + return; + } + + if ( Vll >= Vur ) { + g_FuncTable.m_pfnMessageBox( g_pWnd,"The \"lower-left\" values must be less than " + "the corresponding \"upper-right\" values in " + "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING ); + gtk_notebook_set_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); + return; + } + + if ( !strlen( Texture[Game][0] ) ) { + g_FuncTable.m_pfnMessageBox( g_pWnd, "You must supply a texture name.", "GenSurf", eMB_OK, eMB_ICONWARNING ); + gtk_notebook_set_page( GTK_NOTEBOOK( notebook ), EXTENTS_TAB ); + return; + } /* if (Decimate>0 && GimpHints!=0) - { + { MessageBox(hwnd,"You've elected to use a decimated grid and gimp's non-detail hint brushes. " "This combination usually produces bizarre visual errors in the game, " "so GenSurf has turned off the hint brush option.", "GenSurf",eMB_ICONWARNING); GimpHints = 0; - } */ + } */ - gtk_widget_hide (g_pWnd); - if (g_pWndPreview) - gtk_widget_hide (g_pWndPreview); + gtk_widget_hide( g_pWnd ); + if ( g_pWndPreview ) { + gtk_widget_hide( g_pWndPreview ); + } - GenerateMap(); - WriteIniFile(gszIni); + GenerateMap(); + WriteIniFile( gszIni ); } // ============================================================================= // general tab callbacks -static void general_game (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - Game = GPOINTER_TO_INT (data); - UpdatePreview (TRUE); - } +static void general_game( GtkToggleButton *widget, gpointer data ){ + if ( gtk_toggle_button_get_active( widget ) ) { + Game = GPOINTER_TO_INT( data ); + UpdatePreview( TRUE ); + } } -static void general_plane (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - Plane = GPOINTER_TO_INT (data); - SetupControls (); - UpdatePreview (TRUE); - } +static void general_plane( GtkToggleButton *widget, gpointer data ){ + if ( gtk_toggle_button_get_active( widget ) ) { + Plane = GPOINTER_TO_INT( data ); + SetupControls(); + UpdatePreview( TRUE ); + } } -static void general_wave (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - WaveType = GPOINTER_TO_INT (data); - SetupControls (); - UpdatePreview (TRUE); - } +static void general_wave( GtkToggleButton *widget, gpointer data ){ + if ( gtk_toggle_button_get_active( widget ) ) { + WaveType = GPOINTER_TO_INT( data ); + SetupControls(); + UpdatePreview( TRUE ); + } } -static void general_random (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; +static void general_random( GtkAdjustment *adj, gpointer data ){ + int nPos = (int)adj->value; - if (RandomSeed != nPos) - { - RandomSeed = nPos; - UpdatePreview (true); - } + if ( RandomSeed != nPos ) { + RandomSeed = nPos; + UpdatePreview( true ); + } } // ============================================================================= // extents tab callbacks -static void extents_linearborder (GtkToggleButton *check, gpointer data) -{ - FixBorders = gtk_toggle_button_get_active (check); - UpdatePreview (true); +static void extents_linearborder( GtkToggleButton *check, gpointer data ){ + FixBorders = gtk_toggle_button_get_active( check ); + UpdatePreview( true ); } -static void extents_use_patches (GtkToggleButton *check, gpointer data) -{ - if (Game != QUAKE3) - return; +static void extents_use_patches( GtkToggleButton *check, gpointer data ){ + if ( Game != QUAKE3 ) { + return; + } - UsePatches = gtk_toggle_button_get_active (check); - SetDlgValues (current_tab); - SetupControls (); - UpdatePreview (true); + UsePatches = gtk_toggle_button_get_active( check ); + SetDlgValues( current_tab ); + SetupControls(); + UpdatePreview( true ); } -static void extents_nhnv_spin (GtkAdjustment *adj, int *data) -{ - int nPos = (int)adj->value; - - if (*data != nPos) - { - if (Game==QUAKE3 && UsePatches && (nPos % 2)) - { - if (*data < nPos) - *data += 2; - else - *data -= 2; - gtk_adjustment_set_value (adj, *data); - } - else - *data = nPos; - UpdatePreview (true); - } +static void extents_nhnv_spin( GtkAdjustment *adj, int *data ){ + int nPos = (int)adj->value; + + if ( *data != nPos ) { + if ( Game == QUAKE3 && UsePatches && ( nPos % 2 ) ) { + if ( *data < nPos ) { + *data += 2; + } + else{ + *data -= 2; + } + gtk_adjustment_set_value( adj, *data ); + } + else{ + *data = nPos; + } + UpdatePreview( true ); + } } -static void extents_decimate (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; +static void extents_decimate( GtkAdjustment *adj, gpointer data ){ + int nPos = (int)adj->value; - Decimate = nPos; - UpdatePreview (true); + Decimate = nPos; + UpdatePreview( true ); } // Hydra : snap to grid begin /*static void extents_snaptogrid (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; + { + int nPos = (int)adj->value; - SnapToGrid = nPos; - UpdatePreview (true); -}*/ + SnapToGrid = nPos; + UpdatePreview (true); + }*/ // ^Fishman - Modified version of Hydra's snap to grid code. -static void extents_snaptogrid_spin (GtkAdjustment *adj, int *data) -{ +static void extents_snaptogrid_spin( GtkAdjustment *adj, int *data ){ int nPos = (int)adj->value; SnapToGrid = nPos; - UpdatePreview (true); + UpdatePreview( true ); } // ============================================================================= // bitmap tab callbacks -static gint bitmap_file_entryfocusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) -{ - char filename[NAME_MAX]; - - strcpy (filename, gtk_entry_get_text (GTK_ENTRY(widget))); - if(strcmp (filename,gbmp.name)) - { - strcpy (gbmp.name,filename); - if (strlen(gbmp.name) ) - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } - return FALSE; +static gint bitmap_file_entryfocusout( GtkWidget* widget, GdkEventFocus* event, gpointer data ){ + char filename[NAME_MAX]; + + strcpy( filename, gtk_entry_get_text( GTK_ENTRY( widget ) ) ); + if ( strcmp( filename,gbmp.name ) ) { + strcpy( gbmp.name,filename ); + if ( strlen( gbmp.name ) ) { + OpenBitmap(); + } + ENABLE_WIDGET( "go", ( gbmp.colors != NULL ? TRUE : FALSE ) ); + } + return FALSE; } -static void bitmap_browse (GtkWidget *widget, gpointer data) -{ - const char *filename; - char *ptr; +static void bitmap_browse( GtkWidget *widget, gpointer data ){ + const char *filename; + char *ptr; - filename = g_FuncTable.m_pfnFileDialog (g_pWnd, TRUE, "Bitmap File", gbmp.defpath); + filename = g_FuncTable.m_pfnFileDialog( g_pWnd, TRUE, "Bitmap File", gbmp.defpath ); - if (filename != NULL) - { - strcpy (gbmp.name, filename); + if ( filename != NULL ) { + strcpy( gbmp.name, filename ); - ptr = strrchr (filename, G_DIR_SEPARATOR); - if (ptr != NULL) - { - *(ptr+1) = '\0'; - strcpy (gbmp.defpath, filename); - } + ptr = strrchr( filename, G_DIR_SEPARATOR ); + if ( ptr != NULL ) { + *( ptr + 1 ) = '\0'; + strcpy( gbmp.defpath, filename ); + } - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } + OpenBitmap(); + ENABLE_WIDGET( "go", ( gbmp.colors != NULL ? TRUE : FALSE ) ); + } } -static void bitmap_reload (GtkWidget *widget, gpointer data) -{ - strcpy (gbmp.name, gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")))); - if(strlen (gbmp.name) ) - { - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } - else - ENABLE_WIDGET ("go", FALSE ); +static void bitmap_reload( GtkWidget *widget, gpointer data ){ + strcpy( gbmp.name, gtk_entry_get_text( GTK_ENTRY( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ) ) ); + if ( strlen( gbmp.name ) ) { + OpenBitmap(); + ENABLE_WIDGET( "go", ( gbmp.colors != NULL ? TRUE : FALSE ) ); + } + else{ + ENABLE_WIDGET( "go", FALSE ); + } } // ============================================================================= // fix points tab callbacks -static gint fix_value_entryfocusout (GtkWidget* widget, GdkEventFocus *event, gpointer data) -{ - int i = atoi (gtk_entry_get_text (GTK_ENTRY(widget))), k; - char Text[32]; - - if (i < -65536 || i > 65536) - { - gdk_beep (); - g_FuncTable.m_pfnMessageBox (g_pWnd, "The value must be between -65536 and 65536, inclusive.", - "GenSurf", eMB_OK, eMB_ICONWARNING); - sprintf (Text, "%d", (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value); - gtk_entry_set_text (GTK_ENTRY(widget), Text); - gtk_window_set_focus (GTK_WINDOW (gtk_widget_get_toplevel (widget)), widget); - } - else if (i != xyz[Vertex[0].i][Vertex[0].j].fixed_value) - { - for(k=0; k 65536 ) { + gdk_beep(); + g_FuncTable.m_pfnMessageBox( g_pWnd, "The value must be between -65536 and 65536, inclusive.", + "GenSurf", eMB_OK, eMB_ICONWARNING ); + sprintf( Text, "%d", (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); + gtk_entry_set_text( GTK_ENTRY( widget ), Text ); + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( widget ) ), widget ); + } + else if ( i != xyz[Vertex[0].i][Vertex[0].j].fixed_value ) { + for ( k = 0; k < NumVerticesSelected; k++ ) + xyz[Vertex[k].i][Vertex[k].j].fixed_value = i; + + gtk_spin_button_set_value( GTK_SPIN_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "fix_value" ) ), + (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value ); + UpdatePreview( true ); + } + return FALSE; } -static void fix_value_changed (GtkAdjustment *adj, gpointer data) -{ - int k, i = (int)adj->value; +static void fix_value_changed( GtkAdjustment *adj, gpointer data ){ + int k, i = (int)adj->value; - if (xyz[Vertex[0].i][Vertex[0].j].fixed_value != i) - { - for(k=0; k(data)); - return FALSE; +static gint doublevariable_entryfocusout( GtkWidget* widget, GdkEventFocus* event, gpointer data ){ + UpdateVariable( GTK_ENTRY( widget ), event, reinterpret_cast( data ) ); + return FALSE; } // ============================================================================= // create tooltips -void create_tooltips () -{ - tooltips = gtk_tooltips_new (); - - // Main - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "go")), - "Accept all input and generate a surface in Q3Radiant", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "open")), - "Open a previously saved GenSurf settings file.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "save")), - "Save all settings to a file.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "defaults")), - "Restore default values from DEFAULTS.SRF. If this file does not exist, GenSurf " - "initializes all input parameters to reasonable values. You can create your own " - "default surface by setting all parameters to your liking, then saving a settings " - "file as DEFAULTS.SRF with the Save As button.", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "main_preview")), - "View a wire-frame representation of the surface", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "main_antialiasing")), - "The lines in the preview window are antialiased for better quality", - ""); - - // General tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[0]), - "Builds a surface with alternating hills and valleys. Uses the general form Z=cos(X) " - "x sin(Y)", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[1]), - "Builds a surface with ridges parallel to the vertical axis.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[2]), - "Builds a surface with ridges parallel to the horizontal axis.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[3]), - "Builds a map from a bitmap image representing a contour plot. Click the \"Bitmap\" " - "tab to select the image. GenSurf only supports 256-color (8 bit) " - "bitmaps. GenSurf will work with any 256-color bitmap, but gray scale bitmaps are a bit " - "more intuitive.", - "" ); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[4]), - "Builds a random surface using the Plasma Cloud technique. Variance is controlled " - "by the Roughness input. To build a surface with completely random values not " - "dependent on neighboring vertices, use one of the other waveforms with 0 amplitude.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")), - "Enter the wavelength (distance between crests). NOTE: Wavelengths equal to the grid " - "size or 2 times the grid size will result in 0 amplitudes. For best results, the " - "wavelength value should be at least 4 times the grid size (extents divided by the " - "number of divisions", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")), - "Enter the height of hills/ridges.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "roughness")), - "Enter the roughness value (noise) for the surface. For fractal surfaces, this value " - "is used as a variance in the fractal calculations.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "random")), - "Seed value for the pseudo-random number generator.", - ""); - // Extents tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "hmin")), - "Minimum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "hmax")), - "Maximum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "vmin")), - "Minimum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "vmax")), - "Maximum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "nh")), - "Number of divisions in the horizontal direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "nv")), - "Number of divisions in the vertical direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches")), - "Produce one or more curved patches in the shape of your selected surface rather " - "than producing solid brushes. Depending on the size of your surface (and the " - "user's graphic detail settings, which you cannot control), curved surfaces will " - "be represented in the game by a very large number of polygons. Read the warnings " - "concerning curved surfaces on the GenSurf web page before using this feature.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), - "Use the slider to control the number of vertices discarded by GenSurf. For many " - "surfaces, you can produce roughly the same shape surface with a high decimation " - "value. This will generally result in a map with lower polygon counts (and better " - "in-game performance). However, this feature should NOT be used for large terrain " - "surfaces in Q3", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z00")), - "Enter the height of the surface at the lower left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z01")), - "Enter the height of the surface at the upper left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z10")), - "Enter the height of the surface at the lower right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z11")), - "Enter the height of the surface at the upper right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "linearborder")), - "Restrict the edges of the surface to a straight line. This will help match up " - "brush edges if you drop this surface into another map.", - ""); - // Bitmap tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), - "Type the name of an 8-bit bitmap image file, or click Browse to select an image " - "from a list of those available on your system.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file_browse")), - "Select a bitmap image file from a list of those available on your system.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_reload")), - "Reload the selected bitmap file after making changes in an external image editor.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_black")), - "Enter the value corresponding to color index 0 in the bitmap file. For gray scale " - "images, color 0 is normally black.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_white")), - "Enter the value corresponding to color index 255 in the bitmap file. For gray scale " - "images, color 255 is normally white.", - ""); - // Fixpoints tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_value")), - "Enter a value for the selected vertex. This value will not be adjusted when applying " - "a waveform or roughness to the surface. Unlock this vertex (so that it will be " - "adjusted normally) by clicking \"Free\". This vertex will influence vertices within " - "the \"Range affected\" of this vertex.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_range")), - "Enter the range away from the selected vertex that other vertices will be affected. " - "Use 0 if you don't want other vertices to be influenced by the currently selected " - "one. Note: this box is disabled if you've chosen the fractal generator, as it uses " - "a completely different method for determining values.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_rate")), - "Enter a rate of change for the surface affected by the fixed value. 0 gives a smooth " - "sinusoidal curve, values less than 0 give progressively sharper spikes, and values " - "greater than 0 take on a square shape. Values less than -30 or greater than 30 are " - "set to -30 and 30, respectively. Note that this entry will have no effect unless " - "you also specify a \"range affected\".", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_free")), - "Click this to free (unlock the value of) the currently selected vertex.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_freeall")), - "Click this to free (unlock the values of) all vertices.", - ""); - // Texture tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture1")), - "Enter the name of the texture or shader used for the surface faces.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture2")), - "Enter the name of the texture or shader used for faces other than the surface. Under " - "normal circumstances this should be \"common/caulk\"", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture3")), - "Enter the name of the texture or shader used for \"steep\" surface faces, where \"steep\" " - "is the angle specified below. If this entry is left blank or if the \"steep\" angle is 0, " - "all surface faces will use the texture specified by \"Surface\".", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "detail")), - "Check this box to use the detail content property on the generated brushes. Compile " - "times will be considerably shorter if the detail property is used, though the surface " - "will not block visibility at all. If you use the detail property, you should make sure " - "that \"common/caulk\" is used for the non-surface faces, or the polygon count will be " - "much higher than necessary.", - ""); +void create_tooltips(){ + tooltips = gtk_tooltips_new(); + + // Main + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "go" ) ), + "Accept all input and generate a surface in Q3Radiant", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "open" ) ), + "Open a previously saved GenSurf settings file.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "save" ) ), + "Save all settings to a file.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "defaults" ) ), + "Restore default values from DEFAULTS.SRF. If this file does not exist, GenSurf " + "initializes all input parameters to reasonable values. You can create your own " + "default surface by setting all parameters to your liking, then saving a settings " + "file as DEFAULTS.SRF with the Save As button.", + "" ); + + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "main_preview" ) ), + "View a wire-frame representation of the surface", + "" ); + + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "main_antialiasing" ) ), + "The lines in the preview window are antialiased for better quality", + "" ); + + // General tab + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( wave_radios[0] ), + "Builds a surface with alternating hills and valleys. Uses the general form Z=cos(X) " + "x sin(Y)", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( wave_radios[1] ), + "Builds a surface with ridges parallel to the vertical axis.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( wave_radios[2] ), + "Builds a surface with ridges parallel to the horizontal axis.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( wave_radios[3] ), + "Builds a map from a bitmap image representing a contour plot. Click the \"Bitmap\" " + "tab to select the image. GenSurf only supports 256-color (8 bit) " + "bitmaps. GenSurf will work with any 256-color bitmap, but gray scale bitmaps are a bit " + "more intuitive.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( wave_radios[4] ), + "Builds a random surface using the Plasma Cloud technique. Variance is controlled " + "by the Roughness input. To build a surface with completely random values not " + "dependent on neighboring vertices, use one of the other waveforms with 0 amplitude.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "wavelength" ) ), + "Enter the wavelength (distance between crests). NOTE: Wavelengths equal to the grid " + "size or 2 times the grid size will result in 0 amplitudes. For best results, the " + "wavelength value should be at least 4 times the grid size (extents divided by the " + "number of divisions", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "amplitude" ) ), + "Enter the height of hills/ridges.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "roughness" ) ), + "Enter the roughness value (noise) for the surface. For fractal surfaces, this value " + "is used as a variance in the fractal calculations.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "random" ) ), + "Seed value for the pseudo-random number generator.", + "" ); + // Extents tab + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "hmin" ) ), + "Minimum horizontal coordinate of the surface, i.e. X for a surface parallel to " + "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "hmax" ) ), + "Maximum horizontal coordinate of the surface, i.e. X for a surface parallel to " + "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "vmin" ) ), + "Minimum vertical coordinate of the surface, i.e. Y for a surface parallel to " + "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "vmax" ) ), + "Maximum vertical coordinate of the surface, i.e. Y for a surface parallel to " + "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " + "the extents (maximum-minimum values) in a given direction should be evenly " + "divisible by the number of divisions in that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "nh" ) ), + "Number of divisions in the horizontal direction. For best results, the extents " + "in a given direction should be evenly divisible by the number of divisions in " + "that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "nv" ) ), + "Number of divisions in the vertical direction. For best results, the extents " + "in a given direction should be evenly divisible by the number of divisions in " + "that direction.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "use_patches" ) ), + "Produce one or more curved patches in the shape of your selected surface rather " + "than producing solid brushes. Depending on the size of your surface (and the " + "user's graphic detail settings, which you cannot control), curved surfaces will " + "be represented in the game by a very large number of polygons. Read the warnings " + "concerning curved surfaces on the GenSurf web page before using this feature.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "decimate" ) ), + "Use the slider to control the number of vertices discarded by GenSurf. For many " + "surfaces, you can produce roughly the same shape surface with a high decimation " + "value. This will generally result in a map with lower polygon counts (and better " + "in-game performance). However, this feature should NOT be used for large terrain " + "surfaces in Q3", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z00" ) ), + "Enter the height of the surface at the lower left corner. This value will likely " + "be modified unless \"Linear Borders\" is checked.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z01" ) ), + "Enter the height of the surface at the upper left corner. This value will likely " + "be modified unless \"Linear Borders\" is checked.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z10" ) ), + "Enter the height of the surface at the lower right corner. This value will likely " + "be modified unless \"Linear Borders\" is checked.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "z11" ) ), + "Enter the height of the surface at the upper right corner. This value will likely " + "be modified unless \"Linear Borders\" is checked.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "linearborder" ) ), + "Restrict the edges of the surface to a straight line. This will help match up " + "brush edges if you drop this surface into another map.", + "" ); + // Bitmap tab + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file" ) ), + "Type the name of an 8-bit bitmap image file, or click Browse to select an image " + "from a list of those available on your system.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_file_browse" ) ), + "Select a bitmap image file from a list of those available on your system.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_reload" ) ), + "Reload the selected bitmap file after making changes in an external image editor.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_black" ) ), + "Enter the value corresponding to color index 0 in the bitmap file. For gray scale " + "images, color 0 is normally black.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "bmp_white" ) ), + "Enter the value corresponding to color index 255 in the bitmap file. For gray scale " + "images, color 255 is normally white.", + "" ); + // Fixpoints tab + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_value" ) ), + "Enter a value for the selected vertex. This value will not be adjusted when applying " + "a waveform or roughness to the surface. Unlock this vertex (so that it will be " + "adjusted normally) by clicking \"Free\". This vertex will influence vertices within " + "the \"Range affected\" of this vertex.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_range" ) ), + "Enter the range away from the selected vertex that other vertices will be affected. " + "Use 0 if you don't want other vertices to be influenced by the currently selected " + "one. Note: this box is disabled if you've chosen the fractal generator, as it uses " + "a completely different method for determining values.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_rate" ) ), + "Enter a rate of change for the surface affected by the fixed value. 0 gives a smooth " + "sinusoidal curve, values less than 0 give progressively sharper spikes, and values " + "greater than 0 take on a square shape. Values less than -30 or greater than 30 are " + "set to -30 and 30, respectively. Note that this entry will have no effect unless " + "you also specify a \"range affected\".", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_free" ) ), + "Click this to free (unlock the value of) the currently selected vertex.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "fix_freeall" ) ), + "Click this to free (unlock the values of) all vertices.", + "" ); + // Texture tab + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture1" ) ), + "Enter the name of the texture or shader used for the surface faces.", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture2" ) ), + "Enter the name of the texture or shader used for faces other than the surface. Under " + "normal circumstances this should be \"common/caulk\"", + "" ); + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "texture3" ) ), + "Enter the name of the texture or shader used for \"steep\" surface faces, where \"steep\" " + "is the angle specified below. If this entry is left blank or if the \"steep\" angle is 0, " + "all surface faces will use the texture specified by \"Surface\".", + "" ); + + gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), + GTK_WIDGET( g_object_get_data( G_OBJECT( g_pWnd ), "detail" ) ), + "Check this box to use the detail content property on the generated brushes. Compile " + "times will be considerably shorter if the detail property is used, though the surface " + "will not block visibility at all. If you use the detail property, you should make sure " + "that \"common/caulk\" is used for the non-surface faces, or the polygon count will be " + "much higher than necessary.", + "" ); } // ============================================================================= // create main dialog -GtkWidget* create_main_dialog () -{ - GtkWidget *dlg, *vbox, *hbox, *hbox2, *button, *notebook, *frame, *table, *table2; - GtkWidget *check, *spin, *radio, *label, *entry, *scale; - GtkObject *adj; - GSList *group; - int i; - const char *games[] = { "Quake 2", "Half-Life", "SiN", "Heretic 2", "Kingpin", "Genesis3D", "Quake 3 Arena" }; - const char *waveforms[] = { "Alternating hill/valley", "Cylindrical left-to-right", "Cylindrical top-to-bottom", - "From bitmap", "Fractal" }; - const char *orientations[] = { "Ground surface", "Ceiling", "Wall facing 0", "Wall facing 90", - "Wall facing 180","Wall facing 270" }; - - g_pWnd = dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), gszCaption); - g_signal_connect (G_OBJECT (dlg), "delete_event", G_CALLBACK (main_close), NULL); - // g_signal_connect (G_OBJECT (dlg), "destroy", G_CALLBACK (gtk_widget_destroy), NULL); - gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (g_pRadiantWnd)); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_container_add (GTK_CONTAINER (dlg), hbox); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 5); - - notebook = gtk_notebook_new (); - gtk_widget_show (notebook); - gtk_box_pack_start (GTK_BOX (hbox), notebook, TRUE, TRUE, 0); - g_signal_connect (G_OBJECT (notebook), "switch_page", - G_CALLBACK (switch_page), NULL); - gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP); - g_object_set_data (G_OBJECT (dlg), "notebook", notebook); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("General"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), table, label); - - frame = gtk_frame_new ("Game"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < NUMGAMES; i++) - { - radio = gtk_radio_button_new_with_label (group, games[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - game_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_game), GINT_TO_POINTER (i)); - } - - frame = gtk_frame_new ("Waveform"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < 5; i++) - { - radio = gtk_radio_button_new_with_label (group, waveforms[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - wave_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_wave), GINT_TO_POINTER (i)); - } - - frame = gtk_frame_new ("Orientation"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < 6; i++) - { - radio = gtk_radio_button_new_with_label (group, orientations[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - plane_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_plane), GINT_TO_POINTER (i)); - } - - table2 = gtk_table_new (4, 2, FALSE); - gtk_widget_show (table2); - gtk_table_set_row_spacings (GTK_TABLE (table2), 5); - gtk_table_set_col_spacings (GTK_TABLE (table2), 5); - gtk_table_attach (GTK_TABLE (table), table2, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - label = gtk_label_new ("Wavelength:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Max. amplitude:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Roughness:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Random seed:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 3, 4, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "wavelength", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &WaveLength); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "amplitude", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Amplitude); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "roughness", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Roughness); - - adj = gtk_adjustment_new (1, 1, 32767, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (general_random), NULL); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table2), spin, 1, 2, 3, 4, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "random", spin); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Extents"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 0); - - frame = gtk_frame_new ("Extents"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (hbox2), frame, TRUE, TRUE, 0); - - table = gtk_table_new (3, 4, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "hmin_text", label); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "hmax_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "vmin_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "vmax_text", label); - - label = gtk_label_new ("Lower-left"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Upper-right"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 3, 4, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "hmin", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Hll); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "hmax", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Hur); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "vmin", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Vll); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "vmax", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Vur); - - frame = gtk_frame_new ("Divisions"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (hbox2), frame, TRUE, TRUE, 0); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "nh_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "nv_text", label); - - adj = gtk_adjustment_new (8, 1, MAX_ROWS, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_nhnv_spin), &NH); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "nh", spin); - - adj = gtk_adjustment_new (8, 1, MAX_ROWS, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_nhnv_spin), &NV); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "nv", spin); - - check = gtk_check_button_new_with_label ("Use Bezier patches"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "use_patches", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (extents_use_patches), NULL); +GtkWidget* create_main_dialog(){ + GtkWidget *dlg, *vbox, *hbox, *hbox2, *button, *notebook, *frame, *table, *table2; + GtkWidget *check, *spin, *radio, *label, *entry, *scale; + GtkObject *adj; + GSList *group; + int i; + const char *games[] = { "Quake 2", "Half-Life", "SiN", "Heretic 2", "Kingpin", "Genesis3D", "Quake 3 Arena" }; + const char *waveforms[] = { "Alternating hill/valley", "Cylindrical left-to-right", "Cylindrical top-to-bottom", + "From bitmap", "Fractal" }; + const char *orientations[] = { "Ground surface", "Ceiling", "Wall facing 0", "Wall facing 90", + "Wall facing 180","Wall facing 270" }; + + g_pWnd = dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( dlg ), gszCaption ); + g_signal_connect( G_OBJECT( dlg ), "delete_event", G_CALLBACK( main_close ), NULL ); + // g_signal_connect (G_OBJECT (dlg), "destroy", G_CALLBACK (gtk_widget_destroy), NULL); + gtk_window_set_transient_for( GTK_WINDOW( dlg ), GTK_WINDOW( g_pRadiantWnd ) ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_container_add( GTK_CONTAINER( dlg ), hbox ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ), 5 ); + + notebook = gtk_notebook_new(); + gtk_widget_show( notebook ); + gtk_box_pack_start( GTK_BOX( hbox ), notebook, TRUE, TRUE, 0 ); + g_signal_connect( G_OBJECT( notebook ), "switch_page", + G_CALLBACK( switch_page ), NULL ); + gtk_notebook_set_tab_pos( GTK_NOTEBOOK( notebook ), GTK_POS_TOP ); + g_object_set_data( G_OBJECT( dlg ), "notebook", notebook ); + + table = gtk_table_new( 2, 2, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "General" ); + gtk_widget_show( label ); + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), table, label ); + + frame = gtk_frame_new( "Game" ); + gtk_widget_show( frame ); + gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + vbox = gtk_vbox_new( TRUE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( frame ), vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + for ( i = 0, group = NULL; i < NUMGAMES; i++ ) + { + radio = gtk_radio_button_new_with_label( group, games[i] ); + gtk_widget_show( radio ); + gtk_box_pack_start( GTK_BOX( vbox ), radio, TRUE, TRUE, 0 ); + group = gtk_radio_button_group( GTK_RADIO_BUTTON( radio ) ); + game_radios[i] = radio; + g_signal_connect( G_OBJECT( radio ), "toggled", G_CALLBACK( general_game ), GINT_TO_POINTER( i ) ); + } + + frame = gtk_frame_new( "Waveform" ); + gtk_widget_show( frame ); + gtk_table_attach( GTK_TABLE( table ), frame, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + vbox = gtk_vbox_new( TRUE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( frame ), vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + for ( i = 0, group = NULL; i < 5; i++ ) + { + radio = gtk_radio_button_new_with_label( group, waveforms[i] ); + gtk_widget_show( radio ); + gtk_box_pack_start( GTK_BOX( vbox ), radio, TRUE, TRUE, 0 ); + group = gtk_radio_button_group( GTK_RADIO_BUTTON( radio ) ); + wave_radios[i] = radio; + g_signal_connect( G_OBJECT( radio ), "toggled", G_CALLBACK( general_wave ), GINT_TO_POINTER( i ) ); + } + + frame = gtk_frame_new( "Orientation" ); + gtk_widget_show( frame ); + gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + vbox = gtk_vbox_new( TRUE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( frame ), vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + for ( i = 0, group = NULL; i < 6; i++ ) + { + radio = gtk_radio_button_new_with_label( group, orientations[i] ); + gtk_widget_show( radio ); + gtk_box_pack_start( GTK_BOX( vbox ), radio, TRUE, TRUE, 0 ); + group = gtk_radio_button_group( GTK_RADIO_BUTTON( radio ) ); + plane_radios[i] = radio; + g_signal_connect( G_OBJECT( radio ), "toggled", G_CALLBACK( general_plane ), GINT_TO_POINTER( i ) ); + } + + table2 = gtk_table_new( 4, 2, FALSE ); + gtk_widget_show( table2 ); + gtk_table_set_row_spacings( GTK_TABLE( table2 ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table2 ), 5 ); + gtk_table_attach( GTK_TABLE( table ), table2, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Wavelength:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + label = gtk_label_new( "Max. amplitude:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + label = gtk_label_new( "Roughness:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + label = gtk_label_new( "Random seed:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table2 ), label, 0, 1, 3, 4, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "wavelength", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &WaveLength ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "amplitude", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Amplitude ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table2 ), entry, 1, 2, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "roughness", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Roughness ); + + adj = gtk_adjustment_new( 1, 1, 32767, 1, 10, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( general_random ), NULL ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_table_attach( GTK_TABLE( table2 ), spin, 1, 2, 3, 4, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( spin, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "random", spin ); + + vbox = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + label = gtk_label_new( "Extents" ); + gtk_widget_show( label ); + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), vbox, label ); + + hbox2 = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox2 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox2, FALSE, TRUE, 0 ); + + frame = gtk_frame_new( "Extents" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( hbox2 ), frame, TRUE, TRUE, 0 ); + + table = gtk_table_new( 3, 4, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "X:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "hmin_text", label ); + + label = gtk_label_new( "X:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "hmax_text", label ); + + label = gtk_label_new( "Y:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "vmin_text", label ); + + label = gtk_label_new( "Y:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 2, 3, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "vmax_text", label ); + + label = gtk_label_new( "Lower-left" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Upper-right" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "hmin", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Hll ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "hmax", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Hur ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "vmin", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Vll ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "vmax", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Vur ); + + frame = gtk_frame_new( "Divisions" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( hbox2 ), frame, TRUE, TRUE, 0 ); + + table = gtk_table_new( 2, 2, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "X:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "nh_text", label ); + + label = gtk_label_new( "Y:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "nv_text", label ); + + adj = gtk_adjustment_new( 8, 1, MAX_ROWS, 1, 10, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( extents_nhnv_spin ), &NH ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( spin, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "nh", spin ); + + adj = gtk_adjustment_new( 8, 1, MAX_ROWS, 1, 10, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( extents_nhnv_spin ), &NV ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( spin, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "nv", spin ); + + check = gtk_check_button_new_with_label( "Use Bezier patches" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "use_patches", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( extents_use_patches ), NULL ); // ^Fishman - Snap to grid, replaced scroll bar with a texbox. - label = gtk_label_new ("Snap to grid:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - gtk_object_set_data (GTK_OBJECT (dlg), "snap_text", label); - - adj = gtk_adjustment_new (8, 0, 256, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_snaptogrid_spin), &SP); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (vbox), spin, FALSE, TRUE, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "sp", spin); + label = gtk_label_new( "Snap to grid:" ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, TRUE, 0 ); + gtk_object_set_data( GTK_OBJECT( dlg ), "snap_text", label ); + + adj = gtk_adjustment_new( 8, 0, 256, 1, 10, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( extents_snaptogrid_spin ), &SP ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_box_pack_start( GTK_BOX( vbox ), spin, FALSE, TRUE, 0 ); + gtk_widget_set_usize( spin, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "sp", spin ); // ^Fishman - End of Snap to grid code. - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 10); - - label = gtk_label_new ("Decimate:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (0, 0, 110, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_decimate), NULL); - g_object_set_data (G_OBJECT (dlg), "decimate_adj", adj); - scale = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (scale); - gtk_box_pack_start (GTK_BOX (hbox2), scale, TRUE, TRUE, 0); - gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_RIGHT); - gtk_scale_set_digits (GTK_SCALE (scale), 0); - g_object_set_data (G_OBJECT (dlg), "decimate", scale); - - frame = gtk_frame_new ("Corner values"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (3, 4, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Upper-left:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Lower-left:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Upper-right:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Lower-right:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z01", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z01); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z00", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z00); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z11", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z11); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z10", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z10); - - check = gtk_check_button_new_with_label ("Linear borders"); - gtk_widget_show (check); - gtk_table_attach (GTK_TABLE (table), check, 0, 4, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "linearborder", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (extents_linearborder), NULL); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Bitmap"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - label = gtk_label_new (""); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_note", label); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Filename:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text1", label); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_file", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (bitmap_file_entryfocusout), NULL); - - hbox2 = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - button = gtk_button_new_with_label ("Browse..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox2), button, FALSE, FALSE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_file_browse", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (bitmap_browse), NULL); - - button = gtk_button_new_with_label ("Reload"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox2), button, FALSE, FALSE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_reload", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (bitmap_reload), NULL); - - table = gtk_table_new (2, 2, TRUE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Map color 0 to:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL|GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text2", label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Map color 255 to:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL|GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text3", label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_box_pack_start (GTK_BOX (hbox2), entry, FALSE, FALSE, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_black", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &gbmp.black_value); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_box_pack_start (GTK_BOX (hbox2), entry, FALSE, FALSE, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_white", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &gbmp.white_value); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Fix Points"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - label = gtk_label_new ("Click on a vertex in the lower half of the preview window,\n" - "then use the arrow keys or text box to assign a value.\n" - "Use Ctrl+Click to select multiple vertices/toggle a\n" - "selection. Use Shift+Click to select a range of vertices.\n\n" - "Click \"Free\" to unlock a vertex. Vertices within \"Range\n" - "affected\" will be influenced by this vertex."); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - - table = gtk_table_new (3, 3, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Value:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_value_text", label); - - label = gtk_label_new ("Range affected:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_range_text", label); - - label = gtk_label_new ("Rate of change:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_rate_text", label); - - adj = gtk_adjustment_new (0, -65536, 65536, 1, 16, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (fix_value_changed), NULL); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_EXPAND), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_value", spin); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (fix_value_entryfocusout), NULL); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_range", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (fix_range_entryfocusout), NULL); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_rate", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (fix_rate_entryfocusout), NULL); - - button = gtk_button_new_with_label ("Free"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_free", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (fix_free), NULL); - - button = gtk_button_new_with_label ("Free All"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_freeall", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (fix_freeall), NULL); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Texture"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); + hbox2 = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox2 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox2, FALSE, TRUE, 10 ); + + label = gtk_label_new( "Decimate:" ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( hbox2 ), label, FALSE, TRUE, 0 ); + + adj = gtk_adjustment_new( 0, 0, 110, 1, 10, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( extents_decimate ), NULL ); + g_object_set_data( G_OBJECT( dlg ), "decimate_adj", adj ); + scale = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); + gtk_widget_show( scale ); + gtk_box_pack_start( GTK_BOX( hbox2 ), scale, TRUE, TRUE, 0 ); + gtk_scale_set_value_pos( GTK_SCALE( scale ), GTK_POS_RIGHT ); + gtk_scale_set_digits( GTK_SCALE( scale ), 0 ); + g_object_set_data( G_OBJECT( dlg ), "decimate", scale ); + + frame = gtk_frame_new( "Corner values" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, FALSE, TRUE, 0 ); + + table = gtk_table_new( 3, 4, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_container_add( GTK_CONTAINER( frame ), table ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Upper-left:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Lower-left:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Upper-right:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Lower-right:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "z01", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z01 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "z00", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z00 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "z11", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z11 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "z10", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &Z10 ); + + check = gtk_check_button_new_with_label( "Linear borders" ); + gtk_widget_show( check ); + gtk_table_attach( GTK_TABLE( table ), check, 0, 4, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "linearborder", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( extents_linearborder ), NULL ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_widget_show( vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + label = gtk_label_new( "Bitmap" ); + gtk_widget_show( label ); + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), vbox, label ); + + label = gtk_label_new( "" ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_note", label ); + + table = gtk_table_new( 2, 2, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Filename:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_text1", label ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_file", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( bitmap_file_entryfocusout ), NULL ); + + hbox2 = gtk_hbox_new( TRUE, 5 ); + gtk_widget_show( hbox2 ); + gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 1, 2, + (GtkAttachOptions) ( 0 ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + button = gtk_button_new_with_label( "Browse..." ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( hbox2 ), button, FALSE, FALSE, 0 ); + gtk_widget_set_usize( button, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_file_browse", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( bitmap_browse ), NULL ); + + button = gtk_button_new_with_label( "Reload" ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( hbox2 ), button, FALSE, FALSE, 0 ); + gtk_widget_set_usize( button, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_reload", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( bitmap_reload ), NULL ); + + table = gtk_table_new( 2, 2, TRUE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Map color 0 to:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_text2", label ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + label = gtk_label_new( "Map color 255 to:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL | GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_text3", label ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_RIGHT ); + + hbox2 = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox2 ); + gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_box_pack_start( GTK_BOX( hbox2 ), entry, FALSE, FALSE, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_black", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &gbmp.black_value ); + + hbox2 = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox2 ); + gtk_table_attach( GTK_TABLE( table ), hbox2, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_box_pack_start( GTK_BOX( hbox2 ), entry, FALSE, FALSE, 0 ); + gtk_widget_set_usize( entry, 50, -2 ); + g_object_set_data( G_OBJECT( dlg ), "bmp_white", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( doublevariable_entryfocusout ), &gbmp.white_value ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_widget_show( vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + label = gtk_label_new( "Fix Points" ); + gtk_widget_show( label ); + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), vbox, label ); + + label = gtk_label_new( "Click on a vertex in the lower half of the preview window,\n" + "then use the arrow keys or text box to assign a value.\n" + "Use Ctrl+Click to select multiple vertices/toggle a\n" + "selection. Use Shift+Click to select a range of vertices.\n\n" + "Click \"Free\" to unlock a vertex. Vertices within \"Range\n" + "affected\" will be influenced by this vertex." ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, TRUE, 0 ); + + table = gtk_table_new( 3, 3, FALSE ); + gtk_widget_show( table ); + gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Value:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + g_object_set_data( G_OBJECT( dlg ), "fix_value_text", label ); + + label = gtk_label_new( "Range affected:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + g_object_set_data( G_OBJECT( dlg ), "fix_range_text", label ); + + label = gtk_label_new( "Rate of change:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + g_object_set_data( G_OBJECT( dlg ), "fix_rate_text", label ); + + adj = gtk_adjustment_new( 0, -65536, 65536, 1, 16, 0 ); + g_signal_connect( G_OBJECT( adj ), "value_changed", G_CALLBACK( fix_value_changed ), NULL ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_table_attach( GTK_TABLE( table ), spin, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_EXPAND ), 0, 0 ); + gtk_widget_set_usize( spin, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "fix_value", spin ); + g_signal_connect( G_OBJECT( spin ), "focus_out_event", G_CALLBACK( fix_value_entryfocusout ), NULL ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "fix_range", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( fix_range_entryfocusout ), NULL ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "fix_rate", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( fix_rate_entryfocusout ), NULL ); + + button = gtk_button_new_with_label( "Free" ); + gtk_widget_show( button ); + gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( button, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "fix_free", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( fix_free ), NULL ); + + button = gtk_button_new_with_label( "Free All" ); + gtk_widget_show( button ); + gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( button, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "fix_freeall", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( fix_freeall ), NULL ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_widget_show( vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + label = gtk_label_new( "Texture" ); + gtk_widget_show( label ); + gtk_notebook_append_page( GTK_NOTEBOOK( notebook ), vbox, label ); // ^Fishman - Modified to add more labels and textboxes. - table = gtk_table_new (5, 2, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Surface:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - label = gtk_label_new ("Other:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - label = gtk_label_new ("Steep:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture1", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK(texture_entryfocusout), GINT_TO_POINTER (0)); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture2", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK(texture_entryfocusout), GINT_TO_POINTER (1)); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture3", entry); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 0); - - label = gtk_label_new ("\"Steep\" angle:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (60, 0, 90, 1, 10, 0); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (hbox2), spin, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "tex_slant", spin); - - table = gtk_table_new (2, 4, TRUE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Offset "); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Scale "); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 4, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texoffsetx", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texoffsety", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texscalex", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texscaley", entry); - - - - check = gtk_check_button_new_with_label ("Use detail brushes"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "detail", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_detail), NULL); - - check = gtk_check_button_new_with_label ("Detail hint brushes"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "hint", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_hint), NULL); + table = gtk_table_new( 5, 2, FALSE ); + gtk_widget_show( table ); + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Surface:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + + label = gtk_label_new( "Other:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + + label = gtk_label_new( "Steep:" ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texture1", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( texture_entryfocusout ), GINT_TO_POINTER( 0 ) ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texture2", entry ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( texture_entryfocusout ), GINT_TO_POINTER( 1 ) ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 2, 3, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texture3", entry ); + + hbox2 = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox2 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox2, FALSE, TRUE, 0 ); + + label = gtk_label_new( "\"Steep\" angle:" ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( hbox2 ), label, FALSE, TRUE, 0 ); + + adj = gtk_adjustment_new( 60, 0, 90, 1, 10, 0 ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_box_pack_start( GTK_BOX( hbox2 ), spin, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "tex_slant", spin ); + + table = gtk_table_new( 2, 4, TRUE ); + gtk_widget_show( table ); + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + label = gtk_label_new( "Offset " ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 0, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + label = gtk_label_new( "Scale " ); + gtk_widget_show( label ); + gtk_table_attach( GTK_TABLE( table ), label, 2, 4, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texoffsetx", entry ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texoffsety", entry ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texscalex", entry ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_table_attach( GTK_TABLE( table ), entry, 3, 4, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( GTK_FILL ), 0, 0 ); + gtk_widget_set_usize( entry, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "texscaley", entry ); + + + + check = gtk_check_button_new_with_label( "Use detail brushes" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "detail", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( texture_detail ), NULL ); + + check = gtk_check_button_new_with_label( "Detail hint brushes" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "hint", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( texture_hint ), NULL ); // ^Fishman - Add terrain key to func_group. - check = gtk_check_button_new_with_label ("Add terrain key"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "terrain_ent", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_terrainent), NULL); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, TRUE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "go", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_go), NULL); - - label = gtk_label_new ("Settings:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - - button = gtk_button_new_with_label ("Open..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "open", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_open), NULL); - - button = gtk_button_new_with_label ("Save as..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "save", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_save), NULL); - - button = gtk_button_new_with_label ("Defaults"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "defaults", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_defaults), NULL); - - button = gtk_button_new_with_label ("About..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_about), NULL); - - check = gtk_check_button_new_with_label ("Preview"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (main_preview), NULL); - g_object_set_data (G_OBJECT (dlg), "main_preview", check); + check = gtk_check_button_new_with_label( "Add terrain key" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "terrain_ent", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( texture_terrainent ), NULL ); + + vbox = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox ); + gtk_box_pack_start( GTK_BOX( hbox ), vbox, FALSE, TRUE, 0 ); + + button = gtk_button_new_with_label( "OK" ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, TRUE, 0 ); + gtk_widget_set_usize( button, 60, -2 ); + g_object_set_data( G_OBJECT( dlg ), "go", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( main_go ), NULL ); + + label = gtk_label_new( "Settings:" ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, TRUE, 0 ); + + button = gtk_button_new_with_label( "Open..." ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "open", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( main_open ), NULL ); + + button = gtk_button_new_with_label( "Save as..." ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "save", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( main_save ), NULL ); + + button = gtk_button_new_with_label( "Defaults" ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "defaults", button ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( main_defaults ), NULL ); + + button = gtk_button_new_with_label( "About..." ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, TRUE, 0 ); + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( main_about ), NULL ); + + check = gtk_check_button_new_with_label( "Preview" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( main_preview ), NULL ); + g_object_set_data( G_OBJECT( dlg ), "main_preview", check ); // ^Fishman - Antializing for the preview window. - check = gtk_check_button_new_with_label ("Antialised lines"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "main_antialiasing", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (main_antialiasing), NULL); + check = gtk_check_button_new_with_label( "Antialised lines" ); + gtk_widget_show( check ); + gtk_box_pack_start( GTK_BOX( vbox ), check, FALSE, TRUE, 0 ); + g_object_set_data( G_OBJECT( dlg ), "main_antialiasing", check ); + g_signal_connect( G_OBJECT( check ), "toggled", G_CALLBACK( main_antialiasing ), NULL ); - for (i = 0; i < 5; i++) - SetDlgValues (i); + for ( i = 0; i < 5; i++ ) + SetDlgValues( i ); - CreateViewWindow (); + CreateViewWindow(); - create_tooltips(); + create_tooltips(); - FirstPassComplete = 1; + FirstPassComplete = 1; - return dlg; + return dlg; } @@ -2237,123 +2202,118 @@ GtkWidget* create_main_dialog () HWND hwndDisplay = (HWND)NULL; HWND ghwndTab = (HWND)NULL; -int iTab=0; +int iTab = 0; Rect rcTab; FILE *ftex; char GenSurfURL[40] = {"http://tarot.telefragged.com/gensurf"}; -char GenSurfBoard[40]={"http://tarot.telefragged.com/board"}; +char GenSurfBoard[40] = {"http://tarot.telefragged.com/board"}; /* -* AboutDlgProc - processes messages for the about dialog. -*/ + * AboutDlgProc - processes messages for the about dialog. + */ -qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lparam ) -{ - char szText[256]; +qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lparam ){ + char szText[256]; DRAWITEMSTRUCT *dis; - HDC hdc; - HPEN hpen; - HWND hwndURL; - Rect rc; - SIZE size; + HDC hdc; + HPEN hpen; + HWND hwndURL; + Rect rc; + SIZE size; - lparam = lparam; /* turn off warning */ + lparam = lparam; /* turn off warning */ - switch( msg ) { + switch ( msg ) { case WM_INITDIALOG: - strcpy(szText,"About " ); - strcat(szText,gszCaption); - SetWindowText(hwnd,gszCaption); - SetDlgItemText(hwnd,DLG_ABOUT_APP,szText); + strcpy( szText,"About " ); + strcat( szText,gszCaption ); + SetWindowText( hwnd,gszCaption ); + SetDlgItemText( hwnd,DLG_ABOUT_APP,szText ); /* Application icon: */ SendDlgItemMessage( hwnd, DLG_ABOUT_ICON, - STM_SETICON, (WPARAM)(HICON)LoadIcon(ghInst,"GENSURF"), - (LPARAM) NULL); - - hwndURL = GetDlgItem(hwnd,DLG_ABOUT_URL); - hdc = GetDC(hwndURL); - GetTextExtentPoint(hdc,GenSurfURL,strlen(GenSurfURL),&size); - ReleaseDC(hwndURL,hdc); - GetWindowRect(hwndURL,&rc); - SetWindowPos(hwndURL,(HWND)NULL,0,0,size.cx,size.cy+2, - SWP_NOMOVE | SWP_NOZORDER); - - hwndURL = GetDlgItem(hwnd,DLG_ABOUT_BOARD); - hdc = GetDC(hwndURL); - GetTextExtentPoint(hdc,GenSurfBoard,strlen(GenSurfBoard),&size); - ReleaseDC(hwndURL,hdc); - GetWindowRect(hwndURL,&rc); - SetWindowPos(hwndURL,(HWND)NULL,0,0,size.cx,size.cy+2, - SWP_NOMOVE | SWP_NOZORDER); + STM_SETICON, (WPARAM)(HICON)LoadIcon( ghInst,"GENSURF" ), + (LPARAM) NULL ); + + hwndURL = GetDlgItem( hwnd,DLG_ABOUT_URL ); + hdc = GetDC( hwndURL ); + GetTextExtentPoint( hdc,GenSurfURL,strlen( GenSurfURL ),&size ); + ReleaseDC( hwndURL,hdc ); + GetWindowRect( hwndURL,&rc ); + SetWindowPos( hwndURL,(HWND)NULL,0,0,size.cx,size.cy + 2, + SWP_NOMOVE | SWP_NOZORDER ); + + hwndURL = GetDlgItem( hwnd,DLG_ABOUT_BOARD ); + hdc = GetDC( hwndURL ); + GetTextExtentPoint( hdc,GenSurfBoard,strlen( GenSurfBoard ),&size ); + ReleaseDC( hwndURL,hdc ); + GetWindowRect( hwndURL,&rc ); + SetWindowPos( hwndURL,(HWND)NULL,0,0,size.cx,size.cy + 2, + SWP_NOMOVE | SWP_NOZORDER ); return TRUE; case WM_COMMAND: - switch(LOWORD(wparam)) + switch ( LOWORD( wparam ) ) { case DLG_ABOUT_URL: - HTTP(GenSurfURL); + HTTP( GenSurfURL ); break; case DLG_ABOUT_BOARD: - HTTP(GenSurfBoard); + HTTP( GenSurfBoard ); break; case IDOK: - EndDialog(hwnd,1); + EndDialog( hwnd,1 ); return TRUE; } break; case WM_DRAWITEM: - if(wparam == DLG_ABOUT_URL) - { + if ( wparam == DLG_ABOUT_URL ) { dis = (LPDRAWITEMSTRUCT)lparam; - SetTextColor(dis->hDC,RGB(0,0,255)); - TextOut(dis->hDC,0,0,GenSurfURL,strlen(GenSurfURL)); - GetWindowRect(dis->hwndItem,&rc); - GetTextExtentPoint(dis->hDC,GenSurfURL,strlen(GenSurfURL),&size); - hpen = CreatePen(PS_SOLID,0,RGB(0,0,255)); - SelectObject(dis->hDC,hpen); - MoveToEx(dis->hDC,0,size.cy,NULL); - LineTo(dis->hDC,size.cx,size.cy); - SelectObject(dis->hDC,GetStockObject(BLACK_PEN)); - DeleteObject(hpen); + SetTextColor( dis->hDC,RGB( 0,0,255 ) ); + TextOut( dis->hDC,0,0,GenSurfURL,strlen( GenSurfURL ) ); + GetWindowRect( dis->hwndItem,&rc ); + GetTextExtentPoint( dis->hDC,GenSurfURL,strlen( GenSurfURL ),&size ); + hpen = CreatePen( PS_SOLID,0,RGB( 0,0,255 ) ); + SelectObject( dis->hDC,hpen ); + MoveToEx( dis->hDC,0,size.cy,NULL ); + LineTo( dis->hDC,size.cx,size.cy ); + SelectObject( dis->hDC,GetStockObject( BLACK_PEN ) ); + DeleteObject( hpen ); } - else if(wparam==DLG_ABOUT_BOARD) - { + else if ( wparam == DLG_ABOUT_BOARD ) { dis = (LPDRAWITEMSTRUCT)lparam; - SetTextColor(dis->hDC,RGB(0,0,255)); - TextOut(dis->hDC,0,0,GenSurfBoard,strlen(GenSurfBoard)); - GetWindowRect(dis->hwndItem,&rc); - GetTextExtentPoint(dis->hDC,GenSurfBoard,strlen(GenSurfBoard),&size); - hpen = CreatePen(PS_SOLID,0,RGB(0,0,255)); - SelectObject(dis->hDC,hpen); - MoveToEx(dis->hDC,0,size.cy,NULL); - LineTo(dis->hDC,size.cx,size.cy); - SelectObject(dis->hDC,GetStockObject(BLACK_PEN)); - DeleteObject(hpen); + SetTextColor( dis->hDC,RGB( 0,0,255 ) ); + TextOut( dis->hDC,0,0,GenSurfBoard,strlen( GenSurfBoard ) ); + GetWindowRect( dis->hwndItem,&rc ); + GetTextExtentPoint( dis->hDC,GenSurfBoard,strlen( GenSurfBoard ),&size ); + hpen = CreatePen( PS_SOLID,0,RGB( 0,0,255 ) ); + SelectObject( dis->hDC,hpen ); + MoveToEx( dis->hDC,0,size.cy,NULL ); + LineTo( dis->hDC,size.cx,size.cy ); + SelectObject( dis->hDC,GetStockObject( BLACK_PEN ) ); + DeleteObject( hpen ); } break; case WM_CLOSE: - EndDialog(hwnd,1); + EndDialog( hwnd,1 ); return TRUE; default: return FALSE; } return FALSE; - + } /* AboutDlgProc */ -void About() -{ - if( DialogBox( ghInst,"About", ghwnd_main, (DLGPROC)AboutDlgProc ) < 0) - { +void About(){ + if ( DialogBox( ghInst,"About", ghwnd_main, (DLGPROC)AboutDlgProc ) < 0 ) { char Text[256]; - sprintf(Text,"In About(), GetLastError()=0x%08x",GetLastError()); - MessageBox(ghwnd_main,Text,"GenSurf",eMB_ICONWARNING); + sprintf( Text,"In About(), GetLastError()=0x%08x",GetLastError() ); + MessageBox( ghwnd_main,Text,"GenSurf",eMB_ICONWARNING ); } } -#endif +#endif diff --git a/contrib/gtkgensurf/gendlgs.h b/contrib/gtkgensurf/gendlgs.h index dd954678..d4df4374 100644 --- a/contrib/gtkgensurf/gendlgs.h +++ b/contrib/gtkgensurf/gendlgs.h @@ -1,151 +1,151 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#define DLG_PLANE_XY0 100 -#define DLG_PLANE_XY1 101 -#define DLG_PLANE_YZ0 102 -#define DLG_PLANE_XZ0 103 -#define DLG_PLANE_YZ1 104 -#define DLG_PLANE_XZ1 105 -#define DLG_WAVE_01 106 -#define DLG_WAVE_02 107 -#define DLG_WAVE_03 108 -#define DLG_WAVE_04 109 -#define DLG_WAVE_05 110 -#define DLG_WAVE_06 111 -#define DLG_LAMBDA 112 -#define DLG_LAMBDA_TEXT 113 -#define DLG_AMP 114 -#define DLG_AMP_TEXT 115 -#define DLG_ROUGH 116 -#define DLG_ROUGH_TEXT 117 -#define DLG_LINEARBORDER 118 -#define DLG_FILE 119 -#define DLG_FILE_BROWSE 120 -#define DLG_PREVIEW 121 -#define DLG_GO 122 -#define DLG_ABOUT 123 -#define DLG_NH_TEXT 124 -#define DLG_NH 125 -#define DLG_NH_SPIN 126 -#define DLG_NV_TEXT 127 -#define DLG_NV 128 -#define DLG_NV_SPIN 129 -#define DLG_HMIN_TEXT 130 -#define DLG_HMIN 131 -#define DLG_HMAX_TEXT 132 -#define DLG_HMAX 133 -#define DLG_VMIN_TEXT 134 -#define DLG_VMIN 135 -#define DLG_VMAX_TEXT 136 -#define DLG_VMAX 137 -#define DLG_Z00_TEXT 138 -#define DLG_Z00 139 -#define DLG_Z01_TEXT 140 -#define DLG_Z01 141 -#define DLG_Z10_TEXT 142 -#define DLG_Z10 143 -#define DLG_Z11_TEXT 144 -#define DLG_Z11 145 -#define DLG_TEXTURE 146 -#define DLG_SKYBOX 147 -#define DLG_AUTOOVERWRITE 148 -#define DLG_DETAIL 149 -#define DLG_ARGHRAD2 150 -#define DLG_ARGHRAD2_SPIN 151 -#define DLG_APPEND 152 -#define DLG_REFRESH 153 -#define DLG_TEXOFFSETX 154 -#define DLG_TEXOFFSETY 155 -#define DLG_TEXSCALEX 156 -#define DLG_TEXSCALEY 157 -#define DLG_FIXPOINTS 158 -#define DLG_TEXTURE_BROWSE 159 -#define DLG_AZIMUTH 162 -#define DLG_AZIMUTH_SPIN 163 -#define DLG_ELEVATION 164 -#define DLG_ELEVATION_SPIN 165 -#define DLG_RANDOMSEED 166 -#define DLG_RANDOMSEED_SPIN 167 -#define DLG_BITMAP 168 -#define DLG_SAVE 169 -#define DLG_OPEN 170 -#define DLG_TAB 171 -#define DLG_TEXTURE2 172 -#define DLG_TEXTURE2_BROWSE 173 -#define DLG_LADDER 174 -#define DLG_ARGHRAD2_TEXT 175 -#define DLG_FILE_TEXT 176 -#define DLG_DECIMATE 177 -#define DLG_DECIMATE_TEXT 178 -#define DLG_HIDEBACKFACES 179 -#define DLG_DEFAULTS 180 -#define DLG_ABOUT_APP 200 -#define DLG_ABOUT_ICON 201 -#define DLG_BMP_FILE 202 -#define DLG_BMP_FILE_BROWSE 203 -#define DLG_BMP_BLACK 204 -#define DLG_BMP_WHITE 205 -#define DLG_BMP_TEXT1 206 -#define DLG_BMP_TEXT2 207 -#define DLG_BMP_TEXT3 208 -#define DLG_BMP_NOTE 209 -#define DLG_BMP_RELOAD 210 -#define DLG_ABOUT_URL 211 -#define DLG_ABOUT_BOARD 212 -#define DLG_FIX_FREE 300 -#define DLG_FIX_FREEALL 301 -#define DLG_FIX_VALUE_TEXT 302 -#define DLG_FIX_VALUE 303 -#define DLG_FIX_VALUE_SPIN 304 -#define DLG_FIX_DONE 305 -#define DLG_FIX_RANGE_TEXT 306 -#define DLG_FIX_RANGE 307 -#define DLG_FIX_NOTE 308 -#define DLG_FIX_RATE_TEXT 309 -#define DLG_FIX_RATE 310 -#define DLG_USE_PATCHES 311 -#define DLG_DECIMATE_LABEL 312 -#define DLG_HINT 350 -#define DLG_GAME_00 400 -#define DLG_GAME_01 401 -#define DLG_GAME_02 402 -#define DLG_GAME_03 403 -#define DLG_GAME_04 404 -#define DLG_GAME_05 405 -#define DLG_GAME_06 406 -#define DLG_GAME_07 407 -#define DLG_GAME_08 408 -#define DLG_GAME_09 409 -#define DLG_TEX_USEPAK 420 -#define DLG_TEX_PAK_TEXT 421 -#define DLG_TEX_PAKFILE 422 -#define DLG_TEX_PAK_BROWSE 423 -#define DLG_TEX_LIST1 424 -#define DLG_TEX_LIST2 425 -#define DLG_TEX_LIST3 426 -#define DLG_TEXTURE3 427 -#define DLG_TEXTURE3_BROWSE 428 -#define DLG_TEX_SLANT_TEXT 429 -#define DLG_TEX_SLANT 430 -#define DLG_TEX_SLANT_SPIN 431 -#define DLG_EXCEL_FUNC 500 -#define DLG_EXCEL_FUNC_TEXT 501 -#define DLG_PREVIEW_ANTIALIASING 502 // ^Fishman - Antializing for the preview window. -#define DLG_SNAP_TO_GRID 503 // Hydra : snap to grid +#define DLG_PLANE_XY0 100 +#define DLG_PLANE_XY1 101 +#define DLG_PLANE_YZ0 102 +#define DLG_PLANE_XZ0 103 +#define DLG_PLANE_YZ1 104 +#define DLG_PLANE_XZ1 105 +#define DLG_WAVE_01 106 +#define DLG_WAVE_02 107 +#define DLG_WAVE_03 108 +#define DLG_WAVE_04 109 +#define DLG_WAVE_05 110 +#define DLG_WAVE_06 111 +#define DLG_LAMBDA 112 +#define DLG_LAMBDA_TEXT 113 +#define DLG_AMP 114 +#define DLG_AMP_TEXT 115 +#define DLG_ROUGH 116 +#define DLG_ROUGH_TEXT 117 +#define DLG_LINEARBORDER 118 +#define DLG_FILE 119 +#define DLG_FILE_BROWSE 120 +#define DLG_PREVIEW 121 +#define DLG_GO 122 +#define DLG_ABOUT 123 +#define DLG_NH_TEXT 124 +#define DLG_NH 125 +#define DLG_NH_SPIN 126 +#define DLG_NV_TEXT 127 +#define DLG_NV 128 +#define DLG_NV_SPIN 129 +#define DLG_HMIN_TEXT 130 +#define DLG_HMIN 131 +#define DLG_HMAX_TEXT 132 +#define DLG_HMAX 133 +#define DLG_VMIN_TEXT 134 +#define DLG_VMIN 135 +#define DLG_VMAX_TEXT 136 +#define DLG_VMAX 137 +#define DLG_Z00_TEXT 138 +#define DLG_Z00 139 +#define DLG_Z01_TEXT 140 +#define DLG_Z01 141 +#define DLG_Z10_TEXT 142 +#define DLG_Z10 143 +#define DLG_Z11_TEXT 144 +#define DLG_Z11 145 +#define DLG_TEXTURE 146 +#define DLG_SKYBOX 147 +#define DLG_AUTOOVERWRITE 148 +#define DLG_DETAIL 149 +#define DLG_ARGHRAD2 150 +#define DLG_ARGHRAD2_SPIN 151 +#define DLG_APPEND 152 +#define DLG_REFRESH 153 +#define DLG_TEXOFFSETX 154 +#define DLG_TEXOFFSETY 155 +#define DLG_TEXSCALEX 156 +#define DLG_TEXSCALEY 157 +#define DLG_FIXPOINTS 158 +#define DLG_TEXTURE_BROWSE 159 +#define DLG_AZIMUTH 162 +#define DLG_AZIMUTH_SPIN 163 +#define DLG_ELEVATION 164 +#define DLG_ELEVATION_SPIN 165 +#define DLG_RANDOMSEED 166 +#define DLG_RANDOMSEED_SPIN 167 +#define DLG_BITMAP 168 +#define DLG_SAVE 169 +#define DLG_OPEN 170 +#define DLG_TAB 171 +#define DLG_TEXTURE2 172 +#define DLG_TEXTURE2_BROWSE 173 +#define DLG_LADDER 174 +#define DLG_ARGHRAD2_TEXT 175 +#define DLG_FILE_TEXT 176 +#define DLG_DECIMATE 177 +#define DLG_DECIMATE_TEXT 178 +#define DLG_HIDEBACKFACES 179 +#define DLG_DEFAULTS 180 +#define DLG_ABOUT_APP 200 +#define DLG_ABOUT_ICON 201 +#define DLG_BMP_FILE 202 +#define DLG_BMP_FILE_BROWSE 203 +#define DLG_BMP_BLACK 204 +#define DLG_BMP_WHITE 205 +#define DLG_BMP_TEXT1 206 +#define DLG_BMP_TEXT2 207 +#define DLG_BMP_TEXT3 208 +#define DLG_BMP_NOTE 209 +#define DLG_BMP_RELOAD 210 +#define DLG_ABOUT_URL 211 +#define DLG_ABOUT_BOARD 212 +#define DLG_FIX_FREE 300 +#define DLG_FIX_FREEALL 301 +#define DLG_FIX_VALUE_TEXT 302 +#define DLG_FIX_VALUE 303 +#define DLG_FIX_VALUE_SPIN 304 +#define DLG_FIX_DONE 305 +#define DLG_FIX_RANGE_TEXT 306 +#define DLG_FIX_RANGE 307 +#define DLG_FIX_NOTE 308 +#define DLG_FIX_RATE_TEXT 309 +#define DLG_FIX_RATE 310 +#define DLG_USE_PATCHES 311 +#define DLG_DECIMATE_LABEL 312 +#define DLG_HINT 350 +#define DLG_GAME_00 400 +#define DLG_GAME_01 401 +#define DLG_GAME_02 402 +#define DLG_GAME_03 403 +#define DLG_GAME_04 404 +#define DLG_GAME_05 405 +#define DLG_GAME_06 406 +#define DLG_GAME_07 407 +#define DLG_GAME_08 408 +#define DLG_GAME_09 409 +#define DLG_TEX_USEPAK 420 +#define DLG_TEX_PAK_TEXT 421 +#define DLG_TEX_PAKFILE 422 +#define DLG_TEX_PAK_BROWSE 423 +#define DLG_TEX_LIST1 424 +#define DLG_TEX_LIST2 425 +#define DLG_TEX_LIST3 426 +#define DLG_TEXTURE3 427 +#define DLG_TEXTURE3_BROWSE 428 +#define DLG_TEX_SLANT_TEXT 429 +#define DLG_TEX_SLANT 430 +#define DLG_TEX_SLANT_SPIN 431 +#define DLG_EXCEL_FUNC 500 +#define DLG_EXCEL_FUNC_TEXT 501 +#define DLG_PREVIEW_ANTIALIASING 502 // ^Fishman - Antializing for the preview window. +#define DLG_SNAP_TO_GRID 503 // Hydra : snap to grid diff --git a/contrib/gtkgensurf/genmap.cpp b/contrib/gtkgensurf/genmap.cpp index 6e9c95dc..a31bfbcb 100644 --- a/contrib/gtkgensurf/genmap.cpp +++ b/contrib/gtkgensurf/genmap.cpp @@ -1,34 +1,34 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include #include #include "gensurf.h" -double xmin,xmax,ymin,ymax,zmin,zmax; -double backface; +double xmin,xmax,ymin,ymax,zmin,zmax; +double backface; extern double dh, dv; FILE *fmap; -XYZ xyz[MAX_ROWS+1][MAX_ROWS+1]; -int contents; -int surface[3]; +XYZ xyz[MAX_ROWS + 1][MAX_ROWS + 1]; +int contents; +int surface[3]; #include "iundo.h" @@ -47,1994 +47,2042 @@ scene::Node* h_worldspawn; //============================================================= // Hydra : snap-to-grid begin -double CalculateSnapValue(double value) -{ - long snapvalue; +double CalculateSnapValue( double value ){ + long snapvalue; - // simple uncomplicated snapping, rounding both UP and DOWN to the nearest + // simple uncomplicated snapping, rounding both UP and DOWN to the nearest // grid unit. - if (SnapToGrid >0) - { + if ( SnapToGrid > 0 ) { snapvalue = (int)value / SnapToGrid; - if ((long)value % SnapToGrid < (SnapToGrid / 2)) // Snap Downwards if less than halfway between to grid units - value = snapvalue * SnapToGrid; - else // Snap Upwards if more than halfway between to grid units - value = (snapvalue+1) * SnapToGrid; + if ( (long)value % SnapToGrid < ( SnapToGrid / 2 ) ) { // Snap Downwards if less than halfway between to grid units + value = snapvalue * SnapToGrid; + } + else{ // Snap Upwards if more than halfway between to grid units + value = ( snapvalue + 1 ) * SnapToGrid; + } } - return value; + return value; } // Hydra : snap-to-grid end //============================================================= -bool ValidSurface() -{ - if(WaveType == WAVE_BITMAP && !gbmp.colors) return FALSE; - if(NH < 1) return FALSE; - if(NH > MAX_ROWS) return FALSE; - if(NV < 1) return FALSE; - if(NV > MAX_ROWS) return FALSE; - if(Hll >= Hur) return FALSE; - if(Vll >= Vur) return FALSE; - return TRUE; +bool ValidSurface(){ + if ( WaveType == WAVE_BITMAP && !gbmp.colors ) { + return FALSE; + } + if ( NH < 1 ) { + return FALSE; + } + if ( NH > MAX_ROWS ) { + return FALSE; + } + if ( NV < 1 ) { + return FALSE; + } + if ( NV > MAX_ROWS ) { + return FALSE; + } + if ( Hll >= Hur ) { + return FALSE; + } + if ( Vll >= Vur ) { + return FALSE; + } + return TRUE; } //============================================================= -int MapPatches() -{ - int NH_remain; - int NV_remain; - int NH_patch; - int NV_patch; - int BrushNum = 0; - int i, j, k1, k2, k3; - int i0, j0, ii; - char szOops[128]; - - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - - // Generate control points in pp array to give desired values currently - // in p array. - switch(Plane) - { - case PLANE_XY0: - case PLANE_XY1: - k1 = 0; - k2 = 1; - k3 = 2; - break; - case PLANE_XZ0: - case PLANE_XZ1: - k1 = 0; - k2 = 2; - k3 = 1; - break; - case PLANE_YZ0: - case PLANE_YZ1: - k1 = 1; - k2 = 2; - k3 = 0; - break; - } - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].pp[k1] = xyz[i][j].p[k1]; - xyz[i][j].pp[k2] = xyz[i][j].p[k2]; - } - } - for(i=0; i<=NH; i+=2) - { - for(j=0; j<=NV; j+=2) - xyz[i][j].pp[k3] = xyz[i][j].p[k3]; - } - for(i=1; i 1) - { - if(( (NH_remain-1) % 14) == 0) - NH_patch = 15; - else if(( (NH_remain-1) % 12) == 0) - NH_patch = 13; - else if(( (NH_remain-1) % 10) == 0) - NH_patch = 11; - else if(( (NH_remain-1) % 8) == 0) - NH_patch = 9; - else if(( (NH_remain-1) % 6) == 0) - NH_patch = 7; - else if(( (NH_remain-1) % 4) == 0) - NH_patch = 5; - else if(( (NH_remain-1) % 2) == 0) - NH_patch = 3; - else if(NH_remain > 16) - NH_patch = 7; - else if(NH_remain > 4) - NH_patch = 5; - else - NH_patch = 3; - while( NH_patch > 3 && (NH_patch-1)*dh > 512 ) - NH_patch -= 2; - NH_remain -= (NH_patch-1); - if(NH_remain < 0) - { - sprintf(szOops,"Oops... screwed up with NH=%d",NH); - g_FuncTable.m_pfnMessageBox(NULL,szOops,"Uh oh"); - } - NV_remain = NV+1; - j0 = 0; - while(NV_remain > 1) - { - if(( (NV_remain-1) % 14) == 0) - NV_patch = 15; - else if(( (NV_remain-1) % 12) == 0) - NV_patch = 13; - else if(( (NV_remain-1) % 10) == 0) - NV_patch = 11; - else if(( (NV_remain-1) % 8) == 0) - NV_patch = 9; - else if(( (NV_remain-1) % 6) == 0) - NV_patch = 7; - else if(( (NV_remain-1) % 4) == 0) - NV_patch = 5; - else if(( (NV_remain-1) % 2) == 0) - NV_patch = 3; - else if(NV_remain > 16) - NV_patch = 7; - else if(NV_remain > 4) - NV_patch = 5; - else - NV_patch = 3; - while( NV_patch > 3 && (NV_patch-1)*dh > 512 ) - NV_patch -= 2; - NV_remain -= (NV_patch-1); - if(NV_remain < 0) - { - sprintf(szOops,"Oops... screwed up with NV=%d",NV); - g_FuncTable.m_pfnMessageBox(NULL,szOops,"Uh oh"); - } - - scene::Node* patch = MakePatch(); +int MapPatches(){ + int NH_remain; + int NV_remain; + int NH_patch; + int NV_patch; + int BrushNum = 0; + int i, j, k1, k2, k3; + int i0, j0, ii; + char szOops[128]; + + dh = ( Hur - Hll ) / NH; + dv = ( Vur - Vll ) / NV; + + // Generate control points in pp array to give desired values currently + // in p array. + switch ( Plane ) + { + case PLANE_XY0: + case PLANE_XY1: + k1 = 0; + k2 = 1; + k3 = 2; + break; + case PLANE_XZ0: + case PLANE_XZ1: + k1 = 0; + k2 = 2; + k3 = 1; + break; + case PLANE_YZ0: + case PLANE_YZ1: + k1 = 1; + k2 = 2; + k3 = 0; + break; + } + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + xyz[i][j].pp[k1] = xyz[i][j].p[k1]; + xyz[i][j].pp[k2] = xyz[i][j].p[k2]; + } + } + for ( i = 0; i <= NH; i += 2 ) + { + for ( j = 0; j <= NV; j += 2 ) + xyz[i][j].pp[k3] = xyz[i][j].p[k3]; + } + for ( i = 1; i < NH; i += 2 ) + { + for ( j = 0; j <= NV; j += 2 ) + { + xyz[i][j].pp[k3] = ( 4 * xyz[i][j].p[k3] - xyz[i - 1][j].p[k3] - xyz[i + 1][j].p[k3] ) / 2; + } + } + for ( j = 1; j < NV; j += 2 ) + { + for ( i = 0; i <= NH; i += 2 ) + { + xyz[i][j].pp[k3] = ( 4 * xyz[i][j].p[k3] - xyz[i][j - 1].p[k3] - xyz[i][j + 1].p[k3] ) / 2; + } + } + for ( i = 1; i < NH; i += 2 ) + { + for ( j = 1; j < NV; j += 2 ) + { + xyz[i][j].pp[k3] = ( 16 * xyz[i][j].p[k3] - xyz[i - 1][j - 1].p[k3] - 2 * xyz[i][j - 1].p[k3] + - xyz[i + 1][j - 1].p[k3] - 2 * xyz[i - 1][j].p[k3] - 2 * xyz[i + 1][j].p[k3] + - xyz[i - 1][j + 1].p[k3] - 2 * xyz[i][j + 1].p[k3] - xyz[i + 1][j + 1].p[k3] ) / 4; + } + } + + NH_remain = NH + 1; + i0 = 0; + while ( NH_remain > 1 ) + { + if ( ( ( NH_remain - 1 ) % 14 ) == 0 ) { + NH_patch = 15; + } + else if ( ( ( NH_remain - 1 ) % 12 ) == 0 ) { + NH_patch = 13; + } + else if ( ( ( NH_remain - 1 ) % 10 ) == 0 ) { + NH_patch = 11; + } + else if ( ( ( NH_remain - 1 ) % 8 ) == 0 ) { + NH_patch = 9; + } + else if ( ( ( NH_remain - 1 ) % 6 ) == 0 ) { + NH_patch = 7; + } + else if ( ( ( NH_remain - 1 ) % 4 ) == 0 ) { + NH_patch = 5; + } + else if ( ( ( NH_remain - 1 ) % 2 ) == 0 ) { + NH_patch = 3; + } + else if ( NH_remain > 16 ) { + NH_patch = 7; + } + else if ( NH_remain > 4 ) { + NH_patch = 5; + } + else{ + NH_patch = 3; + } + while ( NH_patch > 3 && ( NH_patch - 1 ) * dh > 512 ) + NH_patch -= 2; + NH_remain -= ( NH_patch - 1 ); + if ( NH_remain < 0 ) { + sprintf( szOops,"Oops... screwed up with NH=%d",NH ); + g_FuncTable.m_pfnMessageBox( NULL,szOops,"Uh oh" ); + } + NV_remain = NV + 1; + j0 = 0; + while ( NV_remain > 1 ) + { + if ( ( ( NV_remain - 1 ) % 14 ) == 0 ) { + NV_patch = 15; + } + else if ( ( ( NV_remain - 1 ) % 12 ) == 0 ) { + NV_patch = 13; + } + else if ( ( ( NV_remain - 1 ) % 10 ) == 0 ) { + NV_patch = 11; + } + else if ( ( ( NV_remain - 1 ) % 8 ) == 0 ) { + NV_patch = 9; + } + else if ( ( ( NV_remain - 1 ) % 6 ) == 0 ) { + NV_patch = 7; + } + else if ( ( ( NV_remain - 1 ) % 4 ) == 0 ) { + NV_patch = 5; + } + else if ( ( ( NV_remain - 1 ) % 2 ) == 0 ) { + NV_patch = 3; + } + else if ( NV_remain > 16 ) { + NV_patch = 7; + } + else if ( NV_remain > 4 ) { + NV_patch = 5; + } + else{ + NV_patch = 3; + } + while ( NV_patch > 3 && ( NV_patch - 1 ) * dh > 512 ) + NV_patch -= 2; + NV_remain -= ( NV_patch - 1 ); + if ( NV_remain < 0 ) { + sprintf( szOops,"Oops... screwed up with NV=%d",NV ); + g_FuncTable.m_pfnMessageBox( NULL,szOops,"Uh oh" ); + } + + scene::Node* patch = MakePatch(); #if 0 - b->pPatch->setDims(NH_patch, NV_patch); - for(i=0; ipPatch->ctrlAt(COL,i,j)[0] = (float)xyz[ii][j0+j].pp[0]; - b->pPatch->ctrlAt(COL,i,j)[1] = (float)xyz[ii][j0+j].pp[1]; - b->pPatch->ctrlAt(COL,i,j)[2] = (float)xyz[ii][j0+j].pp[2]; - b->pPatch->ctrlAt(COL,i,j)[3] = (float)i; - b->pPatch->ctrlAt(COL,i,j)[4] = (float)j; - } - } - b->pPatch->UpdateCachedData(); + b->pPatch->setDims( NH_patch, NV_patch ); + for ( i = 0; i < NH_patch; i++ ) + { + switch ( Plane ) + { + case PLANE_XY1: + case PLANE_XZ0: + case PLANE_YZ1: + ii = i0 + NH_patch - 1 - i; + break; + default: + ii = i0 + i; + } + for ( j = 0; j < NV_patch; j++ ) + { + b->pPatch->ctrlAt( COL,i,j )[0] = (float)xyz[ii][j0 + j].pp[0]; + b->pPatch->ctrlAt( COL,i,j )[1] = (float)xyz[ii][j0 + j].pp[1]; + b->pPatch->ctrlAt( COL,i,j )[2] = (float)xyz[ii][j0 + j].pp[2]; + b->pPatch->ctrlAt( COL,i,j )[3] = (float)i; + b->pPatch->ctrlAt( COL,i,j )[4] = (float)j; + } + } + b->pPatch->UpdateCachedData(); #endif - BrushNum++; - j0 += NV_patch-1; - } - i0 += NH_patch-1; - } - return BrushNum; + BrushNum++; + j0 += NV_patch - 1; + } + i0 += NH_patch - 1; + } + return BrushNum; } //============================================================= -void MapBrushes() -{ - char hint[128]; - char skip[128]; - char sidetext[64]; - char surftext[64]; - char surftext2[64]; - char surft[64]; - float Steep; - vec3_t PlaneNormal,SurfNormal; - vec3_t t[2]; - int i, j, k; - int surf; - bool CheckAngle; - BRUSH brush; - XYZ v[8]; - - strcpy(surftext,Texture[Game][0]); - strcpy(sidetext,(strlen(Texture[Game][1]) ? Texture[Game][1] : Texture[Game][0])); - strcpy(surftext2,(strlen(Texture[Game][2]) ? Texture[Game][2] : Texture[Game][0])); - - // if surftext2 is identical to surftext, there's no need to - // check surface angle - if(!g_strcasecmp(surftext,surftext2)) - CheckAngle = FALSE; - else - { - CheckAngle = TRUE; - Steep = (float)cos((double)SlantAngle/57.2957795); - switch(Plane) - { - case PLANE_XY0: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_XY1: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]=-1.;break; - case PLANE_XZ0: PlaneNormal[0]= 0.;PlaneNormal[1]= 1.;PlaneNormal[2]= 1.;break; - case PLANE_XZ1: PlaneNormal[0]= 0.;PlaneNormal[1]=-1.;PlaneNormal[2]= 1.;break; - case PLANE_YZ0: PlaneNormal[0]= 1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_YZ1: PlaneNormal[0]=-1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - } - } - - OpenFuncGroup(); - - for(i=0; i 0 && (Game != QUAKE3 || UsePatches==0) ) - { - MapOut(gNumNodes,gNumTris,gNode,gTri); - /* - ghCursorCurrent = ghCursorDefault; - SetCursor(ghCursorCurrent); - */ - return; - } - - contents = 0; - // HL doesn't have detail property - if((Game != HALFLIFE) && UseDetail) contents += CONTENTS_DETAIL; - // HL and Q3 don't have ladder property - if((Game != HALFLIFE && Game != QUAKE3) && UseLadder) contents += CONTENTS_LADDER; - // Genesis requires solid property to be set explicitly - if(Game == GENESIS3D) contents |= CONTENTS_SOLID; - // Heretic 2 uses different sounds (in surface props) for different texture types - if(Game == HERETIC2) - { - surface[0] = GetDefSurfaceProps(Texture[Game][0]); - surface[1] = GetDefSurfaceProps(Texture[Game][1]); - surface[2] = GetDefSurfaceProps(Texture[Game][2]); - } - else - { - surface[0] = 0; - surface[1] = 0; - surface[2] = 0; - } - if(Game!=QUAKE3 || UsePatches == 0) - MapBrushes(); - - /* - ghCursorCurrent = ghCursorDefault; - SetCursor(ghCursorCurrent); - */ + GenerateXYZ(); + ntri = NH * NV * 2; + + if ( Game == QUAKE3 && UsePatches != 0 ) { + MapPatches(); + } + + if ( Decimate > 0 && ( Game != QUAKE3 || UsePatches == 0 ) ) { + MapOut( gNumNodes,gNumTris,gNode,gTri ); + /* + ghCursorCurrent = ghCursorDefault; + SetCursor(ghCursorCurrent); + */ + return; + } + + contents = 0; + // HL doesn't have detail property + if ( ( Game != HALFLIFE ) && UseDetail ) { + contents += CONTENTS_DETAIL; + } + // HL and Q3 don't have ladder property + if ( ( Game != HALFLIFE && Game != QUAKE3 ) && UseLadder ) { + contents += CONTENTS_LADDER; + } + // Genesis requires solid property to be set explicitly + if ( Game == GENESIS3D ) { + contents |= CONTENTS_SOLID; + } + // Heretic 2 uses different sounds (in surface props) for different texture types + if ( Game == HERETIC2 ) { + surface[0] = GetDefSurfaceProps( Texture[Game][0] ); + surface[1] = GetDefSurfaceProps( Texture[Game][1] ); + surface[2] = GetDefSurfaceProps( Texture[Game][2] ); + } + else + { + surface[0] = 0; + surface[1] = 0; + surface[2] = 0; + } + if ( Game != QUAKE3 || UsePatches == 0 ) { + MapBrushes(); + } + + /* + ghCursorCurrent = ghCursorDefault; + SetCursor(ghCursorCurrent); + */ } //============================================================= -void GenerateXYZ() -{ - extern void MakeDecimatedMap(int *, int *, NODE **, TRI **); - double zl, zu; - double wh, wv; - int NHalfcycles; - double a,v,h,ha,va; - double delta, dr, rate; - double range, maxrange; - double r; - int i, j, k, N; - int i0, i1, j0, j1; - int ii, jj; +void GenerateXYZ(){ + extern void MakeDecimatedMap( int *, int *, NODE * *, TRI * * ); + double zl, zu; + double wh, wv; + int NHalfcycles; + double a,v,h,ha,va; + double delta, dr, rate; + double range, maxrange; + double r; + int i, j, k, N; + int i0, i1, j0, j1; + int ii, jj; // FILE *f; // char CSV[64]; - if(!ValidSurface()) return; - - srand(1); - srand(RandomSeed); - - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - - // H & V - for(i=0; i<=NH; i++) - { - for(j=0;j<=NV;j++) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[0] = Hll + i*dh; - xyz[i][j].p[2] = Vll + j*dv; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[1] = Hll + i*dh; - xyz[i][j].p[2] = Vll + j*dv; - break; - default: - xyz[i][j].p[0] = Hll + i*dh; - xyz[i][j].p[1] = Vll + j*dv; - } - } - } - - if(WaveType == WAVE_BITMAP) - GenerateBitmapMapping(); - /* - else if(WaveType == WAVE_FORMULA) - DoFormula(); - */ - else - { - // Initialize Z values using bilinear interpolation - for(i=0; i<=NH; i++) - { - zl = Z00 + i*(Z10 - Z00)/NH; - zu = Z01 + i*(Z11 - Z01)/NH; - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(j=0; j<=NV; j++) - xyz[i][j].p[1] = zl + j*(zu-zl)/NV; - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(j=0; j<=NV; j++) - xyz[i][j].p[0] = zl + j*(zu-zl)/NV; - break; - default: - for(j=0; j<=NV; j++) - xyz[i][j].p[2] = zl + j*(zu-zl)/NV; - } - } - } - - switch(WaveType) - { - case WAVE_COS_SIN: - if(FixBorders) - { - NHalfcycles = (int)((Hur-Hll)/(WaveLength/2.)); - NHalfcycles = max(NHalfcycles,1); - wh = 2.*(Hur-Hll)/NHalfcycles; - NHalfcycles = (int)((Vur-Vll)/(WaveLength/2.)); - wv = 2.*(Vur-Vll)/NHalfcycles; - NHalfcycles = max(NHalfcycles,1); - i0 = 1; - i1 = NH-1; - j0 = 1; - j1 = NV-1; - } - else - { - wh = WaveLength; - wv = WaveLength; - i0 = 0; - i1 = NH; - j0 = 0; - j1 = NV; - } - - for(i=i0; i<=i1; i++) - { - h = Hll + i*dh; - ha = ((h-Hll)/wh)*2.*PI - PI/2.; - for(j=j0; j<=j1; j++) - { - v = Vll + j*dv; - va = ((v-Vll)/wv)*2.*PI; - a = Amplitude * cos( ha ) * sin( va ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_HCYLINDER: - for(i=0; i<=NH; i++) - { - h = Hll + i*dh; - ha = ((h-Hll)/WaveLength)*2.*PI - PI/2.; - for(j=0; j<=NV; j++) - { - a = Amplitude * cos( ha ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_VCYLINDER: - for(i=0; i<=NH; i++) - { - h = Hll + i*dh; - for(j=0; j<=NV; j++) - { - v = Vll + j*dv; - va = ((v-Vll)/WaveLength)*2.*PI; - a = Amplitude * sin( va ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_ROUGH_ONLY: - PlasmaCloud(); - break; - } - - if(WaveType != WAVE_ROUGH_ONLY) - { - // Fixed values - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] = xyz[i][j].fixed_value; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] = xyz[i][j].fixed_value; - break; - default: - xyz[i][j].p[2] = xyz[i][j].fixed_value; - } - - if(xyz[i][j].range > 0) - { - maxrange = pow(xyz[i][j].range,2); // so we don't have to do sqrt's - i0 = i - (int)( floor(xyz[i][j].range/dh - 0.5) + 1 ); - i1 = i + i - i0; - j0 = j - (int)( floor(xyz[i][j].range/dv - 0.5) + 1 ); - j1 = j + j - j0; - if(FixBorders) - { - i0 = max(i0,1); - i1 = min(i1,NH-1); - j0 = max(j0,1); - j1 = min(j1,NV-1); - } - else - { - i0 = max(i0,0); - i1 = min(i1,NH); - j0 = max(j0,0); - j1 = min(j1,NV); - } - for(ii=i0; ii<=i1; ii++) - { - for(jj=j0; jj<=j1; jj++) - { - if(ii==i && jj==j) continue; - range = pow( dh*(i-ii), 2) + pow( dv*(j-jj), 2); - if(range > maxrange) continue; - dr = sqrt(range/maxrange); - rate = max(-30.,min(xyz[i][j].rate,30.)); - if(rate < -1.) - { - delta = pow((1.-dr),-rate+1.); - } - else if(rate < 0.) - { - delta = (1+rate)*0.5*(cos(dr*PI)+1.0) - - rate*pow((1.-dr),2); - } - else if(rate == 0.) - { - delta = 0.5*(cos(dr*PI)+1.0); - } - else if(rate <= 1.) - { - delta = (1.-rate)*0.5*(cos(dr*PI)+1.0) + - rate*(1.-pow(dr,2)); - } - else - { - delta = 1.-pow(dr,rate+1); - } - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[ii][jj].p[1] += (xyz[i][j].p[1] - xyz[ii][jj].p[1])*delta; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[ii][jj].p[0] += (xyz[i][j].p[0] - xyz[ii][jj].p[0])*delta; - break; - default: - xyz[ii][jj].p[2] += (xyz[i][j].p[2] - xyz[ii][jj].p[2])*delta; - } - } - } - } - } - } - } - } - - if((Roughness > 0.) && (WaveType != WAVE_ROUGH_ONLY) ) - { - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(CanEdit(i,j) && !xyz[i][j].fixed) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - break; - default: - xyz[i][j].p[2] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - } - } - else - r = rand(); // We still get a random number, so that fixing points - // doesn't change the sequence. - - } - } - } - - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - for(k=0; k<3; k++) - { - xyz[i][j].p[k] = Nearest(xyz[i][j].p[k],2.0); - } - } - } - - // Find minima and maxima - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xmin = Hll; - xmax = Hur; - zmin = Vll; - zmax = Vur; - ymin = xyz[0][0].p[1]; - ymax = ymin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - ymin = min(ymin,xyz[i][j].p[1]); - ymax = max(ymax,xyz[i][j].p[1]); - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - ymin = Hll; - ymax = Hur; - zmin = Vll; - zmax = Vur; - xmin = xyz[0][0].p[0]; - xmax = ymin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xmin = min(xmin,xyz[i][j].p[0]); - xmax = max(xmax,xyz[i][j].p[0]); - } - } - break; - break; - default: - xmin = Hll; - xmax = Hur; - ymin = Vll; - ymax = Vur; - zmin = xyz[0][0].p[2]; - zmax = zmin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - zmin = min(zmin,xyz[i][j].p[2]); - zmax = max(zmax,xyz[i][j].p[2]); - } - } - } - - xmin = Nearest(xmin,2.); - xmax = Nearest(xmax,2.); - ymin = Nearest(ymin,2.); - ymax = Nearest(ymax,2.); - zmin = Nearest(zmin,2.); - zmax = Nearest(zmax,2.); - - switch(Plane) - { - case PLANE_XY1: - backface = AtLeast(zmax+32.,32.); - break; - case PLANE_XZ0: - backface = NoMoreThan(ymin-32.,32.); - break; - case PLANE_XZ1: - backface = AtLeast(ymax+32.,32.); - break; - case PLANE_YZ0: - backface = NoMoreThan(xmin-32.,32.); - break; - case PLANE_YZ1: - backface = AtLeast(xmax+32.,32.); - break; - default: - backface = NoMoreThan(zmin-32.,32.); - } - - if(gNode) - { - free(gNode); - free(gTri); - gNode = (NODE *)NULL; - gTri = (TRI *)NULL; - } - if(Decimate > 0 && (Game != QUAKE3 || UsePatches==0) ) - { - MakeDecimatedMap(&gNumNodes,&gNumTris,&gNode,&gTri); - } - else - { - gNumNodes = (NH+1)*(NV+1); - gNumTris = NH*NV*2; - gNode = (NODE *) malloc(gNumNodes * sizeof(NODE)); - gTri = (TRI *) malloc(gNumTris * sizeof(TRI)); - - for(i=0,N=0; i<=NH; i++) - { - for(j=0; j<=NV; j++, N++) - { - gNode[N].used = 1; - gNode[N].p[0] = (float)xyz[i][j].p[0]; - gNode[N].p[1] = (float)xyz[i][j].p[1]; - gNode[N].p[2] = (float)xyz[i][j].p[2]; - } - } - - for(i=0; i 0 ) { + maxrange = pow( xyz[i][j].range,2 ); // so we don't have to do sqrt's + i0 = i - (int)( floor( xyz[i][j].range / dh - 0.5 ) + 1 ); + i1 = i + i - i0; + j0 = j - (int)( floor( xyz[i][j].range / dv - 0.5 ) + 1 ); + j1 = j + j - j0; + if ( FixBorders ) { + i0 = max( i0,1 ); + i1 = min( i1,NH - 1 ); + j0 = max( j0,1 ); + j1 = min( j1,NV - 1 ); + } + else + { + i0 = max( i0,0 ); + i1 = min( i1,NH ); + j0 = max( j0,0 ); + j1 = min( j1,NV ); + } + for ( ii = i0; ii <= i1; ii++ ) + { + for ( jj = j0; jj <= j1; jj++ ) + { + if ( ii == i && jj == j ) { + continue; + } + range = pow( dh * ( i - ii ), 2 ) + pow( dv * ( j - jj ), 2 ); + if ( range > maxrange ) { + continue; + } + dr = sqrt( range / maxrange ); + rate = max( -30.,min( xyz[i][j].rate,30. ) ); + if ( rate < -1. ) { + delta = pow( ( 1. - dr ),-rate + 1. ); + } + else if ( rate < 0. ) { + delta = ( 1 + rate ) * 0.5 * ( cos( dr * PI ) + 1.0 ) - + rate*pow( ( 1. - dr ),2 ); + } + else if ( rate == 0. ) { + delta = 0.5 * ( cos( dr * PI ) + 1.0 ); + } + else if ( rate <= 1. ) { + delta = ( 1. - rate ) * 0.5 * ( cos( dr * PI ) + 1.0 ) + + rate * ( 1. - pow( dr,2 ) ); + } + else + { + delta = 1. - pow( dr,rate + 1 ); + } + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + xyz[ii][jj].p[1] += ( xyz[i][j].p[1] - xyz[ii][jj].p[1] ) * delta; + break; + case PLANE_YZ0: + case PLANE_YZ1: + xyz[ii][jj].p[0] += ( xyz[i][j].p[0] - xyz[ii][jj].p[0] ) * delta; + break; + default: + xyz[ii][jj].p[2] += ( xyz[i][j].p[2] - xyz[ii][jj].p[2] ) * delta; + } + } + } + } + } + } + } + } + + if ( ( Roughness > 0. ) && ( WaveType != WAVE_ROUGH_ONLY ) ) { + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + if ( CanEdit( i,j ) && !xyz[i][j].fixed ) { + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + xyz[i][j].p[1] += -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ); + break; + case PLANE_YZ0: + case PLANE_YZ1: + xyz[i][j].p[0] += -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ); + break; + default: + xyz[i][j].p[2] += -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ); + } + } + else{ + r = rand(); // We still get a random number, so that fixing points + } + // doesn't change the sequence. + + } + } + } + + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + for ( k = 0; k < 3; k++ ) + { + xyz[i][j].p[k] = Nearest( xyz[i][j].p[k],2.0 ); + } + } + } + + // Find minima and maxima + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + xmin = Hll; + xmax = Hur; + zmin = Vll; + zmax = Vur; + ymin = xyz[0][0].p[1]; + ymax = ymin; + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + ymin = min( ymin,xyz[i][j].p[1] ); + ymax = max( ymax,xyz[i][j].p[1] ); + } + } + break; + case PLANE_YZ0: + case PLANE_YZ1: + ymin = Hll; + ymax = Hur; + zmin = Vll; + zmax = Vur; + xmin = xyz[0][0].p[0]; + xmax = ymin; + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + xmin = min( xmin,xyz[i][j].p[0] ); + xmax = max( xmax,xyz[i][j].p[0] ); + } + } + break; + break; + default: + xmin = Hll; + xmax = Hur; + ymin = Vll; + ymax = Vur; + zmin = xyz[0][0].p[2]; + zmax = zmin; + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + zmin = min( zmin,xyz[i][j].p[2] ); + zmax = max( zmax,xyz[i][j].p[2] ); + } + } + } + + xmin = Nearest( xmin,2. ); + xmax = Nearest( xmax,2. ); + ymin = Nearest( ymin,2. ); + ymax = Nearest( ymax,2. ); + zmin = Nearest( zmin,2. ); + zmax = Nearest( zmax,2. ); + + switch ( Plane ) + { + case PLANE_XY1: + backface = AtLeast( zmax + 32.,32. ); + break; + case PLANE_XZ0: + backface = NoMoreThan( ymin - 32.,32. ); + break; + case PLANE_XZ1: + backface = AtLeast( ymax + 32.,32. ); + break; + case PLANE_YZ0: + backface = NoMoreThan( xmin - 32.,32. ); + break; + case PLANE_YZ1: + backface = AtLeast( xmax + 32.,32. ); + break; + default: + backface = NoMoreThan( zmin - 32.,32. ); + } + + if ( gNode ) { + free( gNode ); + free( gTri ); + gNode = (NODE *)NULL; + gTri = (TRI *)NULL; + } + if ( Decimate > 0 && ( Game != QUAKE3 || UsePatches == 0 ) ) { + MakeDecimatedMap( &gNumNodes,&gNumTris,&gNode,&gTri ); + } + else + { + gNumNodes = ( NH + 1 ) * ( NV + 1 ); + gNumTris = NH * NV * 2; + gNode = (NODE *) malloc( gNumNodes * sizeof( NODE ) ); + gTri = (TRI *) malloc( gNumTris * sizeof( TRI ) ); + + for ( i = 0,N = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++, N++ ) + { + gNode[N].used = 1; + gNode[N].p[0] = (float)xyz[i][j].p[0]; + gNode[N].p[1] = (float)xyz[i][j].p[1]; + gNode[N].p[2] = (float)xyz[i][j].p[2]; + } + } + + for ( i = 0; i < NH; i++ ) + { + for ( j = 0; j < NV; j++ ) + { + k = i * NV * 2 + j * 2; + if ( ( i + j ) % 2 ) { + switch ( Plane ) + { + case PLANE_XY1: + case PLANE_XZ1: + case PLANE_YZ1: + gTri[k ].v[0] = i * ( NV + 1 ) + j; + gTri[k ].v[1] = ( i + 1 ) * ( NV + 1 ) + j + 1; + gTri[k ].v[2] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k + 1].v[0] = i * ( NV + 1 ) + j; + gTri[k + 1].v[1] = i * ( NV + 1 ) + j + 1; + gTri[k + 1].v[2] = ( i + 1 ) * ( NV + 1 ) + j + 1; + break; + default: + gTri[k ].v[0] = i * ( NV + 1 ) + j; + gTri[k ].v[1] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k ].v[2] = ( i + 1 ) * ( NV + 1 ) + j + 1; + gTri[k + 1].v[0] = i * ( NV + 1 ) + j; + gTri[k + 1].v[1] = ( i + 1 ) * ( NV + 1 ) + j + 1; + gTri[k + 1].v[2] = i * ( NV + 1 ) + j + 1; + } + } + else + { + switch ( Plane ) + { + case PLANE_XY1: + case PLANE_XZ1: + case PLANE_YZ1: + gTri[k ].v[0] = i * ( NV + 1 ) + j; + gTri[k ].v[1] = i * ( NV + 1 ) + j + 1; + gTri[k ].v[2] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k + 1].v[0] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k + 1].v[1] = i * ( NV + 1 ) + j + 1; + gTri[k + 1].v[2] = ( i + 1 ) * ( NV + 1 ) + j + 1; + break; + default: + gTri[k ].v[0] = i * ( NV + 1 ) + j; + gTri[k ].v[1] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k ].v[2] = i * ( NV + 1 ) + j + 1; + gTri[k + 1].v[0] = ( i + 1 ) * ( NV + 1 ) + j; + gTri[k + 1].v[1] = ( i + 1 ) * ( NV + 1 ) + j + 1; + gTri[k + 1].v[2] = i * ( NV + 1 ) + j + 1; + } + } + } + } + } /* - sprintf(CSV,"csv%03d.csv",Decimate); - f = fopen(CSV,"w"); - for(i=0; i 0) - { - for(i=0; i 0 ) { + for ( i = 0; i < NH; i++ ) + { + for ( j = 0; j < NV; j++ ) + { + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + xyz[i][j].p[1] = CalculateSnapValue( xyz[i][j].p[1] ); + break; + case PLANE_YZ0: + case PLANE_YZ1: + xyz[i][j].p[0] = CalculateSnapValue( xyz[i][j].p[0] ); + break; + default: + xyz[i][j].p[2] = CalculateSnapValue( xyz[i][j].p[2] ); + } + } + } + } + // Hydra: snap-to-grid end } //============================================================= -double Nearest(double x, double dx) -{ - double xx; +double Nearest( double x, double dx ){ + double xx; - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(fabs(xx) < dx/2) xx = 0.; - return xx; + xx = (double)( floor( x / dx - 0.5 ) + 1. ) * dx; + if ( fabs( xx ) < dx / 2 ) { + xx = 0.; + } + return xx; } //============================================================= -double NoMoreThan(double x, double dx) -{ - double xx; +double NoMoreThan( double x, double dx ){ + double xx; - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(xx > x) xx -= dx; - return xx; + xx = (double)( floor( x / dx - 0.5 ) + 1. ) * dx; + if ( xx > x ) { + xx -= dx; + } + return xx; } //============================================================= -double AtLeast(double x, double dx) -{ - double xx; +double AtLeast( double x, double dx ){ + double xx; - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(xx < x) xx += dx; - return xx; + xx = (double)( floor( x / dx - 0.5 ) + 1. ) * dx; + if ( xx < x ) { + xx += dx; + } + return xx; } //============================================================= -double LessThan(double x,double dx) -{ - double xx; +double LessThan( double x,double dx ){ + double xx; - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(xx >= x) xx -= dx; - return xx; + xx = (double)( floor( x / dx - 0.5 ) + 1. ) * dx; + if ( xx >= x ) { + xx -= dx; + } + return xx; } //============================================================= -double MoreThan(double x,double dx) -{ - double xx; - - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - while(xx <= x) - xx += dx; - return xx; +double MoreThan( double x,double dx ){ + double xx; + + xx = (double)( floor( x / dx - 0.5 ) + 1. ) * dx; + while ( xx <= x ) + xx += dx; + return xx; } //============================================================= -void SubdividePlasma(int i0,int j0,int i1,int j1) -{ - int i, j; - double z1, z2; - double r; // NOTE: This is used to keep the random number sequence the same - // when we fix a point. If we did NOT do this, then simply - // fixing a point at its current value would change the entire - // surface. - - i = (i0+i1)/2; - j = (j0+j1)/2; - if(i1 > i0+1) - { - if(!xyz[i][j0].done) - { - xyz[i][j0].pp[2] = xyz[i0][j0].pp[2] + - (xyz[i1][j0].pp[2] - xyz[i0][j0].pp[2])*(double)(i-i0)/(double)(i1-i0) + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j0].done = 1; - } - else - r = rand(); - if((j1 > j0) && (!xyz[i][j1].done) ) - { - xyz[i][j1].pp[2] = xyz[i0][j1].pp[2] + - (xyz[i1][j1].pp[2] - xyz[i0][j1].pp[2])*(double)(i-i0)/(double)(i1-i0) + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j1].done = 1; - } - else - r = rand(); - } - if(j1 > j0 + 1) - { - if(!xyz[i0][j].done) - { - xyz[i0][j].pp[2] = xyz[i0][j0].pp[2] + - (xyz[i0][j1].pp[2] - xyz[i0][j0].pp[2])*(double)(j-j0)/(double)(j1-j0) + - ((double)(j-j0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i0][j].done = 1; - } - else - r = rand(); - if((i1 > i0) && (!xyz[i1][j].done)) - { - xyz[i1][j].pp[2] = xyz[i1][j0].pp[2] + - (xyz[i1][j1].pp[2] - xyz[i1][j0].pp[2])*(double)(j-j0)/(double)(j1-j0) + - ((double)(j-j0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i1][j].done = 1; - } - else - r = rand(); - } - if((i1 > i0+1) && (j1 > j0+1)) - { - if(!xyz[i][j].done) - { - z1 = xyz[i0][j].pp[2] + - (xyz[i1][j].pp[2] - xyz[i0][j].pp[2])*(double)(i-i0)/(double)(i1-i0); - z2 = xyz[i][j0].pp[2] + - (xyz[i][j1].pp[2] - xyz[i][j0].pp[2])*(double)(j-j0)/(double)(j1-j0); - xyz[i][j].pp[2] = (z1+z2)/2. + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j].done = 1; - } - else - r = rand(); - } - if(i > i0+1 || j > j0+1) - SubdividePlasma(i0,j0,i,j); - if(i1 > i+1 || j > j0+1) - SubdividePlasma(i,j0,i1,j); - if(i > i0+1 || j1 > j0+1) - SubdividePlasma(i0,j,i,j1); - if(i1 > i+1 || j1 > j0+1) - SubdividePlasma(i,j,i1,j1); +void SubdividePlasma( int i0,int j0,int i1,int j1 ){ + int i, j; + double z1, z2; + double r; // NOTE: This is used to keep the random number sequence the same + // when we fix a point. If we did NOT do this, then simply + // fixing a point at its current value would change the entire + // surface. + + i = ( i0 + i1 ) / 2; + j = ( j0 + j1 ) / 2; + if ( i1 > i0 + 1 ) { + if ( !xyz[i][j0].done ) { + xyz[i][j0].pp[2] = xyz[i0][j0].pp[2] + + ( xyz[i1][j0].pp[2] - xyz[i0][j0].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + xyz[i][j0].done = 1; + } + else{ + r = rand(); + } + if ( ( j1 > j0 ) && ( !xyz[i][j1].done ) ) { + xyz[i][j1].pp[2] = xyz[i0][j1].pp[2] + + ( xyz[i1][j1].pp[2] - xyz[i0][j1].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ) + + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + xyz[i][j1].done = 1; + } + else{ + r = rand(); + } + } + if ( j1 > j0 + 1 ) { + if ( !xyz[i0][j].done ) { + xyz[i0][j].pp[2] = xyz[i0][j0].pp[2] + + ( xyz[i0][j1].pp[2] - xyz[i0][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + + ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + xyz[i0][j].done = 1; + } + else{ + r = rand(); + } + if ( ( i1 > i0 ) && ( !xyz[i1][j].done ) ) { + xyz[i1][j].pp[2] = xyz[i1][j0].pp[2] + + ( xyz[i1][j1].pp[2] - xyz[i1][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ) + + ( (double)( j - j0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + xyz[i1][j].done = 1; + } + else{ + r = rand(); + } + } + if ( ( i1 > i0 + 1 ) && ( j1 > j0 + 1 ) ) { + if ( !xyz[i][j].done ) { + z1 = xyz[i0][j].pp[2] + + ( xyz[i1][j].pp[2] - xyz[i0][j].pp[2] ) * (double)( i - i0 ) / (double)( i1 - i0 ); + z2 = xyz[i][j0].pp[2] + + ( xyz[i][j1].pp[2] - xyz[i][j0].pp[2] ) * (double)( j - j0 ) / (double)( j1 - j0 ); + xyz[i][j].pp[2] = ( z1 + z2 ) / 2. + + ( (double)( i - i0 ) ) * ( -Roughness / 2. + Roughness * ( (double)rand() / (double)RAND_MAX ) ); + xyz[i][j].done = 1; + } + else{ + r = rand(); + } + } + if ( i > i0 + 1 || j > j0 + 1 ) { + SubdividePlasma( i0,j0,i,j ); + } + if ( i1 > i + 1 || j > j0 + 1 ) { + SubdividePlasma( i,j0,i1,j ); + } + if ( i > i0 + 1 || j1 > j0 + 1 ) { + SubdividePlasma( i0,j,i,j1 ); + } + if ( i1 > i + 1 || j1 > j0 + 1 ) { + SubdividePlasma( i,j,i1,j1 ); + } } //================================================================================== -void PlasmaCloud() -{ - int i, j; - /* use pp[2] values until done to avoid messing with a bunch of - switch statements */ - - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(FixedPoint(i,j)) - xyz[i][j].done = 1; - else - xyz[i][j].done = 0; - } - } - - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[1]; - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[0]; - } - } - break; - default: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[2]; - } - } - break; - } - SubdividePlasma(0,0,NH,NV); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[1] = xyz[i][j].pp[2]; - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[0] = xyz[i][j].pp[2]; - } - } - break; - default: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[2] = xyz[i][j].pp[2]; - } - } - break; - } +void PlasmaCloud(){ + int i, j; + /* use pp[2] values until done to avoid messing with a bunch of + switch statements */ + + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + if ( FixedPoint( i,j ) ) { + xyz[i][j].done = 1; + } + else{ + xyz[i][j].done = 0; + } + } + } + + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + if ( xyz[i][j].fixed ) { + xyz[i][j].pp[2] = xyz[i][j].fixed_value; + } + else{ + xyz[i][j].pp[2] = xyz[i][j].p[1]; + } + } + } + break; + case PLANE_YZ0: + case PLANE_YZ1: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + if ( xyz[i][j].fixed ) { + xyz[i][j].pp[2] = xyz[i][j].fixed_value; + } + else{ + xyz[i][j].pp[2] = xyz[i][j].p[0]; + } + } + } + break; + default: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + if ( xyz[i][j].fixed ) { + xyz[i][j].pp[2] = xyz[i][j].fixed_value; + } + else{ + xyz[i][j].pp[2] = xyz[i][j].p[2]; + } + } + } + break; + } + SubdividePlasma( 0,0,NH,NV ); + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + xyz[i][j].p[1] = xyz[i][j].pp[2]; + } + } + break; + case PLANE_YZ0: + case PLANE_YZ1: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + xyz[i][j].p[0] = xyz[i][j].pp[2]; + } + } + break; + default: + for ( i = 0; i <= NH; i++ ) + { + for ( j = 0; j <= NV; j++ ) + { + xyz[i][j].p[2] = xyz[i][j].pp[2]; + } + } + break; + } } //=========================================================================== -bool FixedPoint(int i, int j) -{ - if(xyz[i][j].fixed) return TRUE; - return !CanEdit(i,j); +bool FixedPoint( int i, int j ){ + if ( xyz[i][j].fixed ) { + return TRUE; + } + return !CanEdit( i,j ); } //=========================================================================== -bool CanEdit(int i, int j) -{ - if(FixBorders && ( (WaveType==WAVE_COS_SIN) || (WaveType==WAVE_ROUGH_ONLY) ) ) - { - if(i== 0) return FALSE; - if(i==NH) return FALSE; - if(j== 0) return FALSE; - if(j==NV) return FALSE; - } - if(i== 0 && j== 0) return FALSE; - if(i==NH && j== 0) return FALSE; - if(i== 0 && j==NV) return FALSE; - if(i==NH && j==NV) return FALSE; - return TRUE; +bool CanEdit( int i, int j ){ + if ( FixBorders && ( ( WaveType == WAVE_COS_SIN ) || ( WaveType == WAVE_ROUGH_ONLY ) ) ) { + if ( i == 0 ) { + return FALSE; + } + if ( i == NH ) { + return FALSE; + } + if ( j == 0 ) { + return FALSE; + } + if ( j == NV ) { + return FALSE; + } + } + if ( i == 0 && j == 0 ) { + return FALSE; + } + if ( i == NH && j == 0 ) { + return FALSE; + } + if ( i == 0 && j == NV ) { + return FALSE; + } + if ( i == NH && j == NV ) { + return FALSE; + } + return TRUE; } /*============================================================================ - TriangleFromPoint - Determines which triangle in the gTri array bounds the input point. Doesn't - do anything special with border points. -*/ -int TriangleFromPoint(double x, double y) -{ - int j, tri; - - if(!gTri) return -1; - - for(j=0, tri=-1; jp[0],2.); - v[0][1] = (vec)Nearest(xyz->p[1],2.); - v[0][2] = (vec)Nearest(xyz->p[2],2.); +void XYZtoV( XYZ *xyz, vec3 *v ){ + v[0][0] = (vec)Nearest( xyz->p[0],2. ); + v[0][1] = (vec)Nearest( xyz->p[1],2. ); + v[0][2] = (vec)Nearest( xyz->p[2],2. ); } //============================================================= -scene::Node* MakePatch(void) -{ - scene::Node* patch = Patch_AllocNode(); +scene::Node* MakePatch( void ){ + scene::Node* patch = Patch_AllocNode(); #if 0 - patch->m_patch->SetShader(Texture[Game][0]); + patch->m_patch->SetShader( Texture[Game][0] ); #endif - Node_getTraversable(h_worldspawn)->insert(patch); - return patch; + Node_getTraversable( h_worldspawn )->insert( patch ); + return patch; } //============================================================= -void MakeBrush(BRUSH *brush) -{ - NodePtr node(Brush_AllocNode()); +void MakeBrush( BRUSH *brush ){ + NodePtr node( Brush_AllocNode() ); #if 0 - for(int i=0; iNumFaces; i++) - { - _QERFaceData QERFaceData; - if(!strncmp(brush->face[i].texture, "textures/", 9)) - strcpy(QERFaceData.m_TextureName,brush->face[i].texture); - else - { - strcpy(QERFaceData.m_TextureName,"textures/"); - strcpy(QERFaceData.m_TextureName+9,brush->face[i].texture); - } - QERFaceData.m_nContents = brush->face[i].Contents; - QERFaceData.m_nFlags = brush->face[i].Surface; - QERFaceData.m_nValue = brush->face[i].Value; - QERFaceData.m_fShift[0] = brush->face[i].Shift[0]; - QERFaceData.m_fShift[1] = brush->face[i].Shift[1]; - QERFaceData.m_fRotate = brush->face[i].Rotate; - QERFaceData.m_fScale[0] = brush->face[i].Scale[0]; - QERFaceData.m_fScale[1] = brush->face[i].Scale[1]; - QERFaceData.m_v1[0] = brush->face[i].v[0][0]; - QERFaceData.m_v1[1] = brush->face[i].v[0][1]; - QERFaceData.m_v1[2] = brush->face[i].v[0][2]; - QERFaceData.m_v2[0] = brush->face[i].v[1][0]; - QERFaceData.m_v2[1] = brush->face[i].v[1][1]; - QERFaceData.m_v2[2] = brush->face[i].v[1][2]; - QERFaceData.m_v3[0] = brush->face[i].v[2][0]; - QERFaceData.m_v3[1] = brush->face[i].v[2][1]; - QERFaceData.m_v3[2] = brush->face[i].v[2][2]; - QERFaceData.m_bBPrimit = false; - (g_FuncTable.m_pfnAddFaceData)(vp,&QERFaceData); - } + for ( int i = 0; i < brush->NumFaces; i++ ) + { + _QERFaceData QERFaceData; + if ( !strncmp( brush->face[i].texture, "textures/", 9 ) ) { + strcpy( QERFaceData.m_TextureName,brush->face[i].texture ); + } + else + { + strcpy( QERFaceData.m_TextureName,"textures/" ); + strcpy( QERFaceData.m_TextureName + 9,brush->face[i].texture ); + } + QERFaceData.m_nContents = brush->face[i].Contents; + QERFaceData.m_nFlags = brush->face[i].Surface; + QERFaceData.m_nValue = brush->face[i].Value; + QERFaceData.m_fShift[0] = brush->face[i].Shift[0]; + QERFaceData.m_fShift[1] = brush->face[i].Shift[1]; + QERFaceData.m_fRotate = brush->face[i].Rotate; + QERFaceData.m_fScale[0] = brush->face[i].Scale[0]; + QERFaceData.m_fScale[1] = brush->face[i].Scale[1]; + QERFaceData.m_v1[0] = brush->face[i].v[0][0]; + QERFaceData.m_v1[1] = brush->face[i].v[0][1]; + QERFaceData.m_v1[2] = brush->face[i].v[0][2]; + QERFaceData.m_v2[0] = brush->face[i].v[1][0]; + QERFaceData.m_v2[1] = brush->face[i].v[1][1]; + QERFaceData.m_v2[2] = brush->face[i].v[1][2]; + QERFaceData.m_v3[0] = brush->face[i].v[2][0]; + QERFaceData.m_v3[1] = brush->face[i].v[2][1]; + QERFaceData.m_v3[2] = brush->face[i].v[2][2]; + QERFaceData.m_bBPrimit = false; + ( g_FuncTable.m_pfnAddFaceData )( vp,&QERFaceData ); + } #endif - Node_getTraversable(h_func_group)->insert(node); + Node_getTraversable( h_func_group )->insert( node ); } //============================================================= -void OpenFuncGroup() -{ - h_func_group = GlobalEntityCreator().createEntity("func_group"); - h_func_group->IncRef(); - if(AddTerrainKey) - h_func_group->m_entity->setkeyvalue("terrain", "1"); +void OpenFuncGroup(){ + h_func_group = GlobalEntityCreator().createEntity( "func_group" ); + h_func_group->IncRef(); + if ( AddTerrainKey ) { + h_func_group->m_entity->setkeyvalue( "terrain", "1" ); + } } //============================================================= -void CloseFuncGroup() -{ - h_func_group->DecRef(); - if (g_FuncTable.m_pfnSysUpdateWindows != NULL) - g_FuncTable.m_pfnSysUpdateWindows (W_ALL); +void CloseFuncGroup(){ + h_func_group->DecRef(); + if ( g_FuncTable.m_pfnSysUpdateWindows != NULL ) { + g_FuncTable.m_pfnSysUpdateWindows( W_ALL ); + } } diff --git a/contrib/gtkgensurf/gensurf.cpp b/contrib/gtkgensurf/gensurf.cpp index 3c3107aa..b28416e2 100644 --- a/contrib/gtkgensurf/gensurf.cpp +++ b/contrib/gtkgensurf/gensurf.cpp @@ -1,96 +1,96 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include #include /* -#include -#include -#include -*/ + #include + #include + #include + */ #include "gensurf.h" -char gszAppDir[NAME_MAX]; -char gszCaption[64]; -char gszIni[NAME_MAX]; -char gszHelpFile[NAME_MAX]; -char gszMapFile[NAME_MAX]; -char gszVersion[64]; -double Amplitude; -double Roughness; -double TexOffset[2]; -double TexScale[2]; -double WaveLength; -double Hll, Hur, Vll, Vur; -double Z00, Z01, Z10, Z11; -ELEMENT Vertex[(MAX_ROWS+1)*(MAX_ROWS+1)]; -int AddHints; -int ArghRad2; -int AutoOverwrite; -int Decimate=0; -int SnapToGrid=0; // 0, or the grid size to snap to. // Hydra : snap to grid -int FileAppend=0; -int FixBorders; -int HideBackFaces=0; -int NH, NV; -int NumVerticesSelected; -int Plane; -int Preview; -int RandomSeed=1; -int Skybox; -int UseDetail; -int UseLadder; -int VertexMode=0; -int WaveType; -int gNumNodes=0; -int gNumTris=0; -int vid_x, vid_y; -int view_x, view_y; -int view_cx, view_cy; -int UsePatches; -int SlantAngle; -int GimpHints; -int Antialiasing; // ^Fishman - Antializing for the preview window. -int AddTerrainKey; // ^Fishman - Add terrain key to func_group. -int SP; // ^Fishman - Snap to grid. +char gszAppDir[NAME_MAX]; +char gszCaption[64]; +char gszIni[NAME_MAX]; +char gszHelpFile[NAME_MAX]; +char gszMapFile[NAME_MAX]; +char gszVersion[64]; +double Amplitude; +double Roughness; +double TexOffset[2]; +double TexScale[2]; +double WaveLength; +double Hll, Hur, Vll, Vur; +double Z00, Z01, Z10, Z11; +ELEMENT Vertex[( MAX_ROWS + 1 ) * ( MAX_ROWS + 1 )]; +int AddHints; +int ArghRad2; +int AutoOverwrite; +int Decimate = 0; +int SnapToGrid = 0; // 0, or the grid size to snap to. // Hydra : snap to grid +int FileAppend = 0; +int FixBorders; +int HideBackFaces = 0; +int NH, NV; +int NumVerticesSelected; +int Plane; +int Preview; +int RandomSeed = 1; +int Skybox; +int UseDetail; +int UseLadder; +int VertexMode = 0; +int WaveType; +int gNumNodes = 0; +int gNumTris = 0; +int vid_x, vid_y; +int view_x, view_y; +int view_cx, view_cy; +int UsePatches; +int SlantAngle; +int GimpHints; +int Antialiasing; // ^Fishman - Antializing for the preview window. +int AddTerrainKey; // ^Fishman - Add terrain key to func_group. +int SP; // ^Fishman - Snap to grid. GtkWidget *g_pWnd; // ghwnd; GtkWidget *g_pRadiantWnd; // ghwnd_main; /*HWND ghwndAngles; -*/GtkWidget *g_pWndPreview; + */GtkWidget *g_pWndPreview; GtkWidget *g_pPreviewWidget; -MYBITMAP gbmp; -NODE *gNode=(NODE *)NULL; -TRI *gTri=(TRI *)NULL; +MYBITMAP gbmp; +NODE *gNode = (NODE *)NULL; +TRI *gTri = (TRI *)NULL; -int Game; +int Game; bounding_box PlayerBox[NUMGAMES] = { {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Quake2 - {{-16., 16.}, {-16., 16.}, {-36., 36.}}, // Half-Life - {{-16., 16.}, {-16., 16.}, {-32., 32.}}, // SiN - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Heretic2 (guess) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // KingPin (guess) - {{-30., 30.}, {-30., 30.}, {-10.,160.}}, // Genesis3D (no idea) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}}; // Quake3 (not sure) + {{-16., 16.}, {-16., 16.}, {-36., 36.}}, // Half-Life + {{-16., 16.}, {-16., 16.}, {-32., 32.}}, // SiN + {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Heretic2 (guess) + {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // KingPin (guess) + {{-30., 30.}, {-30., 30.}, {-10.,160.}}, // Genesis3D (no idea) + {{-16., 16.}, {-16., 16.}, {-24., 32.}}}; // Quake3 (not sure) //char gszOutputDir[NUMGAMES][NAME_MAX]; //char gszTextureDir[NUMGAMES][NAME_MAX]; -char Texture[NUMGAMES][3][64]; +char Texture[NUMGAMES][3][64]; //char pakfile[NUMGAMES][NAME_MAX]; //char lastpakfile[NUMGAMES][NAME_MAX]; //int UsePak[NUMGAMES]; @@ -99,21 +99,19 @@ char Texture[NUMGAMES][3][64]; char GameName[NUMGAMES][16] = {"Quake2", "Half-Life", "SiN", "Heretic2", "Kingpin", "Genesis3D", "Quake3" }; -bool GenSurfInit () -{ - strcpy (gszVersion, "1.05"); - strcpy (gszCaption, "GtkGenSurf"); - if (strlen (gszVersion)) - { - strcat (gszCaption, " v"); - strcat (gszCaption, gszVersion); - } +bool GenSurfInit(){ + strcpy( gszVersion, "1.05" ); + strcpy( gszCaption, "GtkGenSurf" ); + if ( strlen( gszVersion ) ) { + strcat( gszCaption, " v" ); + strcat( gszCaption, gszVersion ); + } - strcpy (gszIni, g_FuncTable.m_pfnProfileGetDirectory ()); - strcat (gszIni, "gensurf.ini"); + strcpy( gszIni, g_FuncTable.m_pfnProfileGetDirectory() ); + strcat( gszIni, "gensurf.ini" ); /*if (g_FuncTable.m_pfnReadProjectKey != NULL) - { + { char *basepath; basepath = g_FuncTable.m_pfnReadProjectKey("basepath"); @@ -129,341 +127,362 @@ bool GenSurfInit () } else Game = QUAKE3; - } - else */ - Game = QUAKE3; + } + else */ + Game = QUAKE3; - if (g_pWnd == NULL) - g_pWnd = create_main_dialog (); + if ( g_pWnd == NULL ) { + g_pWnd = create_main_dialog(); + } - ReadIniFile (gszIni); + ReadIniFile( gszIni ); - return true; + return true; } // Reads default values #define OPTS_SECTION "Options" -void ReadIniFile (const char *file) -{ - char *Text; - float x1,x2,x3,x4; - int i; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Amplitude", ""); - if (strlen (Text)) - Amplitude = atof (Text); - else - Amplitude = 128; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Roughness", ""); - if (strlen (Text)) - Roughness = atof (Text); - else - Roughness = 16; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "WaveLength", ""); - if (strlen (Text)) - WaveLength = atof (Text); - else - WaveLength = 1024; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Extents", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4); - Hll = x1; - Vll = x2; - Hur = x3; - Vur = x4; - } - else - { - Hll = -512; - Vll = -512; - Hur = 512; - Vur = 512; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "CornerValues", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4); - Z00 = x1; - Z01 = x2; - Z10 = x3; - Z11 = x4; - } - else - { - Z00 = 0.; - Z01 = 0.; - Z10 = 0.; - Z11 = 0.; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "TextureOffset", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f",&x1,&x2); - TexOffset[0] = x1; - TexOffset[1] = x2; - } - else - { - TexOffset[0] = 0.; - TexOffset[1] = 0.; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION,"TextureScale",""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f",&x1,&x2); - TexScale[0] = x1; - TexScale[1] = x2; - if(TexScale[0] == 0.) TexScale[0] = 1.0; - if(TexScale[1] == 0.) TexScale[1] = 1.0; - } - else - { - TexScale[0] = 1.; - TexScale[1] = 1.; - } - - NH = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"NH",8); - NH = max(1,min(NH,MAX_ROWS)); - NV = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"NV",8); - NV = max(1,min(NV,MAX_ROWS)); +void ReadIniFile( const char *file ){ + char *Text; + float x1,x2,x3,x4; + int i; + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "Amplitude", "" ); + if ( strlen( Text ) ) { + Amplitude = atof( Text ); + } + else{ + Amplitude = 128; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "Roughness", "" ); + if ( strlen( Text ) ) { + Roughness = atof( Text ); + } + else{ + Roughness = 16; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "WaveLength", "" ); + if ( strlen( Text ) ) { + WaveLength = atof( Text ); + } + else{ + WaveLength = 1024; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "Extents", "" ); + if ( strlen( Text ) ) { + sscanf( Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4 ); + Hll = x1; + Vll = x2; + Hur = x3; + Vur = x4; + } + else + { + Hll = -512; + Vll = -512; + Hur = 512; + Vur = 512; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "CornerValues", "" ); + if ( strlen( Text ) ) { + sscanf( Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4 ); + Z00 = x1; + Z01 = x2; + Z10 = x3; + Z11 = x4; + } + else + { + Z00 = 0.; + Z01 = 0.; + Z10 = 0.; + Z11 = 0.; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION, "TextureOffset", "" ); + if ( strlen( Text ) ) { + sscanf( Text,"%f,%f",&x1,&x2 ); + TexOffset[0] = x1; + TexOffset[1] = x2; + } + else + { + TexOffset[0] = 0.; + TexOffset[1] = 0.; + } + + Text = g_FuncTable.m_pfnProfileLoadString( file, OPTS_SECTION,"TextureScale","" ); + if ( strlen( Text ) ) { + sscanf( Text,"%f,%f",&x1,&x2 ); + TexScale[0] = x1; + TexScale[1] = x2; + if ( TexScale[0] == 0. ) { + TexScale[0] = 1.0; + } + if ( TexScale[1] == 0. ) { + TexScale[1] = 1.0; + } + } + else + { + TexScale[0] = 1.; + TexScale[1] = 1.; + } + + NH = g_FuncTable.m_pfnProfileLoadInt( file, OPTS_SECTION,"NH",8 ); + NH = max( 1,min( NH,MAX_ROWS ) ); + NV = g_FuncTable.m_pfnProfileLoadInt( file, OPTS_SECTION,"NV",8 ); + NV = max( 1,min( NV,MAX_ROWS ) ); // Decimate = GetPrivateProfileInt(OPTS_SECTION,"Decimate",0,file); // Decimate = max(0,min(Decimate,100)); - AddHints = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AddHints",0); - ArghRad2 = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"ArghRad2",0); - AutoOverwrite = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AutoOverwrite",0); - FixBorders = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"FixBorders",1); - HideBackFaces = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"HideBackFaces",0); - Plane = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Plane",0); - Preview = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Preview", 0); - Antialiasing = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Antialiasing",0); // ^Fishman - Antializing for the preview window. - RandomSeed = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"RandomSeed",1); - Skybox = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Skybox",0); - UseDetail = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UseDetail",0); - AddTerrainKey = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AddTerrainKey",0); // ^Fishman - Add terrain key to func_group. - UseLadder = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UseLadder",0); - WaveType = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"WaveType",0); - vid_x = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"vid_x", 0); - vid_y = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"vid_y", 0); - view_x = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_x",0); - view_y = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_y",0); - view_cx = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_cx",0); - view_cy = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_cy",0); - - UsePatches = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UsePatches",0); - - SlantAngle = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"SlantAngle",60); - GimpHints = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"GimpHints",0); - - for(i=0; i #else template -inline T min (T x, T y) { return (x < y) ? x : y; } +inline T min( T x, T y ) { return ( x < y ) ? x : y; } template -inline T max (T x, T y) { return (x > y) ? x : y; } +inline T max( T x, T y ) { return ( x > y ) ? x : y; } #endif typedef struct { long x, y; } Point; @@ -77,39 +77,46 @@ typedef void* LPVOID; typedef char* LPSTR; //#endif -inline bool PtInRect (Rect *rc, Point pt) -{ - if (pt.x < rc->left) return false; - if (pt.x > rc->right) return false; - if (pt.y < rc->bottom) return false; - if (pt.y > rc->top) return false; - return true; +inline bool PtInRect( Rect *rc, Point pt ){ + if ( pt.x < rc->left ) { + return false; + } + if ( pt.x > rc->right ) { + return false; + } + if ( pt.y < rc->bottom ) { + return false; + } + if ( pt.y > rc->top ) { + return false; + } + return true; } #define NUMGAMES 7 #define CONTENTS_SOLID 0x00000001 -#define CONTENTS_DETAIL 0x08000000 // brushes to be added after vis leafs -#define CONTENTS_LADDER 0x20000000 -#define SURF_HINT 0x100 // make a primary bsp splitter -#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes +#define CONTENTS_DETAIL 0x08000000 // brushes to be added after vis leafs +#define CONTENTS_LADDER 0x20000000 +#define SURF_HINT 0x100 // make a primary bsp splitter +#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes #define HINT_OFFSET 96 #define PI 3.14159265358979224 -#define RadiansToDegrees(a) (floor(a*57.2957795 - 0.5)+1.) -#define DegreesToRadians(a) (a/57.2957795) +#define RadiansToDegrees( a ) ( floor( a * 57.2957795 - 0.5 ) + 1. ) +#define DegreesToRadians( a ) ( a / 57.2957795 ) -#define BOGUS_RANGE 65536 +#define BOGUS_RANGE 65536 /* -#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2]) -#define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];} -#define VectorClear(x) {x[0] = x[1] = x[2] = 0;} -#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} -#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} -#define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];} -*/ -#define XYZVectorSubtract(a,b,c) {c[0]=(float)a[0]-(float)b[0];c[1]=(float)a[1]-(float)b[1];c[2]=(float)a[2]-(float)b[2];} -#define side(u1,v1,u2,v2,u3,v3) (v3-v1)*(u2-u1) - (u3-u1)*(v2-v1) + #define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[2]) + #define VectorAdd(a,b,c) {c[0]=a[0]+b[0];c[1]=a[1]+b[1];c[2]=a[2]+b[2];} + #define VectorClear(x) {x[0] = x[1] = x[2] = 0;} + #define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} + #define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} + #define VectorSubtract(a,b,c) {c[0]=a[0]-b[0];c[1]=a[1]-b[1];c[2]=a[2]-b[2];} + */ +#define XYZVectorSubtract( a,b,c ) {c[0] = (float)a[0] - (float)b[0]; c[1] = (float)a[1] - (float)b[1]; c[2] = (float)a[2] - (float)b[2]; } +#define side( u1,v1,u2,v2,u3,v3 ) ( v3 - v1 ) * ( u2 - u1 ) - ( u3 - u1 ) * ( v2 - v1 ) #define QUAKE2 0 #define HALFLIFE 1 @@ -120,9 +127,9 @@ inline bool PtInRect (Rect *rc, Point pt) #define QUAKE3 6 #define MAX_FACES_PER_BRUSH 6 -#define SLIVER_ANGLE DegreesToRadians(20) -#define MAX_NODES (MAX_ROWS+1)*(MAX_ROWS+1) -#define MAX_TRIS (MAX_ROWS)*(MAX_ROWS) +#define SLIVER_ANGLE DegreesToRadians( 20 ) +#define MAX_NODES ( MAX_ROWS + 1 ) * ( MAX_ROWS + 1 ) +#define MAX_TRIS (MAX_ROWS)*( MAX_ROWS ) typedef float vec; typedef vec vec3[3]; @@ -130,32 +137,32 @@ typedef vec vec2[2]; typedef struct { - vec3 v[3]; - char texture[64]; - float Shift[2]; - float Rotate; - float Scale[2]; - int Contents; - int Surface; - int Value; + vec3 v[3]; + char texture[64]; + float Shift[2]; + float Rotate; + float Scale[2]; + int Contents; + int Surface; + int Value; } FACE; typedef struct { vec3 normal; - vec dist; + vec dist; } PLANE; typedef struct { - int numpoints; - vec3 p[4]; // variable sized + int numpoints; + vec3 p[4]; // variable sized } MY_WINDING; typedef struct { - int Number; - int NumFaces; + int Number; + int NumFaces; FACE face[MAX_FACES_PER_BRUSH]; } BRUSH; @@ -186,131 +193,131 @@ typedef struct } pak_item_t; // SiN .SIN structures -#define SINPAKHEADER (('K'<<24)+('A'<<16)+('P'<<8)+'S') +#define SINPAKHEADER ( ( 'K' << 24 ) + ( 'A' << 16 ) + ( 'P' << 8 ) + 'S' ) #define MAX_PAK_FILENAME_LENGTH 120 typedef struct { - char name[MAX_PAK_FILENAME_LENGTH]; - int filepos, filelen; + char name[MAX_PAK_FILENAME_LENGTH]; + int filepos, filelen; } dpackfile_t; typedef struct { - int ident; // == IDPAKHEADER - int dirofs; - int dirlen; + int ident; // == IDPAKHEADER + int dirofs; + int dirlen; } dpackheader_t; // Half-Life WAD file structures typedef struct { - char identification[4]; // should be WAD2 or 2DAW - int numlumps; - int infotableofs; + char identification[4]; // should be WAD2 or 2DAW + int numlumps; + int infotableofs; } wadinfo_t; typedef struct { - int filepos; - int disksize; - int size; // uncompressed - char type; - char compression; - char pad1, pad2; - char name[16]; // must be null terminated + int filepos; + int disksize; + int size; // uncompressed + char type; + char compression; + char pad1, pad2; + char name[16]; // must be null terminated } lumpinfo_t; typedef struct { - int signature; - short version; - short bitflag; - short compression_method; - short modfiletime; - short modfiledate; - int crc; - int compressed_size; - int uncompressed_size; - short filename_size; - short extra_size; + int signature; + short version; + short bitflag; + short compression_method; + short modfiletime; + short modfiledate; + int crc; + int compressed_size; + int uncompressed_size; + short filename_size; + short extra_size; } zipheader_t; typedef struct { - double x[2]; - double y[2]; - double z[2]; + double x[2]; + double y[2]; + double z[2]; } bounding_box; typedef struct { float p[3]; - int used; - int tri; + int used; + int tri; float error; - int fixed; + int fixed; } NODE; typedef struct { - int v[3]; - int n[3]; // indices of neighboring triangles + int v[3]; + int n[3]; // indices of neighboring triangles PLANE plane; - int flag; + int flag; float min[3]; float max[3]; } TRI; //--------------- bitmap.c ----------------------------- -bool OpenBitmap (); -double CalculateSnapValue(double value); -void GenerateBitmapMapping (); +bool OpenBitmap(); +double CalculateSnapValue( double value ); +void GenerateBitmapMapping(); //--------------- face.c ------------------------------- -void PlaneFromPoints (float *, float *, float *, PLANE *); +void PlaneFromPoints( float *, float *, float *, PLANE * ); //void CrossProduct (vec3 v1, vec3 v2, vec3 cross); //vec VectorNormalize (vec3 in, vec3 out); //--------------- gendlg.c ----------------------------- -GtkWidget* create_main_dialog (); -void About (GtkWidget *parent); +GtkWidget* create_main_dialog(); +void About( GtkWidget *parent ); //--------------- genmap.c ----------------------------- -double AtLeast(double,double); -bool CanEdit(int, int); +double AtLeast( double,double ); +bool CanEdit( int, int ); void CloseFuncGroup(); -bool FixedPoint(int,int); +bool FixedPoint( int,int ); void GenerateMap(); void GenerateXYZ(); -double LessThan(double,double); -void MakeBrush(BRUSH *); -double MoreThan(double,double); -double Nearest(double,double); -double NoMoreThan(double,double); +double LessThan( double,double ); +void MakeBrush( BRUSH * ); +double MoreThan( double,double ); +double Nearest( double,double ); +double NoMoreThan( double,double ); void OpenFuncGroup(); void PlasmaCloud(); -int PlayerStartZ(double,double); -void SubdividePlasma(int,int,int,int); +int PlayerStartZ( double,double ); +void SubdividePlasma( int,int,int,int ); bool ValidSurface(); -void XYZtoV(XYZ *, vec3 *); -scene::Node* MakePatch(void); +void XYZtoV( XYZ *, vec3 * ); +scene::Node* MakePatch( void ); //---------------- gensurf.c --------------------------- -bool GenSurfInit (); -void ReadIniFile (const char *); -void WriteIniFile (const char *); -void OpenSetup (GtkWidget*,int); -void SaveSetup (GtkWidget*); +bool GenSurfInit(); +void ReadIniFile( const char * ); +void WriteIniFile( const char * ); +void OpenSetup( GtkWidget*,int ); +void SaveSetup( GtkWidget* ); //---------------- heretic.c --------------------------- -int GetDefSurfaceProps(char *); +int GetDefSurfaceProps( char * ); //---------------- view.c ------------------------------ -void CreateViewWindow (); -void DrawGrid(Rect); -void DrawPreview(Rect); +void CreateViewWindow(); +void DrawGrid( Rect ); +void DrawPreview( Rect ); void evaluate(); -void GetScaleFactor(Rect); -void project(XYZ *); -void Scale(Rect,XYZ,Point *); -void ShowPreview (); -void UpdatePreview (bool); +void GetScaleFactor( Rect ); +void project( XYZ * ); +void Scale( Rect,XYZ,Point * ); +void ShowPreview(); +void UpdatePreview( bool ); //---------------- plugin.c ----------------------------- void UseFaceBounds(); @@ -337,18 +344,18 @@ extern _QEREntityTable g_EntityTable; #define WAVE_FORMULA 5 #define WAVE_FIRST WAVE_COS_SIN #define WAVE_LAST WAVE_FORMULA -#define DLG_WAVE_LAST DLG_WAVE_01+WAVE_LAST-WAVE_FIRST +#define DLG_WAVE_LAST DLG_WAVE_01 + WAVE_LAST - WAVE_FIRST -#define MSG_VERTEX_SELECTED WM_USER+1 +#define MSG_VERTEX_SELECTED WM_USER + 1 typedef struct tagMYBITMAP { - char name[NAME_MAX]; - char defpath[NAME_MAX]; - double black_value; - double white_value; - int width, height; - unsigned char* colors; + char name[NAME_MAX]; + char defpath[NAME_MAX]; + double black_value; + double white_value; + int width, height; + unsigned char* colors; } MYBITMAP; typedef struct tagELEMENT { @@ -356,73 +363,73 @@ typedef struct tagELEMENT { int j; } ELEMENT; -extern char gszAppDir[NAME_MAX]; -extern char gszCaption[64]; -extern char gszHelpFile[NAME_MAX]; -extern char gszIni[NAME_MAX]; -extern char gszMapFile[NAME_MAX]; -extern char gszVersion[64]; -extern double Amplitude; -extern double Roughness; -extern double TexOffset[2]; -extern double TexScale[2]; -extern double WaveLength; -extern double Hll, Hur, Vll, Vur; -extern double Z00, Z01, Z10, Z11; -extern double yaw, pitch, roll; -extern ELEMENT Vertex[(MAX_ROWS+1)*(MAX_ROWS+1)]; -extern int AddHints; -extern int ArghRad2; -extern int AutoOverwrite; -extern int Decimate; -extern int FileAppend; -extern int FixBorders; -extern int HideBackFaces; -extern int NH, NV; -extern int NumVerticesSelected; -extern int Plane; -extern int Preview; -extern int RandomSeed; -extern int Skybox; -extern int UseDetail; -extern int UseLadder; -extern int VertexMode; -extern int vid_x, vid_y; -extern int WaveType; -extern int gNumNodes; -extern int gNumTris; -extern int view_x, view_y; -extern int view_cx, view_cy; -extern int UsePatches; -extern int SlantAngle; -extern int GimpHints; -extern int Antialiasing; // ^Fishman - Antializing for the preview window. -extern int AddTerrainKey; // ^Fishman - Add terrain key to func_group. -extern int SnapToGrid; // Hydra : snap to grid -extern int SP; // ^Fishman - Snap to grid. +extern char gszAppDir[NAME_MAX]; +extern char gszCaption[64]; +extern char gszHelpFile[NAME_MAX]; +extern char gszIni[NAME_MAX]; +extern char gszMapFile[NAME_MAX]; +extern char gszVersion[64]; +extern double Amplitude; +extern double Roughness; +extern double TexOffset[2]; +extern double TexScale[2]; +extern double WaveLength; +extern double Hll, Hur, Vll, Vur; +extern double Z00, Z01, Z10, Z11; +extern double yaw, pitch, roll; +extern ELEMENT Vertex[( MAX_ROWS + 1 ) * ( MAX_ROWS + 1 )]; +extern int AddHints; +extern int ArghRad2; +extern int AutoOverwrite; +extern int Decimate; +extern int FileAppend; +extern int FixBorders; +extern int HideBackFaces; +extern int NH, NV; +extern int NumVerticesSelected; +extern int Plane; +extern int Preview; +extern int RandomSeed; +extern int Skybox; +extern int UseDetail; +extern int UseLadder; +extern int VertexMode; +extern int vid_x, vid_y; +extern int WaveType; +extern int gNumNodes; +extern int gNumTris; +extern int view_x, view_y; +extern int view_cx, view_cy; +extern int UsePatches; +extern int SlantAngle; +extern int GimpHints; +extern int Antialiasing; // ^Fishman - Antializing for the preview window. +extern int AddTerrainKey; // ^Fishman - Add terrain key to func_group. +extern int SnapToGrid; // Hydra : snap to grid +extern int SP; // ^Fishman - Snap to grid. /*extern HCURSOR ghCursorCurrent; -extern HCURSOR ghCursorDefault; -extern HCURSOR ghCursorVertex; -extern HINSTANCE ghInst;*/ + extern HCURSOR ghCursorDefault; + extern HCURSOR ghCursorVertex; + extern HINSTANCE ghInst;*/ extern GtkWidget *g_pRadiantWnd; extern GtkWidget *g_pWnd; /*extern HWND ghwndAngles; -extern HWND ghwndFix; -*/extern GtkWidget *g_pWndPreview; + extern HWND ghwndFix; + */extern GtkWidget *g_pWndPreview; extern GtkWidget *g_pPreviewWidget; -extern MYBITMAP gbmp; +extern MYBITMAP gbmp; extern NODE *gNode; extern TRI *gTri; -extern XYZ xyz[MAX_ROWS+1][MAX_ROWS+1]; +extern XYZ xyz[MAX_ROWS + 1][MAX_ROWS + 1]; -extern int Game; +extern int Game; extern bounding_box PlayerBox[NUMGAMES]; //extern char gszOutputDir[NUMGAMES][NAME_MAX]; -extern char Texture[NUMGAMES][3][64]; +extern char Texture[NUMGAMES][3][64]; //extern char gszTextureDir[NUMGAMES][NAME_MAX]; -extern char GameName[NUMGAMES][16]; +extern char GameName[NUMGAMES][16]; //extern char pakfile[NUMGAMES][NAME_MAX]; //extern char lastpakfile[NUMGAMES][NAME_MAX]; //extern int UsePak[NUMGAMES]; diff --git a/contrib/gtkgensurf/heretic.cpp b/contrib/gtkgensurf/heretic.cpp index 4fb19a23..e07a378b 100644 --- a/contrib/gtkgensurf/heretic.cpp +++ b/contrib/gtkgensurf/heretic.cpp @@ -1,21 +1,21 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include @@ -26,125 +26,124 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA typedef struct palette_s { - guint8 r,g,b; + guint8 r,g,b; } palette_t; -#define MIP_VERSION 2 -#define PAL_SIZE 256 -#define MIPLEVELS 16 +#define MIP_VERSION 2 +#define PAL_SIZE 256 +#define MIPLEVELS 16 typedef struct miptex_s { - int version; - char name[32]; - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - palette_t palette[PAL_SIZE]; - int flags; - int contents; - int value; + int version; + char name[32]; + unsigned width[MIPLEVELS], height[MIPLEVELS]; + unsigned offsets[MIPLEVELS]; // four mip maps stored + char animname[32]; // next frame in animation chain + palette_t palette[PAL_SIZE]; + int flags; + int contents; + int value; } miptex_t; //============================================================= -int GetDefSurfaceProps(char *Tex) -{ - return 0; // leo: only used for Heretic 2, fix later - /* - char path[NAME_MAX]; - char *p; - int flags; - miptex_t *mt; - FILE *f; - int length; - int pos; +int GetDefSurfaceProps( char *Tex ){ + return 0; // leo: only used for Heretic 2, fix later + /* + char path[NAME_MAX]; + char *p; + int flags; + miptex_t *mt; + FILE *f; + int length; + int pos; - if(Game != HERETIC2) return 0; - if(!strlen(Tex)) return 0; + if(Game != HERETIC2) return 0; + if(!strlen(Tex)) return 0; - mt = NULL; - flags = 0; - if(UsePak[Game]) - { - FILE *fpak; - pak_header_t pakheader; - pak_item_t pakitem; - int i; - int num; - int numitems; + mt = NULL; + flags = 0; + if(UsePak[Game]) + { + FILE *fpak; + pak_header_t pakheader; + pak_item_t pakitem; + int i; + int num; + int numitems; - if (NULL != (fpak = fopen(pakfile[Game], "rb"))) - { - sprintf(path,"textures/%s.m8",Tex); - g_strdown(path); - num=fread(&pakheader,1,sizeof(pak_header_t),fpak); - if((size_t)num < sizeof(pak_header_t)) - { - fclose(fpak); - return 0; - } - if(strncmp(pakheader.id,"PACK",4)) - { - fclose(fpak); - return 0; - } - numitems = pakheader.dsize/sizeof(pak_item_t); - fseek(fpak,pakheader.dstart,SEEK_SET); - for(i=0; iflags; - free(mt); - } - } - } - fclose(fpak); - } - } - else - { - // Assume .map will be output to gamedir/maps, then back up - // to the gamedir and append /textures. Ugly but it should work - strcpy(path,gszMapFile); - g_strdown(path); - p = strstr(path,"maps"); - if(!p) return 0; - p[0] = '\0'; - strcat(path,"textures/"); - strcat(path,Tex); - strcat(path,".m8"); - f = fopen (path, "rb"); - if (!f) - flags = 0; - else - { - pos = ftell (f); - fseek (f, 0, SEEK_END); - length = ftell (f); - fseek (f, pos, SEEK_SET); - if((mt = (miptex_t*)malloc(length+1))==NULL) - flags = 0; - else - { - ((char *)mt)[length] = 0; - fread(mt, 1, length, f); - fclose (f); - flags = mt->flags; - free(mt); - } - } - } - return flags; - */ + if (NULL != (fpak = fopen(pakfile[Game], "rb"))) + { + sprintf(path,"textures/%s.m8",Tex); + g_strdown(path); + num=fread(&pakheader,1,sizeof(pak_header_t),fpak); + if((size_t)num < sizeof(pak_header_t)) + { + fclose(fpak); + return 0; + } + if(strncmp(pakheader.id,"PACK",4)) + { + fclose(fpak); + return 0; + } + numitems = pakheader.dsize/sizeof(pak_item_t); + fseek(fpak,pakheader.dstart,SEEK_SET); + for(i=0; iflags; + free(mt); + } + } + } + fclose(fpak); + } + } + else + { + // Assume .map will be output to gamedir/maps, then back up + // to the gamedir and append /textures. Ugly but it should work + strcpy(path,gszMapFile); + g_strdown(path); + p = strstr(path,"maps"); + if(!p) return 0; + p[0] = '\0'; + strcat(path,"textures/"); + strcat(path,Tex); + strcat(path,".m8"); + f = fopen (path, "rb"); + if (!f) + flags = 0; + else + { + pos = ftell (f); + fseek (f, 0, SEEK_END); + length = ftell (f); + fseek (f, pos, SEEK_SET); + if((mt = (miptex_t*)malloc(length+1))==NULL) + flags = 0; + else + { + ((char *)mt)[length] = 0; + fread(mt, 1, length, f); + fclose (f); + flags = mt->flags; + free(mt); + } + } + } + return flags; + */ } diff --git a/contrib/gtkgensurf/plugin.cpp b/contrib/gtkgensurf/plugin.cpp index 18e12091..38a730da 100644 --- a/contrib/gtkgensurf/plugin.cpp +++ b/contrib/gtkgensurf/plugin.cpp @@ -1,21 +1,21 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "gensurf.h" @@ -31,132 +31,117 @@ bool g_bInitDone; #include "iplugin.h" -const char* QERPlug_Init(void* hApp, void* pMainWidget) -{ - g_pRadiantWnd = (GtkWidget*)pMainWidget; +const char* QERPlug_Init( void* hApp, void* pMainWidget ){ + g_pRadiantWnd = (GtkWidget*)pMainWidget; - return "GenSurf for Q3Radiant"; + return "GenSurf for Q3Radiant"; } -const char* QERPlug_GetName () -{ - return "GtkGenSurf"; +const char* QERPlug_GetName(){ + return "GtkGenSurf"; } -const char* QERPlug_GetCommandList () -{ - return "Wall facing 270...;Wall facing 180...;Wall facing 90...;Wall facing 0...;" - "Ceiling...;Ground surface...;-;About..."; +const char* QERPlug_GetCommandList(){ + return "Wall facing 270...;Wall facing 180...;Wall facing 90...;Wall facing 0...;" + "Ceiling...;Ground surface...;-;About..."; } // vMin/vMax provide the bounds of the selection, they are zero if there is no selection // if there is a selection, bSingleBrush will be true if a single brush is selected // if so, typical plugin behaviour (such as primitive creation) would use the bounds as // a rule to create the primitive, then delete the selection -void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - bool Generate = false; - - if (!g_bInitDone) - { - if (GenSurfInit ()) - g_bInitDone = true; - } - - if (!strcmp (p, "Ground surface...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XY0; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[1]; - Hur = vMax[0]; - Vur = vMax[1]; - Z00 = Z01 = Z10 = Z11 = vMax[2]; - } - Generate = true; - } - else if (!strcmp (p, "Ceiling...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XY1; - if(SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[1]; - Hur = vMax[0]; - Vur = vMax[1]; - Z00 = Z01 = Z10 = Z11 = vMin[2]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 0...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_YZ0; - if (SingleBrushSelected) - { - Hll = vMin[1]; - Vll = vMin[2]; - Hur = vMax[1]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMax[0]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 90...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XZ0; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[2]; - Hur = vMax[0]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMax[1]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 180...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_YZ1; - if (SingleBrushSelected) - { - Hll = vMin[1]; - Vll = vMin[2]; - Hur = vMax[1]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMin[0]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 270...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XZ1; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[2]; - Hur = vMax[0]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMin[1]; - } - Generate = true; - } - else if (!strcmp(p,"About...")) - About (g_pRadiantWnd); - - if (Generate) - { - if (SingleBrushSelected) - UseFaceBounds (); - - gtk_widget_show (g_pWnd); - } +void QERPlug_Dispatch( const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ){ + bool Generate = false; + + if ( !g_bInitDone ) { + if ( GenSurfInit() ) { + g_bInitDone = true; + } + } + + if ( !strcmp( p, "Ground surface..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_XY0; + if ( SingleBrushSelected ) { + Hll = vMin[0]; + Vll = vMin[1]; + Hur = vMax[0]; + Vur = vMax[1]; + Z00 = Z01 = Z10 = Z11 = vMax[2]; + } + Generate = true; + } + else if ( !strcmp( p, "Ceiling..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_XY1; + if ( SingleBrushSelected ) { + Hll = vMin[0]; + Vll = vMin[1]; + Hur = vMax[0]; + Vur = vMax[1]; + Z00 = Z01 = Z10 = Z11 = vMin[2]; + } + Generate = true; + } + else if ( !strcmp( p, "Wall facing 0..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_YZ0; + if ( SingleBrushSelected ) { + Hll = vMin[1]; + Vll = vMin[2]; + Hur = vMax[1]; + Vur = vMax[2]; + Z00 = Z01 = Z10 = Z11 = vMax[0]; + } + Generate = true; + } + else if ( !strcmp( p, "Wall facing 90..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_XZ0; + if ( SingleBrushSelected ) { + Hll = vMin[0]; + Vll = vMin[2]; + Hur = vMax[0]; + Vur = vMax[2]; + Z00 = Z01 = Z10 = Z11 = vMax[1]; + } + Generate = true; + } + else if ( !strcmp( p, "Wall facing 180..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_YZ1; + if ( SingleBrushSelected ) { + Hll = vMin[1]; + Vll = vMin[2]; + Hur = vMax[1]; + Vur = vMax[2]; + Z00 = Z01 = Z10 = Z11 = vMin[0]; + } + Generate = true; + } + else if ( !strcmp( p, "Wall facing 270..." ) ) { + SingleBrushSelected = bSingleBrush; + Plane = PLANE_XZ1; + if ( SingleBrushSelected ) { + Hll = vMin[0]; + Vll = vMin[2]; + Hur = vMax[0]; + Vur = vMax[2]; + Z00 = Z01 = Z10 = Z11 = vMin[1]; + } + Generate = true; + } + else if ( !strcmp( p,"About..." ) ) { + About( g_pRadiantWnd ); + } + + if ( Generate ) { + if ( SingleBrushSelected ) { + UseFaceBounds(); + } + + gtk_widget_show( g_pWnd ); + } } // ============================================================================= @@ -167,58 +152,53 @@ void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrus class GenSurfSynapseClient : public CSynapseClient { public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - GenSurfSynapseClient() { } - virtual ~GenSurfSynapseClient() { } +// CSynapseClient API +bool RequestAPI( APIDescriptor_t *pAPI ); +const char* GetInfo(); + +GenSurfSynapseClient() { } +virtual ~GenSurfSynapseClient() { } }; CSynapseServer* g_pSynapseServer = NULL; GenSurfSynapseClient g_SynapseClient; -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "gtkgensurf", sizeof(_QERPluginTable)); - - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(_QERFuncTable_1), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(UIGTK_MAJOR, NULL, sizeof(_QERUIGtkTable), SYN_REQUIRE, &g_UIGtkTable); - g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(_QERQglTable), SYN_REQUIRE, &g_GLTable); - g_SynapseClient.AddAPI(ENTITY_MAJOR, NULL, sizeof(_QEREntityTable), SYN_REQUIRE, &g_EntityTable); - - return &g_SynapseClient; +extern "C" CSynapseClient * SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces( const char *version, CSynapseServer *pServer ){ + if ( strcmp( version, SYNAPSE_VERSION ) ) { + Syn_Printf( "ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version ); + return NULL; + } + g_pSynapseServer = pServer; + g_pSynapseServer->IncRef(); + Set_Syn_Printf( g_pSynapseServer->Get_Syn_Printf() ); + + g_SynapseClient.AddAPI( PLUGIN_MAJOR, "gtkgensurf", sizeof( _QERPluginTable ) ); + + g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( _QERFuncTable_1 ), SYN_REQUIRE, &g_FuncTable ); + g_SynapseClient.AddAPI( UIGTK_MAJOR, NULL, sizeof( _QERUIGtkTable ), SYN_REQUIRE, &g_UIGtkTable ); + g_SynapseClient.AddAPI( QGL_MAJOR, NULL, sizeof( _QERQglTable ), SYN_REQUIRE, &g_GLTable ); + g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( _QEREntityTable ), SYN_REQUIRE, &g_EntityTable ); + + return &g_SynapseClient; } -bool GenSurfSynapseClient::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; +bool GenSurfSynapseClient::RequestAPI( APIDescriptor_t *pAPI ){ + if ( !strcmp( pAPI->major_name, PLUGIN_MAJOR ) ) { + _QERPluginTable* pTable = static_cast<_QERPluginTable*>( pAPI->mpTable ); + + pTable->m_pfnQERPlug_Init = QERPlug_Init; + pTable->m_pfnQERPlug_GetName = QERPlug_GetName; + pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + return true; + } + + Syn_Printf( "ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo() ); + return false; } #include "version.h" -const char* GenSurfSynapseClient::GetInfo() -{ - return "GtkGenSurf - built " __DATE__ " " RADIANT_VERSION; +const char* GenSurfSynapseClient::GetInfo(){ + return "GtkGenSurf - built " __DATE__ " " RADIANT_VERSION; } diff --git a/contrib/gtkgensurf/triangle.c b/contrib/gtkgensurf/triangle.c index 1e155cac..8d4e0c98 100644 --- a/contrib/gtkgensurf/triangle.c +++ b/contrib/gtkgensurf/triangle.c @@ -352,7 +352,7 @@ enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE}; /* or was not inserted because another point occupies the same location. */ enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT, - DUPLICATEPOINT}; + DUPLICATEPOINT}; /* Labels that signify the result of direction finding. The result */ /* indicates that a segment connecting the two query points falls within */ @@ -488,8 +488,8 @@ typedef REAL **triangle; /* Really: typedef triangle *triangle */ /* directed to point counterclockwise about the corresponding triangle. */ struct triedge { - triangle *tri; - int orient; /* Ranges from 0 to 2. */ + triangle *tri; + int orient; /* Ranges from 0 to 2. */ }; /* The shell data structure. Each shell edge contains two pointers to */ @@ -504,8 +504,8 @@ typedef REAL **shelle; /* Really: typedef shelle *shelle */ /* directed so that the "side" denoted is the right side of the edge. */ struct edge { - shelle *sh; - int shorient; /* Ranges from 0 to 1. */ + shelle *sh; + int shorient; /* Ranges from 0 to 1. */ }; /* The point data structure. Each point is actually an array of REALs. */ @@ -519,9 +519,9 @@ typedef REAL *point; /* stored so that one can check whether a segment is still the same. */ struct badsegment { - struct edge encsegment; /* An encroached segment. */ - point segorg, segdest; /* The two vertices. */ - struct badsegment *nextsegment; /* Pointer to next encroached segment. */ + struct edge encsegment; /* An encroached segment. */ + point segorg, segdest; /* The two vertices. */ + struct badsegment *nextsegment; /* Pointer to next encroached segment. */ }; /* A queue used to store bad triangles. The key is the square of the cosine */ @@ -529,10 +529,10 @@ struct badsegment { /* stored so that one can check whether a triangle is still the same. */ struct badface { - struct triedge badfacetri; /* A bad triangle. */ - REAL key; /* cos^2 of smallest (apical) angle. */ - point faceorg, facedest, faceapex; /* The three vertices. */ - struct badface *nextface; /* Pointer to next bad triangle. */ + struct triedge badfacetri; /* A bad triangle. */ + REAL key; /* cos^2 of smallest (apical) angle. */ + point faceorg, facedest, faceapex; /* The three vertices. */ + struct badface *nextface; /* Pointer to next bad triangle. */ }; /* A node in a heap used to store events for the sweepline Delaunay */ @@ -546,9 +546,9 @@ struct badface { /* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */ struct event { - REAL xkey, ykey; /* Coordinates of the event. */ - VOID *eventptr; /* Can be a point or the location of a circle event. */ - int heapposition; /* Marks this event's position in the heap. */ + REAL xkey, ykey; /* Coordinates of the event. */ + VOID *eventptr; /* Can be a point or the location of a circle event. */ + int heapposition; /* Marks this event's position in the heap. */ }; /* A node in the splay tree. Each node holds an oriented ghost triangle */ @@ -563,9 +563,9 @@ struct event { /* boundary edge and should be deleted. */ struct splaynode { - struct triedge keyedge; /* Lprev of an edge on the front. */ - point keydest; /* Used to verify that splay node is still live. */ - struct splaynode *lchild, *rchild; /* Children in splay tree. */ + struct triedge keyedge; /* Lprev of an edge on the front. */ + point keydest; /* Used to verify that splay node is still live. */ + struct splaynode *lchild, *rchild; /* Children in splay tree. */ }; /* A type used to allocate memory. firstblock is the first block of items. */ @@ -593,18 +593,18 @@ struct splaynode { /* on deaditemstack. */ struct memorypool { - VOID **firstblock, **nowblock; - VOID *nextitem; - VOID *deaditemstack; - VOID **pathblock; - VOID *pathitem; - enum wordtype itemwordtype; - int alignbytes; - int itembytes, itemwords; - int itemsperblock; - long items, maxitems; - int unallocateditems; - int pathitemsleft; + VOID **firstblock, **nowblock; + VOID *nextitem; + VOID *deaditemstack; + VOID **pathblock; + VOID *pathitem; + enum wordtype itemwordtype; + int alignbytes; + int itembytes, itemwords; + int itemsperblock; + long items, maxitems; + int unallocateditems; + int pathitemsleft; }; /* Variables used to allocate memory for triangles, shell edges, points, */ @@ -786,17 +786,17 @@ int minus1mod3[3] = {2, 0, 1}; /* decode() converts a pointer to an oriented triangle. The orientation is */ /* extracted from the two least significant bits of the pointer. */ -#define decode(ptr, triedge) \ - (triedge).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l); \ - (triedge).tri = (triangle *) \ - ((unsigned long) (ptr) ^ (unsigned long) (triedge).orient) +#define decode( ptr, triedge ) \ + ( triedge ).orient = (int) ( (unsigned long) ( ptr ) & (unsigned long) 3l ); \ + ( triedge ).tri = (triangle *) \ + ( (unsigned long) ( ptr ) ^ (unsigned long) ( triedge ).orient ) /* encode() compresses an oriented triangle into a single pointer. It */ /* relies on the assumption that all triangles are aligned to four-byte */ /* boundaries, so the two least significant bits of (triedge).tri are zero.*/ -#define encode(triedge) \ - (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient) +#define encode( triedge ) \ + (triangle) ( (unsigned long) ( triedge ).tri | (unsigned long) ( triedge ).orient ) /* The following edge manipulation primitives are all described by Guibas */ /* and Stolfi. However, they use an edge-based data structure, whereas I */ @@ -806,190 +806,190 @@ int minus1mod3[3] = {2, 0, 1}; /* edge direction is necessarily reversed, because triangle/edge handles */ /* are always directed counterclockwise around the triangle. */ -#define sym(triedge1, triedge2) \ - ptr = (triedge1).tri[(triedge1).orient]; \ - decode(ptr, triedge2); +#define sym( triedge1, triedge2 ) \ + ptr = ( triedge1 ).tri[( triedge1 ).orient]; \ + decode( ptr, triedge2 ); -#define symself(triedge) \ - ptr = (triedge).tri[(triedge).orient]; \ - decode(ptr, triedge); +#define symself( triedge ) \ + ptr = ( triedge ).tri[( triedge ).orient]; \ + decode( ptr, triedge ); /* lnext() finds the next edge (counterclockwise) of a triangle. */ -#define lnext(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = plus1mod3[(triedge1).orient] +#define lnext( triedge1, triedge2 ) \ + ( triedge2 ).tri = ( triedge1 ).tri; \ + ( triedge2 ).orient = plus1mod3[( triedge1 ).orient] -#define lnextself(triedge) \ - (triedge).orient = plus1mod3[(triedge).orient] +#define lnextself( triedge ) \ + ( triedge ).orient = plus1mod3[( triedge ).orient] /* lprev() finds the previous edge (clockwise) of a triangle. */ -#define lprev(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = minus1mod3[(triedge1).orient] +#define lprev( triedge1, triedge2 ) \ + ( triedge2 ).tri = ( triedge1 ).tri; \ + ( triedge2 ).orient = minus1mod3[( triedge1 ).orient] -#define lprevself(triedge) \ - (triedge).orient = minus1mod3[(triedge).orient] +#define lprevself( triedge ) \ + ( triedge ).orient = minus1mod3[( triedge ).orient] /* onext() spins counterclockwise around a point; that is, it finds the next */ /* edge with the same origin in the counterclockwise direction. This edge */ /* will be part of a different triangle. */ -#define onext(triedge1, triedge2) \ - lprev(triedge1, triedge2); \ - symself(triedge2); +#define onext( triedge1, triedge2 ) \ + lprev( triedge1, triedge2 ); \ + symself( triedge2 ); -#define onextself(triedge) \ - lprevself(triedge); \ - symself(triedge); +#define onextself( triedge ) \ + lprevself( triedge ); \ + symself( triedge ); /* oprev() spins clockwise around a point; that is, it finds the next edge */ /* with the same origin in the clockwise direction. This edge will be */ /* part of a different triangle. */ -#define oprev(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lnextself(triedge2); +#define oprev( triedge1, triedge2 ) \ + sym( triedge1, triedge2 ); \ + lnextself( triedge2 ); -#define oprevself(triedge) \ - symself(triedge); \ - lnextself(triedge); +#define oprevself( triedge ) \ + symself( triedge ); \ + lnextself( triedge ); /* dnext() spins counterclockwise around a point; that is, it finds the next */ /* edge with the same destination in the counterclockwise direction. This */ /* edge will be part of a different triangle. */ -#define dnext(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lprevself(triedge2); +#define dnext( triedge1, triedge2 ) \ + sym( triedge1, triedge2 ); \ + lprevself( triedge2 ); -#define dnextself(triedge) \ - symself(triedge); \ - lprevself(triedge); +#define dnextself( triedge ) \ + symself( triedge ); \ + lprevself( triedge ); /* dprev() spins clockwise around a point; that is, it finds the next edge */ /* with the same destination in the clockwise direction. This edge will */ /* be part of a different triangle. */ -#define dprev(triedge1, triedge2) \ - lnext(triedge1, triedge2); \ - symself(triedge2); +#define dprev( triedge1, triedge2 ) \ + lnext( triedge1, triedge2 ); \ + symself( triedge2 ); -#define dprevself(triedge) \ - lnextself(triedge); \ - symself(triedge); +#define dprevself( triedge ) \ + lnextself( triedge ); \ + symself( triedge ); /* rnext() moves one edge counterclockwise about the adjacent triangle. */ /* (It's best understood by reading Guibas and Stolfi. It involves */ /* changing triangles twice.) */ -#define rnext(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lnextself(triedge2); \ - symself(triedge2); +#define rnext( triedge1, triedge2 ) \ + sym( triedge1, triedge2 ); \ + lnextself( triedge2 ); \ + symself( triedge2 ); -#define rnextself(triedge) \ - symself(triedge); \ - lnextself(triedge); \ - symself(triedge); +#define rnextself( triedge ) \ + symself( triedge ); \ + lnextself( triedge ); \ + symself( triedge ); /* rnext() moves one edge clockwise about the adjacent triangle. */ /* (It's best understood by reading Guibas and Stolfi. It involves */ /* changing triangles twice.) */ -#define rprev(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lprevself(triedge2); \ - symself(triedge2); +#define rprev( triedge1, triedge2 ) \ + sym( triedge1, triedge2 ); \ + lprevself( triedge2 ); \ + symself( triedge2 ); -#define rprevself(triedge) \ - symself(triedge); \ - lprevself(triedge); \ - symself(triedge); +#define rprevself( triedge ) \ + symself( triedge ); \ + lprevself( triedge ); \ + symself( triedge ); /* These primitives determine or set the origin, destination, or apex of a */ /* triangle. */ -#define org(triedge, pointptr) \ - pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3] +#define org( triedge, pointptr ) \ + pointptr = (point) ( triedge ).tri[plus1mod3[( triedge ).orient] + 3] -#define dest(triedge, pointptr) \ - pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3] +#define dest( triedge, pointptr ) \ + pointptr = (point) ( triedge ).tri[minus1mod3[( triedge ).orient] + 3] -#define apex(triedge, pointptr) \ - pointptr = (point) (triedge).tri[(triedge).orient + 3] +#define apex( triedge, pointptr ) \ + pointptr = (point) ( triedge ).tri[( triedge ).orient + 3] -#define setorg(triedge, pointptr) \ - (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr +#define setorg( triedge, pointptr ) \ + ( triedge ).tri[plus1mod3[( triedge ).orient] + 3] = (triangle) pointptr -#define setdest(triedge, pointptr) \ - (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr +#define setdest( triedge, pointptr ) \ + ( triedge ).tri[minus1mod3[( triedge ).orient] + 3] = (triangle) pointptr -#define setapex(triedge, pointptr) \ - (triedge).tri[(triedge).orient + 3] = (triangle) pointptr +#define setapex( triedge, pointptr ) \ + ( triedge ).tri[( triedge ).orient + 3] = (triangle) pointptr -#define setvertices2null(triedge) \ - (triedge).tri[3] = (triangle) NULL; \ - (triedge).tri[4] = (triangle) NULL; \ - (triedge).tri[5] = (triangle) NULL; +#define setvertices2null( triedge ) \ + ( triedge ).tri[3] = (triangle) NULL; \ + ( triedge ).tri[4] = (triangle) NULL; \ + ( triedge ).tri[5] = (triangle) NULL; /* Bond two triangles together. */ -#define bond(triedge1, triedge2) \ - (triedge1).tri[(triedge1).orient] = encode(triedge2); \ - (triedge2).tri[(triedge2).orient] = encode(triedge1) +#define bond( triedge1, triedge2 ) \ + ( triedge1 ).tri[( triedge1 ).orient] = encode( triedge2 ); \ + ( triedge2 ).tri[( triedge2 ).orient] = encode( triedge1 ) /* Dissolve a bond (from one side). Note that the other triangle will still */ /* think it's connected to this triangle. Usually, however, the other */ /* triangle is being deleted entirely, or bonded to another triangle, so */ /* it doesn't matter. */ -#define dissolve(triedge) \ - (triedge).tri[(triedge).orient] = (triangle) dummytri +#define dissolve( triedge ) \ + ( triedge ).tri[( triedge ).orient] = (triangle) dummytri /* Copy a triangle/edge handle. */ -#define triedgecopy(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = (triedge1).orient +#define triedgecopy( triedge1, triedge2 ) \ + ( triedge2 ).tri = ( triedge1 ).tri; \ + ( triedge2 ).orient = ( triedge1 ).orient /* Test for equality of triangle/edge handles. */ -#define triedgeequal(triedge1, triedge2) \ - (((triedge1).tri == (triedge2).tri) && \ - ((triedge1).orient == (triedge2).orient)) +#define triedgeequal( triedge1, triedge2 ) \ + ( ( ( triedge1 ).tri == ( triedge2 ).tri ) && \ + ( ( triedge1 ).orient == ( triedge2 ).orient ) ) /* Primitives to infect or cure a triangle with the virus. These rely on */ /* the assumption that all shell edges are aligned to four-byte boundaries.*/ -#define infect(triedge) \ - (triedge).tri[6] = (triangle) \ - ((unsigned long) (triedge).tri[6] | (unsigned long) 2l) +#define infect( triedge ) \ + ( triedge ).tri[6] = (triangle) \ + ( (unsigned long) ( triedge ).tri[6] | (unsigned long) 2l ) -#define uninfect(triedge) \ - (triedge).tri[6] = (triangle) \ - ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l) +#define uninfect( triedge ) \ + ( triedge ).tri[6] = (triangle) \ + ( (unsigned long) ( triedge ).tri[6] & ~(unsigned long) 2l ) /* Test a triangle for viral infection. */ -#define infected(triedge) \ - (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0) +#define infected( triedge ) \ + ( ( (unsigned long) ( triedge ).tri[6] & (unsigned long) 2l ) != 0 ) /* Check or set a triangle's attributes. */ -#define elemattribute(triedge, attnum) \ - ((REAL *) (triedge).tri)[elemattribindex + (attnum)] +#define elemattribute( triedge, attnum ) \ + ( (REAL *) ( triedge ).tri )[elemattribindex + ( attnum )] -#define setelemattribute(triedge, attnum, value) \ - ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = (REAL)value +#define setelemattribute( triedge, attnum, value ) \ + ( (REAL *) ( triedge ).tri )[elemattribindex + ( attnum )] = (REAL)value /* Check or set a triangle's maximum area bound. */ -#define areabound(triedge) ((REAL *) (triedge).tri)[areaboundindex] +#define areabound( triedge ) ( (REAL *) ( triedge ).tri )[areaboundindex] -#define setareabound(triedge, value) \ - ((REAL *) (triedge).tri)[areaboundindex] = (REAL)value +#define setareabound( triedge, value ) \ + ( (REAL *) ( triedge ).tri )[areaboundindex] = (REAL)value /********* Primitives for shell edges *********/ /* */ @@ -1000,95 +1000,95 @@ int minus1mod3[3] = {2, 0, 1}; /* least significant bits (one for orientation, one for viral infection) */ /* are masked out to produce the real pointer. */ -#define sdecode(sptr, edge) \ - (edge).shorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l); \ - (edge).sh = (shelle *) \ - ((unsigned long) (sptr) & ~ (unsigned long) 3l) +#define sdecode( sptr, edge ) \ + ( edge ).shorient = (int) ( (unsigned long) ( sptr ) & (unsigned long) 1l ); \ + ( edge ).sh = (shelle *) \ + ( (unsigned long) ( sptr ) & ~(unsigned long) 3l ) /* sencode() compresses an oriented shell edge into a single pointer. It */ /* relies on the assumption that all shell edges are aligned to two-byte */ /* boundaries, so the least significant bit of (edge).sh is zero. */ -#define sencode(edge) \ - (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient) +#define sencode( edge ) \ + (shelle) ( (unsigned long) ( edge ).sh | (unsigned long) ( edge ).shorient ) /* ssym() toggles the orientation of a shell edge. */ -#define ssym(edge1, edge2) \ - (edge2).sh = (edge1).sh; \ - (edge2).shorient = 1 - (edge1).shorient +#define ssym( edge1, edge2 ) \ + ( edge2 ).sh = ( edge1 ).sh; \ + ( edge2 ).shorient = 1 - ( edge1 ).shorient -#define ssymself(edge) \ - (edge).shorient = 1 - (edge).shorient +#define ssymself( edge ) \ + ( edge ).shorient = 1 - ( edge ).shorient /* spivot() finds the other shell edge (from the same segment) that shares */ /* the same origin. */ -#define spivot(edge1, edge2) \ - sptr = (edge1).sh[(edge1).shorient]; \ - sdecode(sptr, edge2) +#define spivot( edge1, edge2 ) \ + sptr = ( edge1 ).sh[( edge1 ).shorient]; \ + sdecode( sptr, edge2 ) -#define spivotself(edge) \ - sptr = (edge).sh[(edge).shorient]; \ - sdecode(sptr, edge) +#define spivotself( edge ) \ + sptr = ( edge ).sh[( edge ).shorient]; \ + sdecode( sptr, edge ) /* snext() finds the next shell edge (from the same segment) in sequence; */ /* one whose origin is the input shell edge's destination. */ -#define snext(edge1, edge2) \ - sptr = (edge1).sh[1 - (edge1).shorient]; \ - sdecode(sptr, edge2) +#define snext( edge1, edge2 ) \ + sptr = ( edge1 ).sh[1 - ( edge1 ).shorient]; \ + sdecode( sptr, edge2 ) -#define snextself(edge) \ - sptr = (edge).sh[1 - (edge).shorient]; \ - sdecode(sptr, edge) +#define snextself( edge ) \ + sptr = ( edge ).sh[1 - ( edge ).shorient]; \ + sdecode( sptr, edge ) /* These primitives determine or set the origin or destination of a shell */ /* edge. */ -#define sorg(edge, pointptr) \ - pointptr = (point) (edge).sh[2 + (edge).shorient] +#define sorg( edge, pointptr ) \ + pointptr = (point) ( edge ).sh[2 + ( edge ).shorient] -#define sdest(edge, pointptr) \ - pointptr = (point) (edge).sh[3 - (edge).shorient] +#define sdest( edge, pointptr ) \ + pointptr = (point) ( edge ).sh[3 - ( edge ).shorient] -#define setsorg(edge, pointptr) \ - (edge).sh[2 + (edge).shorient] = (shelle) pointptr +#define setsorg( edge, pointptr ) \ + ( edge ).sh[2 + ( edge ).shorient] = (shelle) pointptr -#define setsdest(edge, pointptr) \ - (edge).sh[3 - (edge).shorient] = (shelle) pointptr +#define setsdest( edge, pointptr ) \ + ( edge ).sh[3 - ( edge ).shorient] = (shelle) pointptr /* These primitives read or set a shell marker. Shell markers are used to */ /* hold user boundary information. */ -#define mark(edge) (* (int *) ((edge).sh + 6)) +#define mark( edge ) ( *(int *) ( ( edge ).sh + 6 ) ) -#define setmark(edge, value) \ - * (int *) ((edge).sh + 6) = value +#define setmark( edge, value ) \ + *(int *) ( ( edge ).sh + 6 ) = value /* Bond two shell edges together. */ -#define sbond(edge1, edge2) \ - (edge1).sh[(edge1).shorient] = sencode(edge2); \ - (edge2).sh[(edge2).shorient] = sencode(edge1) +#define sbond( edge1, edge2 ) \ + ( edge1 ).sh[( edge1 ).shorient] = sencode( edge2 ); \ + ( edge2 ).sh[( edge2 ).shorient] = sencode( edge1 ) /* Dissolve a shell edge bond (from one side). Note that the other shell */ /* edge will still think it's connected to this shell edge. */ -#define sdissolve(edge) \ - (edge).sh[(edge).shorient] = (shelle) dummysh +#define sdissolve( edge ) \ + ( edge ).sh[( edge ).shorient] = (shelle) dummysh /* Copy a shell edge. */ -#define shellecopy(edge1, edge2) \ - (edge2).sh = (edge1).sh; \ - (edge2).shorient = (edge1).shorient +#define shellecopy( edge1, edge2 ) \ + ( edge2 ).sh = ( edge1 ).sh; \ + ( edge2 ).shorient = ( edge1 ).shorient /* Test for equality of shell edges. */ -#define shelleequal(edge1, edge2) \ - (((edge1).sh == (edge2).sh) && \ - ((edge1).shorient == (edge2).shorient)) +#define shelleequal( edge1, edge2 ) \ + ( ( ( edge1 ).sh == ( edge2 ).sh ) && \ + ( ( edge1 ).shorient == ( edge2 ).shorient ) ) /********* Primitives for interacting triangles and shell edges *********/ /* */ @@ -1096,46 +1096,46 @@ int minus1mod3[3] = {2, 0, 1}; /* tspivot() finds a shell edge abutting a triangle. */ -#define tspivot(triedge, edge) \ - sptr = (shelle) (triedge).tri[6 + (triedge).orient]; \ - sdecode(sptr, edge) +#define tspivot( triedge, edge ) \ + sptr = (shelle) ( triedge ).tri[6 + ( triedge ).orient]; \ + sdecode( sptr, edge ) /* stpivot() finds a triangle abutting a shell edge. It requires that the */ /* variable `ptr' of type `triangle' be defined. */ -#define stpivot(edge, triedge) \ - ptr = (triangle) (edge).sh[4 + (edge).shorient]; \ - decode(ptr, triedge) +#define stpivot( edge, triedge ) \ + ptr = (triangle) ( edge ).sh[4 + ( edge ).shorient]; \ + decode( ptr, triedge ) /* Bond a triangle to a shell edge. */ -#define tsbond(triedge, edge) \ - (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge); \ - (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge) +#define tsbond( triedge, edge ) \ + ( triedge ).tri[6 + ( triedge ).orient] = (triangle) sencode( edge ); \ + ( edge ).sh[4 + ( edge ).shorient] = (shelle) encode( triedge ) /* Dissolve a bond (from the triangle side). */ -#define tsdissolve(triedge) \ - (triedge).tri[6 + (triedge).orient] = (triangle) dummysh +#define tsdissolve( triedge ) \ + ( triedge ).tri[6 + ( triedge ).orient] = (triangle) dummysh /* Dissolve a bond (from the shell edge side). */ -#define stdissolve(edge) \ - (edge).sh[4 + (edge).shorient] = (shelle) dummytri +#define stdissolve( edge ) \ + ( edge ).sh[4 + ( edge ).shorient] = (shelle) dummytri /********* Primitives for points *********/ /* */ /* */ -#define pointmark(pt) ((int *) (pt))[pointmarkindex] +#define pointmark( pt ) ( (int *) ( pt ) )[pointmarkindex] -#define setpointmark(pt, value) \ - ((int *) (pt))[pointmarkindex] = value +#define setpointmark( pt, value ) \ + ( (int *) ( pt ) )[pointmarkindex] = value -#define point2tri(pt) ((triangle *) (pt))[point2triindex] +#define point2tri( pt ) ( (triangle *) ( pt ) )[point2triindex] -#define setpoint2tri(pt, value) \ - ((triangle *) (pt))[point2triindex] = value +#define setpoint2tri( pt, value ) \ + ( (triangle *) ( pt ) )[point2triindex] = value /** **/ /** **/ @@ -1153,65 +1153,64 @@ int minus1mod3[3] = {2, 0, 1}; #ifndef TRILIBRARY -void syntax() -{ +void syntax(){ #ifdef CDT_ONLY #ifdef REDUCED - printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n"); + printf( "triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n" ); #else /* not REDUCED */ - printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n"); + printf( "triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n" ); #endif /* not REDUCED */ #else /* not CDT_ONLY */ #ifdef REDUCED - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n"); + printf( "triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n" ); #else /* not REDUCED */ - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n"); + printf( "triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n" ); #endif /* not REDUCED */ #endif /* not CDT_ONLY */ - printf(" -p Triangulates a Planar Straight Line Graph (.poly file).\n"); + printf( " -p Triangulates a Planar Straight Line Graph (.poly file).\n" ); #ifndef CDT_ONLY - printf(" -r Refines a previously generated mesh.\n"); - printf( - " -q Quality mesh generation. A minimum angle may be specified.\n"); - printf(" -a Applies a maximum triangle area constraint.\n"); + printf( " -r Refines a previously generated mesh.\n" ); + printf( + " -q Quality mesh generation. A minimum angle may be specified.\n" ); + printf( " -a Applies a maximum triangle area constraint.\n" ); #endif /* not CDT_ONLY */ - printf( - " -A Applies attributes to identify elements in certain regions.\n"); - printf(" -c Encloses the convex hull with segments.\n"); - printf(" -e Generates an edge list.\n"); - printf(" -v Generates a Voronoi diagram.\n"); - printf(" -n Generates a list of triangle neighbors.\n"); - printf(" -g Generates an .off file for Geomview.\n"); - printf(" -B Suppresses output of boundary information.\n"); - printf(" -P Suppresses output of .poly file.\n"); - printf(" -N Suppresses output of .node file.\n"); - printf(" -E Suppresses output of .ele file.\n"); - printf(" -I Suppresses mesh iteration numbers.\n"); - printf(" -O Ignores holes in .poly file.\n"); - printf(" -X Suppresses use of exact arithmetic.\n"); - printf(" -z Numbers all items starting from zero (rather than one).\n"); - printf(" -o2 Generates second-order subparametric elements.\n"); + printf( + " -A Applies attributes to identify elements in certain regions.\n" ); + printf( " -c Encloses the convex hull with segments.\n" ); + printf( " -e Generates an edge list.\n" ); + printf( " -v Generates a Voronoi diagram.\n" ); + printf( " -n Generates a list of triangle neighbors.\n" ); + printf( " -g Generates an .off file for Geomview.\n" ); + printf( " -B Suppresses output of boundary information.\n" ); + printf( " -P Suppresses output of .poly file.\n" ); + printf( " -N Suppresses output of .node file.\n" ); + printf( " -E Suppresses output of .ele file.\n" ); + printf( " -I Suppresses mesh iteration numbers.\n" ); + printf( " -O Ignores holes in .poly file.\n" ); + printf( " -X Suppresses use of exact arithmetic.\n" ); + printf( " -z Numbers all items starting from zero (rather than one).\n" ); + printf( " -o2 Generates second-order subparametric elements.\n" ); #ifndef CDT_ONLY - printf(" -Y Suppresses boundary segment splitting.\n"); - printf(" -S Specifies maximum number of added Steiner points.\n"); + printf( " -Y Suppresses boundary segment splitting.\n" ); + printf( " -S Specifies maximum number of added Steiner points.\n" ); #endif /* not CDT_ONLY */ #ifndef REDUCED - printf(" -i Uses incremental method, rather than divide-and-conquer.\n"); - printf(" -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n"); + printf( " -i Uses incremental method, rather than divide-and-conquer.\n" ); + printf( " -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n" ); #endif /* not REDUCED */ - printf(" -l Uses vertical cuts only, rather than alternating cuts.\n"); + printf( " -l Uses vertical cuts only, rather than alternating cuts.\n" ); #ifndef REDUCED #ifndef CDT_ONLY - printf( - " -s Force segments into mesh by splitting (instead of using CDT).\n"); + printf( + " -s Force segments into mesh by splitting (instead of using CDT).\n" ); #endif /* not CDT_ONLY */ - printf(" -C Check consistency of final mesh.\n"); + printf( " -C Check consistency of final mesh.\n" ); #endif /* not REDUCED */ - printf(" -Q Quiet: No terminal output except errors.\n"); - printf(" -V Verbose: Detailed information on what I'm doing.\n"); - printf(" -h Help: Detailed instructions for Triangle.\n"); - exit(0); + printf( " -Q Quiet: No terminal output except errors.\n" ); + printf( " -V Verbose: Detailed information on what I'm doing.\n" ); + printf( " -h Help: Detailed instructions for Triangle.\n" ); + exit( 0 ); } #endif /* not TRILIBRARY */ @@ -1224,1427 +1223,1426 @@ void syntax() #ifndef TRILIBRARY -void info() -{ - printf("Triangle\n"); - printf( -"A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n"); - printf("Version 1.3\n\n"); - printf( -"Copyright 1996 Jonathan Richard Shewchuk (bugs/comments to jrs@cs.cmu.edu)\n" -); - printf("School of Computer Science / Carnegie Mellon University\n"); - printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania 15213-3891\n"); - printf( -"Created as part of the Archimedes project (tools for parallel FEM).\n"); - printf( -"Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n"); - printf("There is no warranty whatsoever. Use at your own risk.\n"); +void info(){ + printf( "Triangle\n" ); + printf( + "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n" ); + printf( "Version 1.3\n\n" ); + printf( + "Copyright 1996 Jonathan Richard Shewchuk (bugs/comments to jrs@cs.cmu.edu)\n" + ); + printf( "School of Computer Science / Carnegie Mellon University\n" ); + printf( "5000 Forbes Avenue / Pittsburgh, Pennsylvania 15213-3891\n" ); + printf( + "Created as part of the Archimedes project (tools for parallel FEM).\n" ); + printf( + "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n" ); + printf( "There is no warranty whatsoever. Use at your own risk.\n" ); #ifdef SINGLE - printf("This executable is compiled for single precision arithmetic.\n\n\n"); + printf( "This executable is compiled for single precision arithmetic.\n\n\n" ); #else /* not SINGLE */ - printf("This executable is compiled for double precision arithmetic.\n\n\n"); + printf( "This executable is compiled for double precision arithmetic.\n\n\n" ); #endif /* not SINGLE */ - printf( -"Triangle generates exact Delaunay triangulations, constrained Delaunay\n"); - printf( -"triangulations, and quality conforming Delaunay triangulations. The latter\n" -); - printf( -"can be generated with no small angles, and are thus suitable for finite\n"); - printf( -"element analysis. If no command line switches are specified, your .node\n"); - printf( -"input file will be read, and the Delaunay triangulation will be returned in\n" -); - printf(".node and .ele output files. The command syntax is:\n\n"); + printf( + "Triangle generates exact Delaunay triangulations, constrained Delaunay\n" ); + printf( + "triangulations, and quality conforming Delaunay triangulations. The latter\n" + ); + printf( + "can be generated with no small angles, and are thus suitable for finite\n" ); + printf( + "element analysis. If no command line switches are specified, your .node\n" ); + printf( + "input file will be read, and the Delaunay triangulation will be returned in\n" + ); + printf( ".node and .ele output files. The command syntax is:\n\n" ); #ifdef CDT_ONLY #ifdef REDUCED - printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n"); + printf( "triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n" ); #else /* not REDUCED */ - printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n"); + printf( "triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n" ); #endif /* not REDUCED */ #else /* not CDT_ONLY */ #ifdef REDUCED - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n"); + printf( "triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n" ); #else /* not REDUCED */ - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n"); + printf( "triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n" ); #endif /* not REDUCED */ #endif /* not CDT_ONLY */ - printf( -"Underscores indicate that numbers may optionally follow certain switches;\n"); - printf( -"do not leave any space between a switch and its numeric parameter.\n"); - printf( -"input_file must be a file with extension .node, or extension .poly if the\n"); - printf( -"-p switch is used. If -r is used, you must supply .node and .ele files,\n"); - printf( -"and possibly a .poly file and .area file as well. The formats of these\n"); - printf("files are described below.\n\n"); - printf("Command Line Switches:\n\n"); - printf( -" -p Reads a Planar Straight Line Graph (.poly file), which can specify\n" -); - printf( -" points, segments, holes, and regional attributes and area\n"); - printf( -" constraints. Will generate a constrained Delaunay triangulation\n"); - printf( -" fitting the input; or, if -s, -q, or -a is used, a conforming\n"); - printf( -" Delaunay triangulation. If -p is not used, Triangle reads a .node\n" -); - printf(" file by default.\n"); - printf( -" -r Refines a previously generated mesh. The mesh is read from a .node\n" -); - printf( -" file and an .ele file. If -p is also used, a .poly file is read\n"); - printf( -" and used to constrain edges in the mesh. Further details on\n"); - printf(" refinement are given below.\n"); - printf( -" -q Quality mesh generation by Jim Ruppert's Delaunay refinement\n"); - printf( -" algorithm. Adds points to the mesh to ensure that no angles\n"); - printf( -" smaller than 20 degrees occur. An alternative minimum angle may be\n" -); - printf( -" specified after the `q'. If the minimum angle is 20.7 degrees or\n"); - printf( -" smaller, the triangulation algorithm is theoretically guaranteed to\n" -); - printf( -" terminate (assuming infinite precision arithmetic - Triangle may\n"); - printf( -" fail to terminate if you run out of precision). In practice, the\n"); - printf( -" algorithm often succeeds for minimum angles up to 33.8 degrees.\n"); - printf( -" For highly refined meshes, however, it may be necessary to reduce\n"); - printf( -" the minimum angle to well below 20 to avoid problems associated\n"); - printf( -" with insufficient floating-point precision. The specified angle\n"); - printf(" may include a decimal point.\n"); - printf( -" -a Imposes a maximum triangle area. If a number follows the `a', no\n"); - printf( -" triangle will be generated whose area is larger than that number.\n"); - printf( -" If no number is specified, an .area file (if -r is used) or .poly\n"); - printf( -" file (if -r is not used) specifies a number of maximum area\n"); - printf( -" constraints. An .area file contains a separate area constraint for\n" -); - printf( -" each triangle, and is useful for refining a finite element mesh\n"); - printf( -" based on a posteriori error estimates. A .poly file can optionally\n" -); - printf( -" contain an area constraint for each segment-bounded region, thereby\n" -); - printf( -" enforcing triangle densities in a first triangulation. You can\n"); - printf( -" impose both a fixed area constraint and a varying area constraint\n"); - printf( -" by invoking the -a switch twice, once with and once without a\n"); - printf( -" number following. Each area specified may include a decimal point.\n" -); - printf( -" -A Assigns an additional attribute to each triangle that identifies\n"); - printf( -" what segment-bounded region each triangle belongs to. Attributes\n"); - printf( -" are assigned to regions by the .poly file. If a region is not\n"); - printf( -" explicitly marked by the .poly file, triangles in that region are\n"); - printf( -" assigned an attribute of zero. The -A switch has an effect only\n"); - printf(" when the -p switch is used and the -r switch is not.\n"); - printf( -" -c Creates segments on the convex hull of the triangulation. If you\n"); - printf( -" are triangulating a point set, this switch causes a .poly file to\n"); - printf( -" be written, containing all edges in the convex hull. (By default,\n" -); - printf( -" a .poly file is written only if a .poly file is read.) If you are\n" -); - printf( -" triangulating a PSLG, this switch specifies that the interior of\n"); - printf( -" the convex hull of the PSLG should be triangulated. If you do not\n" -); - printf( -" use this switch when triangulating a PSLG, it is assumed that you\n"); - printf( -" have identified the region to be triangulated by surrounding it\n"); - printf( -" with segments of the input PSLG. Beware: if you are not careful,\n" -); - printf( -" this switch can cause the introduction of an extremely thin angle\n"); - printf( -" between a PSLG segment and a convex hull segment, which can cause\n"); - printf( -" overrefinement or failure if Triangle runs out of precision. If\n"); - printf( -" you are refining a mesh, the -c switch works differently; it\n"); - printf( -" generates the set of boundary edges of the mesh, rather than the\n"); - printf(" convex hull.\n"); - printf( -" -e Outputs (to an .edge file) a list of edges of the triangulation.\n"); - printf( -" -v Outputs the Voronoi diagram associated with the triangulation.\n"); - printf(" Does not attempt to detect degeneracies.\n"); - printf( -" -n Outputs (to a .neigh file) a list of triangles neighboring each\n"); - printf(" triangle.\n"); - printf( -" -g Outputs the mesh to an Object File Format (.off) file, suitable for\n" -); - printf(" viewing with the Geometry Center's Geomview package.\n"); - printf( -" -B No boundary markers in the output .node, .poly, and .edge output\n"); - printf( -" files. See the detailed discussion of boundary markers below.\n"); - printf( -" -P No output .poly file. Saves disk space, but you lose the ability\n"); - printf( -" to impose segment constraints on later refinements of the mesh.\n"); - printf(" -N No output .node file.\n"); - printf(" -E No output .ele file.\n"); - printf( -" -I No iteration numbers. Suppresses the output of .node and .poly\n"); - printf( -" files, so your input files won't be overwritten. (If your input is\n" -); - printf( -" a .poly file only, a .node file will be written.) Cannot be used\n"); - printf( -" with the -r switch, because that would overwrite your input .ele\n"); - printf( -" file. Shouldn't be used with the -s, -q, or -a switch if you are\n"); - printf( -" using a .node file for input, because no .node file will be\n"); - printf(" written, so there will be no record of any added points.\n"); - printf(" -O No holes. Ignores the holes in the .poly file.\n"); - printf( -" -X No exact arithmetic. Normally, Triangle uses exact floating-point\n" -); - printf( -" arithmetic for certain tests if it thinks the inexact tests are not\n" -); - printf( -" accurate enough. Exact arithmetic ensures the robustness of the\n"); - printf( -" triangulation algorithms, despite floating-point roundoff error.\n"); - printf( -" Disabling exact arithmetic with the -X switch will cause a small\n"); - printf( -" improvement in speed and create the possibility (albeit small) that\n" -); - printf( -" Triangle will fail to produce a valid mesh. Not recommended.\n"); - printf( -" -z Numbers all items starting from zero (rather than one). Note that\n" -); - printf( -" this switch is normally overrided by the value used to number the\n"); - printf( -" first point of the input .node or .poly file. However, this switch\n" -); - printf(" is useful when calling Triangle from another program.\n"); - printf( -" -o2 Generates second-order subparametric elements with six nodes each.\n" -); - printf( -" -Y No new points on the boundary. This switch is useful when the mesh\n" -); - printf( -" boundary must be preserved so that it conforms to some adjacent\n"); - printf( -" mesh. Be forewarned that you will probably sacrifice some of the\n"); - printf( -" quality of the mesh; Triangle will try, but the resulting mesh may\n" -); - printf( -" contain triangles of poor aspect ratio. Works well if all the\n"); - printf( -" boundary points are closely spaced. Specify this switch twice\n"); - printf( -" (`-YY') to prevent all segment splitting, including internal\n"); - printf(" boundaries.\n"); - printf( -" -S Specifies the maximum number of Steiner points (points that are not\n" -); - printf( -" in the input, but are added to meet the constraints of minimum\n"); - printf( -" angle and maximum area). The default is to allow an unlimited\n"); - printf( -" number. If you specify this switch with no number after it,\n"); - printf( -" the limit is set to zero. Triangle always adds points at segment\n"); - printf( -" intersections, even if it needs to use more points than the limit\n"); - printf( -" you set. When Triangle inserts segments by splitting (-s), it\n"); - printf( -" always adds enough points to ensure that all the segments appear in\n" -); - printf( -" the triangulation, again ignoring the limit. Be forewarned that\n"); - printf( -" the -S switch may result in a conforming triangulation that is not\n" -); - printf( -" truly Delaunay, because Triangle may be forced to stop adding\n"); - printf( -" points when the mesh is in a state where a segment is non-Delaunay\n" -); - printf( -" and needs to be split. If so, Triangle will print a warning.\n"); - printf( -" -i Uses an incremental rather than divide-and-conquer algorithm to\n"); - printf( -" form a Delaunay triangulation. Try it if the divide-and-conquer\n"); - printf(" algorithm fails.\n"); - printf( -" -F Uses Steven Fortune's sweepline algorithm to form a Delaunay\n"); - printf( -" triangulation. Warning: does not use exact arithmetic for all\n"); - printf(" calculations. An exact result is not guaranteed.\n"); - printf( -" -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n"); - printf( -" default, Triangle uses alternating vertical and horizontal cuts,\n"); - printf( -" which usually improve the speed except with point sets that are\n"); - printf( -" small or short and wide. This switch is primarily of theoretical\n"); - printf(" interest.\n"); - printf( -" -s Specifies that segments should be forced into the triangulation by\n" -); - printf( -" recursively splitting them at their midpoints, rather than by\n"); - printf( -" generating a constrained Delaunay triangulation. Segment splitting\n" -); - printf( -" is true to Ruppert's original algorithm, but can create needlessly\n" -); - printf(" small triangles near external small features.\n"); - printf( -" -C Check the consistency of the final mesh. Uses exact arithmetic for\n" -); - printf( -" checking, even if the -X switch is used. Useful if you suspect\n"); - printf(" Triangle is buggy.\n"); - printf( -" -Q Quiet: Suppresses all explanation of what Triangle is doing, unless\n" -); - printf(" an error occurs.\n"); - printf( -" -V Verbose: Gives detailed information about what Triangle is doing.\n"); - printf( -" Add more `V's for increasing amount of detail. `-V' gives\n"); - printf( -" information on algorithmic progress and more detailed statistics.\n"); - printf( -" `-VV' gives point-by-point details, and will print so much that\n"); - printf( -" Triangle will run much more slowly. `-VVV' gives information only\n" -); - printf(" a debugger could love.\n"); - printf(" -h Help: Displays these instructions.\n"); - printf("\n"); - printf("Definitions:\n"); - printf("\n"); - printf( -" A Delaunay triangulation of a point set is a triangulation whose vertices\n" -); - printf( -" are the point set, having the property that no point in the point set\n"); - printf( -" falls in the interior of the circumcircle (circle that passes through all\n" -); - printf(" three vertices) of any triangle in the triangulation.\n\n"); - printf( -" A Voronoi diagram of a point set is a subdivision of the plane into\n"); - printf( -" polygonal regions (some of which may be infinite), where each region is\n"); - printf( -" the set of points in the plane that are closer to some input point than\n"); - printf( -" to any other input point. (The Voronoi diagram is the geometric dual of\n" -); - printf(" the Delaunay triangulation.)\n\n"); - printf( -" A Planar Straight Line Graph (PSLG) is a collection of points and\n"); - printf( -" segments. Segments are simply edges, whose endpoints are points in the\n"); - printf( -" PSLG. The file format for PSLGs (.poly files) is described below.\n"); - printf("\n"); - printf( -" A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n"); - printf( -" triangulation, but each PSLG segment is present as a single edge in the\n"); - printf( -" triangulation. (A constrained Delaunay triangulation is not truly a\n"); - printf(" Delaunay triangulation.)\n\n"); - printf( -" A conforming Delaunay triangulation of a PSLG is a true Delaunay\n"); - printf( -" triangulation in which each PSLG segment may have been subdivided into\n"); - printf( -" several edges by the insertion of additional points. These inserted\n"); - printf( -" points are necessary to allow the segments to exist in the mesh while\n"); - printf(" maintaining the Delaunay property.\n\n"); - printf("File Formats:\n\n"); - printf( -" All files may contain comments prefixed by the character '#'. Points,\n"); - printf( -" triangles, edges, holes, and maximum area constraints must be numbered\n"); - printf( -" consecutively, starting from either 1 or 0. Whichever you choose, all\n"); - printf( -" input files must be consistent; if the nodes are numbered from 1, so must\n" -); - printf( -" be all other objects. Triangle automatically detects your choice while\n"); - printf( -" reading the .node (or .poly) file. (When calling Triangle from another\n"); - printf( -" program, use the -z switch if you wish to number objects from zero.)\n"); - printf(" Examples of these file formats are given below.\n\n"); - printf(" .node files:\n"); - printf( -" First line: <# of points> <# of attributes>\n"); - printf( -" <# of boundary markers (0 or 1)>\n" -); - printf( -" Remaining lines: [attributes] [boundary marker]\n"); - printf("\n"); - printf( -" The attributes, which are typically floating-point values of physical\n"); - printf( -" quantities (such as mass or conductivity) associated with the nodes of\n" -); - printf( -" a finite element mesh, are copied unchanged to the output mesh. If -s,\n" -); - printf( -" -q, or -a is selected, each new Steiner point added to the mesh will\n"); - printf(" have attributes assigned to it by linear interpolation.\n\n"); - printf( -" If the fourth entry of the first line is `1', the last column of the\n"); - printf( -" remainder of the file is assumed to contain boundary markers. Boundary\n" -); - printf( -" markers are used to identify boundary points and points resting on PSLG\n" -); - printf( -" segments; a complete description appears in a section below. The .node\n" -); - printf( -" file produced by Triangle will contain boundary markers in the last\n"); - printf(" column unless they are suppressed by the -B switch.\n\n"); - printf(" .ele files:\n"); - printf( -" First line: <# of triangles> <# of attributes>\n"); - printf( -" Remaining lines: ... [attributes]\n" -); - printf("\n"); - printf( -" Points are indices into the corresponding .node file. The first three\n" -); - printf( -" points are the corners, and are listed in counterclockwise order around\n" -); - printf( -" each triangle. (The remaining points, if any, depend on the type of\n"); - printf( -" finite element used.) The attributes are just like those of .node\n"); - printf( -" files. Because there is no simple mapping from input to output\n"); - printf( -" triangles, an attempt is made to interpolate attributes, which may\n"); - printf( -" result in a good deal of diffusion of attributes among nearby triangles\n" -); - printf( -" as the triangulation is refined. Diffusion does not occur across\n"); - printf( -" segments, so attributes used to identify segment-bounded regions remain\n" -); - printf( -" intact. In output .ele files, all triangles have three points each\n"); - printf( -" unless the -o2 switch is used, in which case they have six, and the\n"); - printf( -" fourth, fifth, and sixth points lie on the midpoints of the edges\n"); - printf(" opposite the first, second, and third corners.\n\n"); - printf(" .poly files:\n"); - printf( -" First line: <# of points> <# of attributes>\n"); - printf( -" <# of boundary markers (0 or 1)>\n" -); - printf( -" Following lines: [attributes] [boundary marker]\n"); - printf(" One line: <# of segments> <# of boundary markers (0 or 1)>\n"); - printf( -" Following lines: [boundary marker]\n"); - printf(" One line: <# of holes>\n"); - printf(" Following lines: \n"); - printf( -" Optional line: <# of regional attributes and/or area constraints>\n"); - printf( -" Optional following lines: \n"); - printf("\n"); - printf( -" A .poly file represents a PSLG, as well as some additional information.\n" -); - printf( -" The first section lists all the points, and is identical to the format\n" -); - printf( -" of .node files. <# of points> may be set to zero to indicate that the\n" -); - printf( -" points are listed in a separate .node file; .poly files produced by\n"); - printf( -" Triangle always have this format. This has the advantage that a point\n" -); - printf( -" set may easily be triangulated with or without segments. (The same\n"); - printf( -" effect can be achieved, albeit using more disk space, by making a copy\n" -); - printf( -" of the .poly file with the extension .node; all sections of the file\n"); - printf(" but the first are ignored.)\n\n"); - printf( -" The second section lists the segments. Segments are edges whose\n"); - printf( -" presence in the triangulation is enforced. Each segment is specified\n"); - printf( -" by listing the indices of its two endpoints. This means that you must\n" -); - printf( -" include its endpoints in the point list. If -s, -q, and -a are not\n"); - printf( -" selected, Triangle will produce a constrained Delaunay triangulation,\n"); - printf( -" in which each segment appears as a single edge in the triangulation.\n"); - printf( -" If -q or -a is selected, Triangle will produce a conforming Delaunay\n"); - printf( -" triangulation, in which segments may be subdivided into smaller edges.\n" -); - printf(" Each segment, like each point, may have a boundary marker.\n\n"); - printf( -" The third section lists holes (and concavities, if -c is selected) in\n"); - printf( -" the triangulation. Holes are specified by identifying a point inside\n"); - printf( -" each hole. After the triangulation is formed, Triangle creates holes\n"); - printf( -" by eating triangles, spreading out from each hole point until its\n"); - printf( -" progress is blocked by PSLG segments; you must be careful to enclose\n"); - printf( -" each hole in segments, or your whole triangulation may be eaten away.\n"); - printf( -" If the two triangles abutting a segment are eaten, the segment itself\n"); - printf( -" is also eaten. Do not place a hole directly on a segment; if you do,\n"); - printf(" Triangle will choose one side of the segment arbitrarily.\n\n"); - printf( -" The optional fourth section lists regional attributes (to be assigned\n"); - printf( -" to all triangles in a region) and regional constraints on the maximum\n"); - printf( -" triangle area. Triangle will read this section only if the -A switch\n"); - printf( -" is used or the -a switch is used without a number following it, and the\n" -); - printf( -" -r switch is not used. Regional attributes and area constraints are\n"); - printf( -" propagated in the same manner as holes; you specify a point for each\n"); - printf( -" attribute and/or constraint, and the attribute and/or constraint will\n"); - printf( -" affect the whole region (bounded by segments) containing the point. If\n" -); - printf( -" two values are written on a line after the x and y coordinate, the\n"); - printf( -" former is assumed to be a regional attribute (but will only be applied\n" -); - printf( -" if the -A switch is selected), and the latter is assumed to be a\n"); - printf( -" regional area constraint (but will only be applied if the -a switch is\n" -); - printf( -" selected). You may also specify just one value after the coordinates,\n" -); - printf( -" which can serve as both an attribute and an area constraint, depending\n" -); - printf( -" on the choice of switches. If you are using the -A and -a switches\n"); - printf( -" simultaneously and wish to assign an attribute to some region without\n"); - printf(" imposing an area constraint, use a negative maximum area.\n\n"); - printf( -" When a triangulation is created from a .poly file, you must either\n"); - printf( -" enclose the entire region to be triangulated in PSLG segments, or\n"); - printf( -" use the -c switch, which encloses the convex hull of the input point\n"); - printf( -" set. If you do not use the -c switch, Triangle will eat all triangles\n" -); - printf( -" on the outer boundary that are not protected by segments; if you are\n"); - printf( -" not careful, your whole triangulation may be eaten away. If you do\n"); - printf( -" use the -c switch, you can still produce concavities by appropriate\n"); - printf(" placement of holes just inside the convex hull.\n\n"); - printf( -" An ideal PSLG has no intersecting segments, nor any points that lie\n"); - printf( -" upon segments (except, of course, the endpoints of each segment.) You\n" -); - printf( -" aren't required to make your .poly files ideal, but you should be aware\n" -); - printf( -" of what can go wrong. Segment intersections are relatively safe -\n"); - printf( -" Triangle will calculate the intersection points for you and add them to\n" -); - printf( -" the triangulation - as long as your machine's floating-point precision\n" -); - printf( -" doesn't become a problem. You are tempting the fates if you have three\n" -); - printf( -" segments that cross at the same location, and expect Triangle to figure\n" -); - printf( -" out where the intersection point is. Thanks to floating-point roundoff\n" -); - printf( -" error, Triangle will probably decide that the three segments intersect\n" -); - printf( -" at three different points, and you will find a minuscule triangle in\n"); - printf( -" your output - unless Triangle tries to refine the tiny triangle, uses\n"); - printf( -" up the last bit of machine precision, and fails to terminate at all.\n"); - printf( -" You're better off putting the intersection point in the input files,\n"); - printf( -" and manually breaking up each segment into two. Similarly, if you\n"); - printf( -" place a point at the middle of a segment, and hope that Triangle will\n"); - printf( -" break up the segment at that point, you might get lucky. On the other\n" -); - printf( -" hand, Triangle might decide that the point doesn't lie precisely on the\n" -); - printf( -" line, and you'll have a needle-sharp triangle in your output - or a lot\n" -); - printf(" of tiny triangles if you're generating a quality mesh.\n\n"); - printf( -" When Triangle reads a .poly file, it also writes a .poly file, which\n"); - printf( -" includes all edges that are part of input segments. If the -c switch\n"); - printf( -" is used, the output .poly file will also include all of the edges on\n"); - printf( -" the convex hull. Hence, the output .poly file is useful for finding\n"); - printf( -" edges associated with input segments and setting boundary conditions in\n" -); - printf( -" finite element simulations. More importantly, you will need it if you\n" -); - printf( -" plan to refine the output mesh, and don't want segments to be missing\n"); - printf(" in later triangulations.\n\n"); - printf(" .area files:\n"); - printf(" First line: <# of triangles>\n"); - printf(" Following lines: \n\n"); - printf( -" An .area file associates with each triangle a maximum area that is used\n" -); - printf( -" for mesh refinement. As with other file formats, every triangle must\n"); - printf( -" be represented, and they must be numbered consecutively. A triangle\n"); - printf( -" may be left unconstrained by assigning it a negative maximum area.\n"); - printf("\n"); - printf(" .edge files:\n"); - printf(" First line: <# of edges> <# of boundary markers (0 or 1)>\n"); - printf( -" Following lines: [boundary marker]\n"); - printf("\n"); - printf( -" Endpoints are indices into the corresponding .node file. Triangle can\n" -); - printf( -" produce .edge files (use the -e switch), but cannot read them. The\n"); - printf( -" optional column of boundary markers is suppressed by the -B switch.\n"); - printf("\n"); - printf( -" In Voronoi diagrams, one also finds a special kind of edge that is an\n"); - printf( -" infinite ray with only one endpoint. For these edges, a different\n"); - printf(" format is used:\n\n"); - printf(" -1 \n\n"); - printf( -" The `direction' is a floating-point vector that indicates the direction\n" -); - printf(" of the infinite ray.\n\n"); - printf(" .neigh files:\n"); - printf( -" First line: <# of triangles> <# of neighbors per triangle (always 3)>\n" -); - printf( -" Following lines: \n"); - printf("\n"); - printf( -" Neighbors are indices into the corresponding .ele file. An index of -1\n" -); - printf( -" indicates a mesh boundary, and therefore no neighbor. Triangle can\n"); - printf( -" produce .neigh files (use the -n switch), but cannot read them.\n"); - printf("\n"); - printf( -" The first neighbor of triangle i is opposite the first corner of\n"); - printf(" triangle i, and so on.\n\n"); - printf("Boundary Markers:\n\n"); - printf( -" Boundary markers are tags used mainly to identify which output points and\n" -); - printf( -" edges are associated with which PSLG segment, and to identify which\n"); - printf( -" points and edges occur on a boundary of the triangulation. A common use\n" -); - printf( -" is to determine where boundary conditions should be applied to a finite\n"); - printf( -" element mesh. You can prevent boundary markers from being written into\n"); - printf(" files produced by Triangle by using the -B switch.\n\n"); - printf( -" The boundary marker associated with each segment in an output .poly file\n" -); - printf(" or edge in an output .edge file is chosen as follows:\n"); - printf( -" - If an output edge is part or all of a PSLG segment with a nonzero\n"); - printf( -" boundary marker, then the edge is assigned the same marker.\n"); - printf( -" - Otherwise, if the edge occurs on a boundary of the triangulation\n"); - printf( -" (including boundaries of holes), then the edge is assigned the marker\n" -); - printf(" one (1).\n"); - printf(" - Otherwise, the edge is assigned the marker zero (0).\n"); - printf( -" The boundary marker associated with each point in an output .node file is\n" -); - printf(" chosen as follows:\n"); - printf( -" - If a point is assigned a nonzero boundary marker in the input file,\n"); - printf( -" then it is assigned the same marker in the output .node file.\n"); - printf( -" - Otherwise, if the point lies on a PSLG segment (including the\n"); - printf( -" segment's endpoints) with a nonzero boundary marker, then the point\n"); - printf( -" is assigned the same marker. If the point lies on several such\n"); - printf(" segments, one of the markers is chosen arbitrarily.\n"); - printf( -" - Otherwise, if the point occurs on a boundary of the triangulation,\n"); - printf(" then the point is assigned the marker one (1).\n"); - printf(" - Otherwise, the point is assigned the marker zero (0).\n"); - printf("\n"); - printf( -" If you want Triangle to determine for you which points and edges are on\n"); - printf( -" the boundary, assign them the boundary marker zero (or use no markers at\n" -); - printf( -" all) in your input files. Alternatively, you can mark some of them and\n"); - printf(" leave others marked zero, allowing Triangle to label them.\n\n"); - printf("Triangulation Iteration Numbers:\n\n"); - printf( -" Because Triangle can read and refine its own triangulations, input\n"); - printf( -" and output files have iteration numbers. For instance, Triangle might\n"); - printf( -" read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n"); - printf( -" triangulation, and output the files mesh.4.node, mesh.4.ele, and\n"); - printf(" mesh.4.poly. Files with no iteration number are treated as if\n"); - printf( -" their iteration number is zero; hence, Triangle might read the file\n"); - printf( -" points.node, triangulate it, and produce the files points.1.node and\n"); - printf(" points.1.ele.\n\n"); - printf( -" Iteration numbers allow you to create a sequence of successively finer\n"); - printf( -" meshes suitable for multigrid methods. They also allow you to produce a\n" -); - printf( -" sequence of meshes using error estimate-driven mesh refinement.\n"); - printf("\n"); - printf( -" If you're not using refinement or quality meshing, and you don't like\n"); - printf( -" iteration numbers, use the -I switch to disable them. This switch will\n"); - printf( -" also disable output of .node and .poly files to prevent your input files\n" -); - printf( -" from being overwritten. (If the input is a .poly file that contains its\n" -); - printf(" own points, a .node file will be written.)\n\n"); - printf("Examples of How to Use Triangle:\n\n"); - printf( -" `triangle dots' will read points from dots.node, and write their Delaunay\n" -); - printf( -" triangulation to dots.1.node and dots.1.ele. (dots.1.node will be\n"); - printf( -" identical to dots.node.) `triangle -I dots' writes the triangulation to\n" -); - printf( -" dots.ele instead. (No additional .node file is needed, so none is\n"); - printf(" written.)\n\n"); - printf( -" `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n" -); - printf( -" object.1.node, if the points are omitted from object.1.poly) and write\n"); - printf(" their constrained Delaunay triangulation to object.2.node and\n"); - printf( -" object.2.ele. The segments will be copied to object.2.poly, and all\n"); - printf(" edges will be written to object.2.edge.\n\n"); - printf( -" `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n"); - printf( -" possibly object.node), generate a mesh whose angles are all greater than\n" -); - printf( -" 31.5 degrees and whose triangles all have area smaller than 0.1, and\n"); - printf( -" write the mesh to object.1.node and object.1.ele. Each segment may have\n" -); - printf( -" been broken up into multiple edges; the resulting constrained edges are\n"); - printf(" written to object.1.poly.\n\n"); - printf( -" Here is a sample file `box.poly' describing a square with a square hole:\n" -); - printf("\n"); - printf( -" # A box with eight points in 2D, no attributes, one boundary marker.\n"); - printf(" 8 2 0 1\n"); - printf(" # Outer box has these vertices:\n"); - printf(" 1 0 0 0\n"); - printf(" 2 0 3 0\n"); - printf(" 3 3 0 0\n"); - printf(" 4 3 3 33 # A special marker for this point.\n"); - printf(" # Inner square has these vertices:\n"); - printf(" 5 1 1 0\n"); - printf(" 6 1 2 0\n"); - printf(" 7 2 1 0\n"); - printf(" 8 2 2 0\n"); - printf(" # Five segments with boundary markers.\n"); - printf(" 5 1\n"); - printf(" 1 1 2 5 # Left side of outer box.\n"); - printf(" 2 5 7 0 # Segments 2 through 5 enclose the hole.\n"); - printf(" 3 7 8 0\n"); - printf(" 4 8 6 10\n"); - printf(" 5 6 5 0\n"); - printf(" # One hole in the middle of the inner square.\n"); - printf(" 1\n"); - printf(" 1 1.5 1.5\n\n"); - printf( -" Note that some segments are missing from the outer square, so one must\n"); - printf( -" use the `-c' switch. After `triangle -pqc box.poly', here is the output\n" -); - printf( -" file `box.1.node', with twelve points. The last four points were added\n"); - printf( -" to meet the angle constraint. Points 1, 2, and 9 have markers from\n"); - printf( -" segment 1. Points 6 and 8 have markers from segment 4. All the other\n"); - printf( -" points but 4 have been marked to indicate that they lie on a boundary.\n"); - printf("\n"); - printf(" 12 2 0 1\n"); - printf(" 1 0 0 5\n"); - printf(" 2 0 3 5\n"); - printf(" 3 3 0 1\n"); - printf(" 4 3 3 33\n"); - printf(" 5 1 1 1\n"); - printf(" 6 1 2 10\n"); - printf(" 7 2 1 1\n"); - printf(" 8 2 2 10\n"); - printf(" 9 0 1.5 5\n"); - printf(" 10 1.5 0 1\n"); - printf(" 11 3 1.5 1\n"); - printf(" 12 1.5 3 1\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf(" Here is the output file `box.1.ele', with twelve triangles.\n\n"); - printf(" 12 3 0\n"); - printf(" 1 5 6 9\n"); - printf(" 2 10 3 7\n"); - printf(" 3 6 8 12\n"); - printf(" 4 9 1 5\n"); - printf(" 5 6 2 9\n"); - printf(" 6 7 3 11\n"); - printf(" 7 11 4 8\n"); - printf(" 8 7 5 10\n"); - printf(" 9 12 2 6\n"); - printf(" 10 8 7 11\n"); - printf(" 11 5 1 10\n"); - printf(" 12 8 4 12\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf( -" Here is the output file `box.1.poly'. Note that segments have been added\n" -); - printf( -" to represent the convex hull, and some segments have been split by newly\n" -); - printf( -" added points. Note also that <# of points> is set to zero to indicate\n"); - printf(" that the points should be read from the .node file.\n\n"); - printf(" 0 2 0 1\n"); - printf(" 12 1\n"); - printf(" 1 1 9 5\n"); - printf(" 2 5 7 1\n"); - printf(" 3 8 7 1\n"); - printf(" 4 6 8 10\n"); - printf(" 5 5 6 1\n"); - printf(" 6 3 10 1\n"); - printf(" 7 4 11 1\n"); - printf(" 8 2 12 1\n"); - printf(" 9 9 2 5\n"); - printf(" 10 10 1 1\n"); - printf(" 11 11 3 1\n"); - printf(" 12 12 4 1\n"); - printf(" 1\n"); - printf(" 1 1.5 1.5\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf("Refinement and Area Constraints:\n\n"); - printf( -" The -r switch causes a mesh (.node and .ele files) to be read and\n"); - printf( -" refined. If the -p switch is also used, a .poly file is read and used to\n" -); - printf( -" specify edges that are constrained and cannot be eliminated (although\n"); - printf( -" they can be divided into smaller edges) by the refinement process.\n"); - printf("\n"); - printf( -" When you refine a mesh, you generally want to impose tighter quality\n"); - printf( -" constraints. One way to accomplish this is to use -q with a larger\n"); - printf( -" angle, or -a followed by a smaller area than you used to generate the\n"); - printf( -" mesh you are refining. Another way to do this is to create an .area\n"); - printf( -" file, which specifies a maximum area for each triangle, and use the -a\n"); - printf( -" switch (without a number following). Each triangle's area constraint is\n" -); - printf( -" applied to that triangle. Area constraints tend to diffuse as the mesh\n"); - printf( -" is refined, so if there are large variations in area constraint between\n"); - printf(" adjacent triangles, you may not get the results you want.\n\n"); - printf( -" If you are refining a mesh composed of linear (three-node) elements, the\n" -); - printf( -" output mesh will contain all the nodes present in the input mesh, in the\n" -); - printf( -" same order, with new nodes added at the end of the .node file. However,\n" -); - printf( -" there is no guarantee that each output element is contained in a single\n"); - printf( -" input element. Often, output elements will overlap two input elements,\n"); - printf( -" and input edges are not present in the output mesh. Hence, a sequence of\n" -); - printf( -" refined meshes will form a hierarchy of nodes, but not a hierarchy of\n"); - printf( -" elements. If you a refining a mesh of higher-order elements, the\n"); - printf( -" hierarchical property applies only to the nodes at the corners of an\n"); - printf(" element; other nodes may not be present in the refined mesh.\n\n"); - printf( -" It is important to understand that maximum area constraints in .poly\n"); - printf( -" files are handled differently from those in .area files. A maximum area\n" -); - printf( -" in a .poly file applies to the whole (segment-bounded) region in which a\n" -); - printf( -" point falls, whereas a maximum area in an .area file applies to only one\n" -); - printf( -" triangle. Area constraints in .poly files are used only when a mesh is\n"); - printf( -" first generated, whereas area constraints in .area files are used only to\n" -); - printf( -" refine an existing mesh, and are typically based on a posteriori error\n"); - printf( -" estimates resulting from a finite element simulation on that mesh.\n"); - printf("\n"); - printf( -" `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n" -); - printf( -" refine the triangulation to enforce a 25 degree minimum angle, and then\n"); - printf( -" write the refined triangulation to object.2.node and object.2.ele.\n"); - printf("\n"); - printf( -" `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n"); - printf( -" z.3.area. After reconstructing the mesh and its segments, Triangle will\n" -); - printf( -" refine the mesh so that no triangle has area greater than 6.2, and\n"); - printf( -" furthermore the triangles satisfy the maximum area constraints in\n"); - printf( -" z.3.area. The output is written to z.4.node, z.4.ele, and z.4.poly.\n"); - printf("\n"); - printf( -" The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n"); - printf( -" x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n"); - printf(" suitable for multigrid.\n\n"); - printf("Convex Hulls and Mesh Boundaries:\n\n"); - printf( -" If the input is a point set (rather than a PSLG), Triangle produces its\n"); - printf( -" convex hull as a by-product in the output .poly file if you use the -c\n"); - printf( -" switch. There are faster algorithms for finding a two-dimensional convex\n" -); - printf( -" hull than triangulation, of course, but this one comes for free. If the\n" -); - printf( -" input is an unconstrained mesh (you are using the -r switch but not the\n"); - printf( -" -p switch), Triangle produces a list of its boundary edges (including\n"); - printf(" hole boundaries) as a by-product if you use the -c switch.\n\n"); - printf("Voronoi Diagrams:\n\n"); - printf( -" The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n"); - printf( -" .v.edge. For example, `triangle -v points' will read points.node,\n"); - printf( -" produce its Delaunay triangulation in points.1.node and points.1.ele,\n"); - printf( -" and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n"); - printf( -" The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n" -); - printf( -" file contains a list of all Voronoi edges, some of which may be infinite\n" -); - printf( -" rays. (The choice of filenames makes it easy to run the set of Voronoi\n"); - printf(" vertices through Triangle, if so desired.)\n\n"); - printf( -" This implementation does not use exact arithmetic to compute the Voronoi\n" -); - printf( -" vertices, and does not check whether neighboring vertices are identical.\n" -); - printf( -" Be forewarned that if the Delaunay triangulation is degenerate or\n"); - printf( -" near-degenerate, the Voronoi diagram may have duplicate points, crossing\n" -); - printf( -" edges, or infinite rays whose direction vector is zero. Also, if you\n"); - printf( -" generate a constrained (as opposed to conforming) Delaunay triangulation,\n" -); - printf( -" or if the triangulation has holes, the corresponding Voronoi diagram is\n"); - printf(" likely to have crossing edges and unlikely to make sense.\n\n"); - printf("Mesh Topology:\n\n"); - printf( -" You may wish to know which triangles are adjacent to a certain Delaunay\n"); - printf( -" edge in an .edge file, which Voronoi regions are adjacent to a certain\n"); - printf( -" Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n" -); - printf( -" each other. All of this information can be found by cross-referencing\n"); - printf( -" output files with the recollection that the Delaunay triangulation and\n"); - printf(" the Voronoi diagrams are planar duals.\n\n"); - printf( -" Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n"); - printf( -" the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n"); - printf( -" wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n"); - printf( -" vertex j of the corresponding .v.node file; and Voronoi region k is the\n"); - printf(" dual of point k of the corresponding .node file.\n\n"); - printf( -" Hence, to find the triangles adjacent to a Delaunay edge, look at the\n"); - printf( -" vertices of the corresponding Voronoi edge; their dual triangles are on\n"); - printf( -" the left and right of the Delaunay edge, respectively. To find the\n"); - printf( -" Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n" -); - printf( -" corresponding Delaunay edge; their dual regions are on the right and left\n" -); - printf( -" of the Voronoi edge, respectively. To find which Voronoi regions are\n"); - printf(" adjacent to each other, just read the list of Delaunay edges.\n"); - printf("\n"); - printf("Statistics:\n"); - printf("\n"); - printf( -" After generating a mesh, Triangle prints a count of the number of points,\n" -); - printf( -" triangles, edges, boundary edges, and segments in the output mesh. If\n"); - printf( -" you've forgotten the statistics for an existing mesh, the -rNEP switches\n" -); - printf( -" (or -rpNEP if you've got a .poly file for the existing mesh) will\n"); - printf(" regenerate these statistics without writing any output.\n\n"); - printf( -" The -V switch produces extended statistics, including a rough estimate\n"); - printf( -" of memory use and a histogram of triangle aspect ratios and angles in the\n" -); - printf(" mesh.\n\n"); - printf("Exact Arithmetic:\n\n"); - printf( -" Triangle uses adaptive exact arithmetic to perform what computational\n"); - printf( -" geometers call the `orientation' and `incircle' tests. If the floating-\n" -); - printf( -" point arithmetic of your machine conforms to the IEEE 754 standard (as\n"); - printf( -" most workstations do), and does not use extended precision internal\n"); - printf( -" registers, then your output is guaranteed to be an absolutely true\n"); - printf(" Delaunay or conforming Delaunay triangulation, roundoff error\n"); - printf( -" notwithstanding. The word `adaptive' implies that these arithmetic\n"); - printf( -" routines compute the result only to the precision necessary to guarantee\n" -); - printf( -" correctness, so they are usually nearly as fast as their approximate\n"); - printf( -" counterparts. The exact tests can be disabled with the -X switch. On\n"); - printf( -" most inputs, this switch will reduce the computation time by about eight\n" -); - printf( -" percent - it's not worth the risk. There are rare difficult inputs\n"); - printf( -" (having many collinear and cocircular points), however, for which the\n"); - printf( -" difference could be a factor of two. These are precisely the inputs most\n" -); - printf(" likely to cause errors if you use the -X switch.\n\n"); - printf( -" Unfortunately, these routines don't solve every numerical problem. Exact\n" -); - printf( -" arithmetic is not used to compute the positions of points, because the\n"); - printf( -" bit complexity of point coordinates would grow without bound. Hence,\n"); - printf( -" segment intersections aren't computed exactly; in very unusual cases,\n"); - printf( -" roundoff error in computing an intersection point might actually lead to\n" -); - printf( -" an inverted triangle and an invalid triangulation. (This is one reason\n"); - printf( -" to compute your own intersection points in your .poly files.) Similarly,\n" -); - printf( -" exact arithmetic is not used to compute the vertices of the Voronoi\n"); - printf(" diagram.\n\n"); - printf( -" Underflow and overflow can also cause difficulties; the exact arithmetic\n" -); - printf( -" routines do not ameliorate out-of-bounds exponents, which can arise\n"); - printf( -" during the orientation and incircle tests. As a rule of thumb, you\n"); - printf( -" should ensure that your input values are within a range such that their\n"); - printf( -" third powers can be taken without underflow or overflow. Underflow can\n"); - printf( -" silently prevent the tests from being performed exactly, while overflow\n"); - printf(" will typically cause a floating exception.\n\n"); - printf("Calling Triangle from Another Program:\n\n"); - printf(" Read the file triangle.h for details.\n\n"); - printf("Troubleshooting:\n\n"); - printf(" Please read this section before mailing me bugs.\n\n"); - printf(" `My output mesh has no triangles!'\n\n"); - printf( -" If you're using a PSLG, you've probably failed to specify a proper set\n" -); - printf( -" of bounding segments, or forgotten to use the -c switch. Or you may\n"); - printf( -" have placed a hole badly. To test these possibilities, try again with\n" -); - printf( -" the -c and -O switches. Alternatively, all your input points may be\n"); - printf( -" collinear, in which case you can hardly expect to triangulate them.\n"); - printf("\n"); - printf(" `Triangle doesn't terminate, or just crashes.'\n"); - printf("\n"); - printf( -" Bad things can happen when triangles get so small that the distance\n"); - printf( -" between their vertices isn't much larger than the precision of your\n"); - printf( -" machine's arithmetic. If you've compiled Triangle for single-precision\n" -); - printf( -" arithmetic, you might do better by recompiling it for double-precision.\n" -); - printf( -" Then again, you might just have to settle for more lenient constraints\n" -); - printf( -" on the minimum angle and the maximum area than you had planned.\n"); - printf("\n"); - printf( -" You can minimize precision problems by ensuring that the origin lies\n"); - printf( -" inside your point set, or even inside the densest part of your\n"); - printf( -" mesh. On the other hand, if you're triangulating an object whose x\n"); - printf( -" coordinates all fall between 6247133 and 6247134, you're not leaving\n"); - printf(" much floating-point precision for Triangle to work with.\n\n"); - printf( -" Precision problems can occur covertly if the input PSLG contains two\n"); - printf( -" segments that meet (or intersect) at a very small angle, or if such an\n" -); - printf( -" angle is introduced by the -c switch, which may occur if a point lies\n"); - printf( -" ever-so-slightly inside the convex hull, and is connected by a PSLG\n"); - printf( -" segment to a point on the convex hull. If you don't realize that a\n"); - printf( -" small angle is being formed, you might never discover why Triangle is\n"); - printf( -" crashing. To check for this possibility, use the -S switch (with an\n"); - printf( -" appropriate limit on the number of Steiner points, found by trial-and-\n" -); - printf( -" error) to stop Triangle early, and view the output .poly file with\n"); - printf( -" Show Me (described below). Look carefully for small angles between\n"); - printf( -" segments; zoom in closely, as such segments might look like a single\n"); - printf(" segment from a distance.\n\n"); - printf( -" If some of the input values are too large, Triangle may suffer a\n"); - printf( -" floating exception due to overflow when attempting to perform an\n"); - printf( -" orientation or incircle test. (Read the section on exact arithmetic\n"); - printf( -" above.) Again, I recommend compiling Triangle for double (rather\n"); - printf(" than single) precision arithmetic.\n\n"); - printf( -" `The numbering of the output points doesn't match the input points.'\n"); - printf("\n"); - printf( -" You may have eaten some of your input points with a hole, or by placing\n" -); - printf(" them outside the area enclosed by segments.\n\n"); - printf( -" `Triangle executes without incident, but when I look at the resulting\n"); - printf( -" mesh, it has overlapping triangles or other geometric inconsistencies.'\n"); - printf("\n"); - printf( -" If you select the -X switch, Triangle's divide-and-conquer Delaunay\n"); - printf( -" triangulation algorithm occasionally makes mistakes due to floating-\n"); - printf( -" point roundoff error. Although these errors are rare, don't use the -X\n" -); - printf(" switch. If you still have problems, please report the bug.\n"); - printf("\n"); - printf( -" Strange things can happen if you've taken liberties with your PSLG. Do\n"); - printf( -" you have a point lying in the middle of a segment? Triangle sometimes\n"); - printf( -" copes poorly with that sort of thing. Do you want to lay out a collinear\n" -); - printf( -" row of evenly spaced, segment-connected points? Have you simply defined\n" -); - printf( -" one long segment connecting the leftmost point to the rightmost point,\n"); - printf( -" and a bunch of points lying along it? This method occasionally works,\n"); - printf( -" especially with horizontal and vertical lines, but often it doesn't, and\n" -); - printf( -" you'll have to connect each adjacent pair of points with a separate\n"); - printf(" segment. If you don't like it, tough.\n\n"); - printf( -" Furthermore, if you have segments that intersect other than at their\n"); - printf( -" endpoints, try not to let the intersections fall extremely close to PSLG\n" -); - printf(" points or each other.\n\n"); - printf( -" If you have problems refining a triangulation not produced by Triangle:\n"); - printf( -" Are you sure the triangulation is geometrically valid? Is it formatted\n"); - printf( -" correctly for Triangle? Are the triangles all listed so the first three\n" -); - printf(" points are their corners in counterclockwise order?\n\n"); - printf("Show Me:\n\n"); - printf( -" Triangle comes with a separate program named `Show Me', whose primary\n"); - printf( -" purpose is to draw meshes on your screen or in PostScript. Its secondary\n" -); - printf( -" purpose is to check the validity of your input files, and do so more\n"); - printf( -" thoroughly than Triangle does. Show Me requires that you have the X\n"); - printf( -" Windows system. If you didn't receive Show Me with Triangle, complain to\n" -); - printf(" whomever you obtained Triangle from, then send me mail.\n\n"); - printf("Triangle on the Web:\n\n"); - printf( -" To see an illustrated, updated version of these instructions, check out\n"); - printf("\n"); - printf(" http://www.cs.cmu.edu/~quake/triangle.html\n"); - printf("\n"); - printf("A Brief Plea:\n"); - printf("\n"); - printf( -" If you use Triangle, and especially if you use it to accomplish real\n"); - printf( -" work, I would like very much to hear from you. A short letter or email\n"); - printf( -" (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n"); - printf( -" me. The more people I know are using this program, the more easily I can\n" -); - printf( -" justify spending time on improvements and on the three-dimensional\n"); - printf( -" successor to Triangle, which in turn will benefit you. Also, I can put\n"); - printf( -" you on a list to receive email whenever a new version of Triangle is\n"); - printf(" available.\n\n"); - printf( -" If you use a mesh generated by Triangle in a publication, please include\n" -); - printf(" an acknowledgment as well.\n\n"); - printf("Research credit:\n\n"); - printf( -" Of course, I can take credit for only a fraction of the ideas that made\n"); - printf( -" this mesh generator possible. Triangle owes its existence to the efforts\n" -); - printf( -" of many fine computational geometers and other researchers, including\n"); - printf( -" Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n"); - printf( -" Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n"); - printf( -" Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n"); - printf( -" Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n" -); - printf( -" J. Van Wyk, David F. Watson, and Binhai Zhu. See the comments at the\n"); - printf(" beginning of the source code for references.\n\n"); - exit(0); + printf( + "Underscores indicate that numbers may optionally follow certain switches;\n" ); + printf( + "do not leave any space between a switch and its numeric parameter.\n" ); + printf( + "input_file must be a file with extension .node, or extension .poly if the\n" ); + printf( + "-p switch is used. If -r is used, you must supply .node and .ele files,\n" ); + printf( + "and possibly a .poly file and .area file as well. The formats of these\n" ); + printf( "files are described below.\n\n" ); + printf( "Command Line Switches:\n\n" ); + printf( + " -p Reads a Planar Straight Line Graph (.poly file), which can specify\n" + ); + printf( + " points, segments, holes, and regional attributes and area\n" ); + printf( + " constraints. Will generate a constrained Delaunay triangulation\n" ); + printf( + " fitting the input; or, if -s, -q, or -a is used, a conforming\n" ); + printf( + " Delaunay triangulation. If -p is not used, Triangle reads a .node\n" + ); + printf( " file by default.\n" ); + printf( + " -r Refines a previously generated mesh. The mesh is read from a .node\n" + ); + printf( + " file and an .ele file. If -p is also used, a .poly file is read\n" ); + printf( + " and used to constrain edges in the mesh. Further details on\n" ); + printf( " refinement are given below.\n" ); + printf( + " -q Quality mesh generation by Jim Ruppert's Delaunay refinement\n" ); + printf( + " algorithm. Adds points to the mesh to ensure that no angles\n" ); + printf( + " smaller than 20 degrees occur. An alternative minimum angle may be\n" + ); + printf( + " specified after the `q'. If the minimum angle is 20.7 degrees or\n" ); + printf( + " smaller, the triangulation algorithm is theoretically guaranteed to\n" + ); + printf( + " terminate (assuming infinite precision arithmetic - Triangle may\n" ); + printf( + " fail to terminate if you run out of precision). In practice, the\n" ); + printf( + " algorithm often succeeds for minimum angles up to 33.8 degrees.\n" ); + printf( + " For highly refined meshes, however, it may be necessary to reduce\n" ); + printf( + " the minimum angle to well below 20 to avoid problems associated\n" ); + printf( + " with insufficient floating-point precision. The specified angle\n" ); + printf( " may include a decimal point.\n" ); + printf( + " -a Imposes a maximum triangle area. If a number follows the `a', no\n" ); + printf( + " triangle will be generated whose area is larger than that number.\n" ); + printf( + " If no number is specified, an .area file (if -r is used) or .poly\n" ); + printf( + " file (if -r is not used) specifies a number of maximum area\n" ); + printf( + " constraints. An .area file contains a separate area constraint for\n" + ); + printf( + " each triangle, and is useful for refining a finite element mesh\n" ); + printf( + " based on a posteriori error estimates. A .poly file can optionally\n" + ); + printf( + " contain an area constraint for each segment-bounded region, thereby\n" + ); + printf( + " enforcing triangle densities in a first triangulation. You can\n" ); + printf( + " impose both a fixed area constraint and a varying area constraint\n" ); + printf( + " by invoking the -a switch twice, once with and once without a\n" ); + printf( + " number following. Each area specified may include a decimal point.\n" + ); + printf( + " -A Assigns an additional attribute to each triangle that identifies\n" ); + printf( + " what segment-bounded region each triangle belongs to. Attributes\n" ); + printf( + " are assigned to regions by the .poly file. If a region is not\n" ); + printf( + " explicitly marked by the .poly file, triangles in that region are\n" ); + printf( + " assigned an attribute of zero. The -A switch has an effect only\n" ); + printf( " when the -p switch is used and the -r switch is not.\n" ); + printf( + " -c Creates segments on the convex hull of the triangulation. If you\n" ); + printf( + " are triangulating a point set, this switch causes a .poly file to\n" ); + printf( + " be written, containing all edges in the convex hull. (By default,\n" + ); + printf( + " a .poly file is written only if a .poly file is read.) If you are\n" + ); + printf( + " triangulating a PSLG, this switch specifies that the interior of\n" ); + printf( + " the convex hull of the PSLG should be triangulated. If you do not\n" + ); + printf( + " use this switch when triangulating a PSLG, it is assumed that you\n" ); + printf( + " have identified the region to be triangulated by surrounding it\n" ); + printf( + " with segments of the input PSLG. Beware: if you are not careful,\n" + ); + printf( + " this switch can cause the introduction of an extremely thin angle\n" ); + printf( + " between a PSLG segment and a convex hull segment, which can cause\n" ); + printf( + " overrefinement or failure if Triangle runs out of precision. If\n" ); + printf( + " you are refining a mesh, the -c switch works differently; it\n" ); + printf( + " generates the set of boundary edges of the mesh, rather than the\n" ); + printf( " convex hull.\n" ); + printf( + " -e Outputs (to an .edge file) a list of edges of the triangulation.\n" ); + printf( + " -v Outputs the Voronoi diagram associated with the triangulation.\n" ); + printf( " Does not attempt to detect degeneracies.\n" ); + printf( + " -n Outputs (to a .neigh file) a list of triangles neighboring each\n" ); + printf( " triangle.\n" ); + printf( + " -g Outputs the mesh to an Object File Format (.off) file, suitable for\n" + ); + printf( " viewing with the Geometry Center's Geomview package.\n" ); + printf( + " -B No boundary markers in the output .node, .poly, and .edge output\n" ); + printf( + " files. See the detailed discussion of boundary markers below.\n" ); + printf( + " -P No output .poly file. Saves disk space, but you lose the ability\n" ); + printf( + " to impose segment constraints on later refinements of the mesh.\n" ); + printf( " -N No output .node file.\n" ); + printf( " -E No output .ele file.\n" ); + printf( + " -I No iteration numbers. Suppresses the output of .node and .poly\n" ); + printf( + " files, so your input files won't be overwritten. (If your input is\n" + ); + printf( + " a .poly file only, a .node file will be written.) Cannot be used\n" ); + printf( + " with the -r switch, because that would overwrite your input .ele\n" ); + printf( + " file. Shouldn't be used with the -s, -q, or -a switch if you are\n" ); + printf( + " using a .node file for input, because no .node file will be\n" ); + printf( " written, so there will be no record of any added points.\n" ); + printf( " -O No holes. Ignores the holes in the .poly file.\n" ); + printf( + " -X No exact arithmetic. Normally, Triangle uses exact floating-point\n" + ); + printf( + " arithmetic for certain tests if it thinks the inexact tests are not\n" + ); + printf( + " accurate enough. Exact arithmetic ensures the robustness of the\n" ); + printf( + " triangulation algorithms, despite floating-point roundoff error.\n" ); + printf( + " Disabling exact arithmetic with the -X switch will cause a small\n" ); + printf( + " improvement in speed and create the possibility (albeit small) that\n" + ); + printf( + " Triangle will fail to produce a valid mesh. Not recommended.\n" ); + printf( + " -z Numbers all items starting from zero (rather than one). Note that\n" + ); + printf( + " this switch is normally overrided by the value used to number the\n" ); + printf( + " first point of the input .node or .poly file. However, this switch\n" + ); + printf( " is useful when calling Triangle from another program.\n" ); + printf( + " -o2 Generates second-order subparametric elements with six nodes each.\n" + ); + printf( + " -Y No new points on the boundary. This switch is useful when the mesh\n" + ); + printf( + " boundary must be preserved so that it conforms to some adjacent\n" ); + printf( + " mesh. Be forewarned that you will probably sacrifice some of the\n" ); + printf( + " quality of the mesh; Triangle will try, but the resulting mesh may\n" + ); + printf( + " contain triangles of poor aspect ratio. Works well if all the\n" ); + printf( + " boundary points are closely spaced. Specify this switch twice\n" ); + printf( + " (`-YY') to prevent all segment splitting, including internal\n" ); + printf( " boundaries.\n" ); + printf( + " -S Specifies the maximum number of Steiner points (points that are not\n" + ); + printf( + " in the input, but are added to meet the constraints of minimum\n" ); + printf( + " angle and maximum area). The default is to allow an unlimited\n" ); + printf( + " number. If you specify this switch with no number after it,\n" ); + printf( + " the limit is set to zero. Triangle always adds points at segment\n" ); + printf( + " intersections, even if it needs to use more points than the limit\n" ); + printf( + " you set. When Triangle inserts segments by splitting (-s), it\n" ); + printf( + " always adds enough points to ensure that all the segments appear in\n" + ); + printf( + " the triangulation, again ignoring the limit. Be forewarned that\n" ); + printf( + " the -S switch may result in a conforming triangulation that is not\n" + ); + printf( + " truly Delaunay, because Triangle may be forced to stop adding\n" ); + printf( + " points when the mesh is in a state where a segment is non-Delaunay\n" + ); + printf( + " and needs to be split. If so, Triangle will print a warning.\n" ); + printf( + " -i Uses an incremental rather than divide-and-conquer algorithm to\n" ); + printf( + " form a Delaunay triangulation. Try it if the divide-and-conquer\n" ); + printf( " algorithm fails.\n" ); + printf( + " -F Uses Steven Fortune's sweepline algorithm to form a Delaunay\n" ); + printf( + " triangulation. Warning: does not use exact arithmetic for all\n" ); + printf( " calculations. An exact result is not guaranteed.\n" ); + printf( + " -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n" ); + printf( + " default, Triangle uses alternating vertical and horizontal cuts,\n" ); + printf( + " which usually improve the speed except with point sets that are\n" ); + printf( + " small or short and wide. This switch is primarily of theoretical\n" ); + printf( " interest.\n" ); + printf( + " -s Specifies that segments should be forced into the triangulation by\n" + ); + printf( + " recursively splitting them at their midpoints, rather than by\n" ); + printf( + " generating a constrained Delaunay triangulation. Segment splitting\n" + ); + printf( + " is true to Ruppert's original algorithm, but can create needlessly\n" + ); + printf( " small triangles near external small features.\n" ); + printf( + " -C Check the consistency of the final mesh. Uses exact arithmetic for\n" + ); + printf( + " checking, even if the -X switch is used. Useful if you suspect\n" ); + printf( " Triangle is buggy.\n" ); + printf( + " -Q Quiet: Suppresses all explanation of what Triangle is doing, unless\n" + ); + printf( " an error occurs.\n" ); + printf( + " -V Verbose: Gives detailed information about what Triangle is doing.\n" ); + printf( + " Add more `V's for increasing amount of detail. `-V' gives\n" ); + printf( + " information on algorithmic progress and more detailed statistics.\n" ); + printf( + " `-VV' gives point-by-point details, and will print so much that\n" ); + printf( + " Triangle will run much more slowly. `-VVV' gives information only\n" + ); + printf( " a debugger could love.\n" ); + printf( " -h Help: Displays these instructions.\n" ); + printf( "\n" ); + printf( "Definitions:\n" ); + printf( "\n" ); + printf( + " A Delaunay triangulation of a point set is a triangulation whose vertices\n" + ); + printf( + " are the point set, having the property that no point in the point set\n" ); + printf( + " falls in the interior of the circumcircle (circle that passes through all\n" + ); + printf( " three vertices) of any triangle in the triangulation.\n\n" ); + printf( + " A Voronoi diagram of a point set is a subdivision of the plane into\n" ); + printf( + " polygonal regions (some of which may be infinite), where each region is\n" ); + printf( + " the set of points in the plane that are closer to some input point than\n" ); + printf( + " to any other input point. (The Voronoi diagram is the geometric dual of\n" + ); + printf( " the Delaunay triangulation.)\n\n" ); + printf( + " A Planar Straight Line Graph (PSLG) is a collection of points and\n" ); + printf( + " segments. Segments are simply edges, whose endpoints are points in the\n" ); + printf( + " PSLG. The file format for PSLGs (.poly files) is described below.\n" ); + printf( "\n" ); + printf( + " A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n" ); + printf( + " triangulation, but each PSLG segment is present as a single edge in the\n" ); + printf( + " triangulation. (A constrained Delaunay triangulation is not truly a\n" ); + printf( " Delaunay triangulation.)\n\n" ); + printf( + " A conforming Delaunay triangulation of a PSLG is a true Delaunay\n" ); + printf( + " triangulation in which each PSLG segment may have been subdivided into\n" ); + printf( + " several edges by the insertion of additional points. These inserted\n" ); + printf( + " points are necessary to allow the segments to exist in the mesh while\n" ); + printf( " maintaining the Delaunay property.\n\n" ); + printf( "File Formats:\n\n" ); + printf( + " All files may contain comments prefixed by the character '#'. Points,\n" ); + printf( + " triangles, edges, holes, and maximum area constraints must be numbered\n" ); + printf( + " consecutively, starting from either 1 or 0. Whichever you choose, all\n" ); + printf( + " input files must be consistent; if the nodes are numbered from 1, so must\n" + ); + printf( + " be all other objects. Triangle automatically detects your choice while\n" ); + printf( + " reading the .node (or .poly) file. (When calling Triangle from another\n" ); + printf( + " program, use the -z switch if you wish to number objects from zero.)\n" ); + printf( " Examples of these file formats are given below.\n\n" ); + printf( " .node files:\n" ); + printf( + " First line: <# of points> <# of attributes>\n" ); + printf( + " <# of boundary markers (0 or 1)>\n" + ); + printf( + " Remaining lines: [attributes] [boundary marker]\n" ); + printf( "\n" ); + printf( + " The attributes, which are typically floating-point values of physical\n" ); + printf( + " quantities (such as mass or conductivity) associated with the nodes of\n" + ); + printf( + " a finite element mesh, are copied unchanged to the output mesh. If -s,\n" + ); + printf( + " -q, or -a is selected, each new Steiner point added to the mesh will\n" ); + printf( " have attributes assigned to it by linear interpolation.\n\n" ); + printf( + " If the fourth entry of the first line is `1', the last column of the\n" ); + printf( + " remainder of the file is assumed to contain boundary markers. Boundary\n" + ); + printf( + " markers are used to identify boundary points and points resting on PSLG\n" + ); + printf( + " segments; a complete description appears in a section below. The .node\n" + ); + printf( + " file produced by Triangle will contain boundary markers in the last\n" ); + printf( " column unless they are suppressed by the -B switch.\n\n" ); + printf( " .ele files:\n" ); + printf( + " First line: <# of triangles> <# of attributes>\n" ); + printf( + " Remaining lines: ... [attributes]\n" + ); + printf( "\n" ); + printf( + " Points are indices into the corresponding .node file. The first three\n" + ); + printf( + " points are the corners, and are listed in counterclockwise order around\n" + ); + printf( + " each triangle. (The remaining points, if any, depend on the type of\n" ); + printf( + " finite element used.) The attributes are just like those of .node\n" ); + printf( + " files. Because there is no simple mapping from input to output\n" ); + printf( + " triangles, an attempt is made to interpolate attributes, which may\n" ); + printf( + " result in a good deal of diffusion of attributes among nearby triangles\n" + ); + printf( + " as the triangulation is refined. Diffusion does not occur across\n" ); + printf( + " segments, so attributes used to identify segment-bounded regions remain\n" + ); + printf( + " intact. In output .ele files, all triangles have three points each\n" ); + printf( + " unless the -o2 switch is used, in which case they have six, and the\n" ); + printf( + " fourth, fifth, and sixth points lie on the midpoints of the edges\n" ); + printf( " opposite the first, second, and third corners.\n\n" ); + printf( " .poly files:\n" ); + printf( + " First line: <# of points> <# of attributes>\n" ); + printf( + " <# of boundary markers (0 or 1)>\n" + ); + printf( + " Following lines: [attributes] [boundary marker]\n" ); + printf( " One line: <# of segments> <# of boundary markers (0 or 1)>\n" ); + printf( + " Following lines: [boundary marker]\n" ); + printf( " One line: <# of holes>\n" ); + printf( " Following lines: \n" ); + printf( + " Optional line: <# of regional attributes and/or area constraints>\n" ); + printf( + " Optional following lines: \n" ); + printf( "\n" ); + printf( + " A .poly file represents a PSLG, as well as some additional information.\n" + ); + printf( + " The first section lists all the points, and is identical to the format\n" + ); + printf( + " of .node files. <# of points> may be set to zero to indicate that the\n" + ); + printf( + " points are listed in a separate .node file; .poly files produced by\n" ); + printf( + " Triangle always have this format. This has the advantage that a point\n" + ); + printf( + " set may easily be triangulated with or without segments. (The same\n" ); + printf( + " effect can be achieved, albeit using more disk space, by making a copy\n" + ); + printf( + " of the .poly file with the extension .node; all sections of the file\n" ); + printf( " but the first are ignored.)\n\n" ); + printf( + " The second section lists the segments. Segments are edges whose\n" ); + printf( + " presence in the triangulation is enforced. Each segment is specified\n" ); + printf( + " by listing the indices of its two endpoints. This means that you must\n" + ); + printf( + " include its endpoints in the point list. If -s, -q, and -a are not\n" ); + printf( + " selected, Triangle will produce a constrained Delaunay triangulation,\n" ); + printf( + " in which each segment appears as a single edge in the triangulation.\n" ); + printf( + " If -q or -a is selected, Triangle will produce a conforming Delaunay\n" ); + printf( + " triangulation, in which segments may be subdivided into smaller edges.\n" + ); + printf( " Each segment, like each point, may have a boundary marker.\n\n" ); + printf( + " The third section lists holes (and concavities, if -c is selected) in\n" ); + printf( + " the triangulation. Holes are specified by identifying a point inside\n" ); + printf( + " each hole. After the triangulation is formed, Triangle creates holes\n" ); + printf( + " by eating triangles, spreading out from each hole point until its\n" ); + printf( + " progress is blocked by PSLG segments; you must be careful to enclose\n" ); + printf( + " each hole in segments, or your whole triangulation may be eaten away.\n" ); + printf( + " If the two triangles abutting a segment are eaten, the segment itself\n" ); + printf( + " is also eaten. Do not place a hole directly on a segment; if you do,\n" ); + printf( " Triangle will choose one side of the segment arbitrarily.\n\n" ); + printf( + " The optional fourth section lists regional attributes (to be assigned\n" ); + printf( + " to all triangles in a region) and regional constraints on the maximum\n" ); + printf( + " triangle area. Triangle will read this section only if the -A switch\n" ); + printf( + " is used or the -a switch is used without a number following it, and the\n" + ); + printf( + " -r switch is not used. Regional attributes and area constraints are\n" ); + printf( + " propagated in the same manner as holes; you specify a point for each\n" ); + printf( + " attribute and/or constraint, and the attribute and/or constraint will\n" ); + printf( + " affect the whole region (bounded by segments) containing the point. If\n" + ); + printf( + " two values are written on a line after the x and y coordinate, the\n" ); + printf( + " former is assumed to be a regional attribute (but will only be applied\n" + ); + printf( + " if the -A switch is selected), and the latter is assumed to be a\n" ); + printf( + " regional area constraint (but will only be applied if the -a switch is\n" + ); + printf( + " selected). You may also specify just one value after the coordinates,\n" + ); + printf( + " which can serve as both an attribute and an area constraint, depending\n" + ); + printf( + " on the choice of switches. If you are using the -A and -a switches\n" ); + printf( + " simultaneously and wish to assign an attribute to some region without\n" ); + printf( " imposing an area constraint, use a negative maximum area.\n\n" ); + printf( + " When a triangulation is created from a .poly file, you must either\n" ); + printf( + " enclose the entire region to be triangulated in PSLG segments, or\n" ); + printf( + " use the -c switch, which encloses the convex hull of the input point\n" ); + printf( + " set. If you do not use the -c switch, Triangle will eat all triangles\n" + ); + printf( + " on the outer boundary that are not protected by segments; if you are\n" ); + printf( + " not careful, your whole triangulation may be eaten away. If you do\n" ); + printf( + " use the -c switch, you can still produce concavities by appropriate\n" ); + printf( " placement of holes just inside the convex hull.\n\n" ); + printf( + " An ideal PSLG has no intersecting segments, nor any points that lie\n" ); + printf( + " upon segments (except, of course, the endpoints of each segment.) You\n" + ); + printf( + " aren't required to make your .poly files ideal, but you should be aware\n" + ); + printf( + " of what can go wrong. Segment intersections are relatively safe -\n" ); + printf( + " Triangle will calculate the intersection points for you and add them to\n" + ); + printf( + " the triangulation - as long as your machine's floating-point precision\n" + ); + printf( + " doesn't become a problem. You are tempting the fates if you have three\n" + ); + printf( + " segments that cross at the same location, and expect Triangle to figure\n" + ); + printf( + " out where the intersection point is. Thanks to floating-point roundoff\n" + ); + printf( + " error, Triangle will probably decide that the three segments intersect\n" + ); + printf( + " at three different points, and you will find a minuscule triangle in\n" ); + printf( + " your output - unless Triangle tries to refine the tiny triangle, uses\n" ); + printf( + " up the last bit of machine precision, and fails to terminate at all.\n" ); + printf( + " You're better off putting the intersection point in the input files,\n" ); + printf( + " and manually breaking up each segment into two. Similarly, if you\n" ); + printf( + " place a point at the middle of a segment, and hope that Triangle will\n" ); + printf( + " break up the segment at that point, you might get lucky. On the other\n" + ); + printf( + " hand, Triangle might decide that the point doesn't lie precisely on the\n" + ); + printf( + " line, and you'll have a needle-sharp triangle in your output - or a lot\n" + ); + printf( " of tiny triangles if you're generating a quality mesh.\n\n" ); + printf( + " When Triangle reads a .poly file, it also writes a .poly file, which\n" ); + printf( + " includes all edges that are part of input segments. If the -c switch\n" ); + printf( + " is used, the output .poly file will also include all of the edges on\n" ); + printf( + " the convex hull. Hence, the output .poly file is useful for finding\n" ); + printf( + " edges associated with input segments and setting boundary conditions in\n" + ); + printf( + " finite element simulations. More importantly, you will need it if you\n" + ); + printf( + " plan to refine the output mesh, and don't want segments to be missing\n" ); + printf( " in later triangulations.\n\n" ); + printf( " .area files:\n" ); + printf( " First line: <# of triangles>\n" ); + printf( " Following lines: \n\n" ); + printf( + " An .area file associates with each triangle a maximum area that is used\n" + ); + printf( + " for mesh refinement. As with other file formats, every triangle must\n" ); + printf( + " be represented, and they must be numbered consecutively. A triangle\n" ); + printf( + " may be left unconstrained by assigning it a negative maximum area.\n" ); + printf( "\n" ); + printf( " .edge files:\n" ); + printf( " First line: <# of edges> <# of boundary markers (0 or 1)>\n" ); + printf( + " Following lines: [boundary marker]\n" ); + printf( "\n" ); + printf( + " Endpoints are indices into the corresponding .node file. Triangle can\n" + ); + printf( + " produce .edge files (use the -e switch), but cannot read them. The\n" ); + printf( + " optional column of boundary markers is suppressed by the -B switch.\n" ); + printf( "\n" ); + printf( + " In Voronoi diagrams, one also finds a special kind of edge that is an\n" ); + printf( + " infinite ray with only one endpoint. For these edges, a different\n" ); + printf( " format is used:\n\n" ); + printf( " -1 \n\n" ); + printf( + " The `direction' is a floating-point vector that indicates the direction\n" + ); + printf( " of the infinite ray.\n\n" ); + printf( " .neigh files:\n" ); + printf( + " First line: <# of triangles> <# of neighbors per triangle (always 3)>\n" + ); + printf( + " Following lines: \n" ); + printf( "\n" ); + printf( + " Neighbors are indices into the corresponding .ele file. An index of -1\n" + ); + printf( + " indicates a mesh boundary, and therefore no neighbor. Triangle can\n" ); + printf( + " produce .neigh files (use the -n switch), but cannot read them.\n" ); + printf( "\n" ); + printf( + " The first neighbor of triangle i is opposite the first corner of\n" ); + printf( " triangle i, and so on.\n\n" ); + printf( "Boundary Markers:\n\n" ); + printf( + " Boundary markers are tags used mainly to identify which output points and\n" + ); + printf( + " edges are associated with which PSLG segment, and to identify which\n" ); + printf( + " points and edges occur on a boundary of the triangulation. A common use\n" + ); + printf( + " is to determine where boundary conditions should be applied to a finite\n" ); + printf( + " element mesh. You can prevent boundary markers from being written into\n" ); + printf( " files produced by Triangle by using the -B switch.\n\n" ); + printf( + " The boundary marker associated with each segment in an output .poly file\n" + ); + printf( " or edge in an output .edge file is chosen as follows:\n" ); + printf( + " - If an output edge is part or all of a PSLG segment with a nonzero\n" ); + printf( + " boundary marker, then the edge is assigned the same marker.\n" ); + printf( + " - Otherwise, if the edge occurs on a boundary of the triangulation\n" ); + printf( + " (including boundaries of holes), then the edge is assigned the marker\n" + ); + printf( " one (1).\n" ); + printf( " - Otherwise, the edge is assigned the marker zero (0).\n" ); + printf( + " The boundary marker associated with each point in an output .node file is\n" + ); + printf( " chosen as follows:\n" ); + printf( + " - If a point is assigned a nonzero boundary marker in the input file,\n" ); + printf( + " then it is assigned the same marker in the output .node file.\n" ); + printf( + " - Otherwise, if the point lies on a PSLG segment (including the\n" ); + printf( + " segment's endpoints) with a nonzero boundary marker, then the point\n" ); + printf( + " is assigned the same marker. If the point lies on several such\n" ); + printf( " segments, one of the markers is chosen arbitrarily.\n" ); + printf( + " - Otherwise, if the point occurs on a boundary of the triangulation,\n" ); + printf( " then the point is assigned the marker one (1).\n" ); + printf( " - Otherwise, the point is assigned the marker zero (0).\n" ); + printf( "\n" ); + printf( + " If you want Triangle to determine for you which points and edges are on\n" ); + printf( + " the boundary, assign them the boundary marker zero (or use no markers at\n" + ); + printf( + " all) in your input files. Alternatively, you can mark some of them and\n" ); + printf( " leave others marked zero, allowing Triangle to label them.\n\n" ); + printf( "Triangulation Iteration Numbers:\n\n" ); + printf( + " Because Triangle can read and refine its own triangulations, input\n" ); + printf( + " and output files have iteration numbers. For instance, Triangle might\n" ); + printf( + " read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n" ); + printf( + " triangulation, and output the files mesh.4.node, mesh.4.ele, and\n" ); + printf( " mesh.4.poly. Files with no iteration number are treated as if\n" ); + printf( + " their iteration number is zero; hence, Triangle might read the file\n" ); + printf( + " points.node, triangulate it, and produce the files points.1.node and\n" ); + printf( " points.1.ele.\n\n" ); + printf( + " Iteration numbers allow you to create a sequence of successively finer\n" ); + printf( + " meshes suitable for multigrid methods. They also allow you to produce a\n" + ); + printf( + " sequence of meshes using error estimate-driven mesh refinement.\n" ); + printf( "\n" ); + printf( + " If you're not using refinement or quality meshing, and you don't like\n" ); + printf( + " iteration numbers, use the -I switch to disable them. This switch will\n" ); + printf( + " also disable output of .node and .poly files to prevent your input files\n" + ); + printf( + " from being overwritten. (If the input is a .poly file that contains its\n" + ); + printf( " own points, a .node file will be written.)\n\n" ); + printf( "Examples of How to Use Triangle:\n\n" ); + printf( + " `triangle dots' will read points from dots.node, and write their Delaunay\n" + ); + printf( + " triangulation to dots.1.node and dots.1.ele. (dots.1.node will be\n" ); + printf( + " identical to dots.node.) `triangle -I dots' writes the triangulation to\n" + ); + printf( + " dots.ele instead. (No additional .node file is needed, so none is\n" ); + printf( " written.)\n\n" ); + printf( + " `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n" + ); + printf( + " object.1.node, if the points are omitted from object.1.poly) and write\n" ); + printf( " their constrained Delaunay triangulation to object.2.node and\n" ); + printf( + " object.2.ele. The segments will be copied to object.2.poly, and all\n" ); + printf( " edges will be written to object.2.edge.\n\n" ); + printf( + " `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n" ); + printf( + " possibly object.node), generate a mesh whose angles are all greater than\n" + ); + printf( + " 31.5 degrees and whose triangles all have area smaller than 0.1, and\n" ); + printf( + " write the mesh to object.1.node and object.1.ele. Each segment may have\n" + ); + printf( + " been broken up into multiple edges; the resulting constrained edges are\n" ); + printf( " written to object.1.poly.\n\n" ); + printf( + " Here is a sample file `box.poly' describing a square with a square hole:\n" + ); + printf( "\n" ); + printf( + " # A box with eight points in 2D, no attributes, one boundary marker.\n" ); + printf( " 8 2 0 1\n" ); + printf( " # Outer box has these vertices:\n" ); + printf( " 1 0 0 0\n" ); + printf( " 2 0 3 0\n" ); + printf( " 3 3 0 0\n" ); + printf( " 4 3 3 33 # A special marker for this point.\n" ); + printf( " # Inner square has these vertices:\n" ); + printf( " 5 1 1 0\n" ); + printf( " 6 1 2 0\n" ); + printf( " 7 2 1 0\n" ); + printf( " 8 2 2 0\n" ); + printf( " # Five segments with boundary markers.\n" ); + printf( " 5 1\n" ); + printf( " 1 1 2 5 # Left side of outer box.\n" ); + printf( " 2 5 7 0 # Segments 2 through 5 enclose the hole.\n" ); + printf( " 3 7 8 0\n" ); + printf( " 4 8 6 10\n" ); + printf( " 5 6 5 0\n" ); + printf( " # One hole in the middle of the inner square.\n" ); + printf( " 1\n" ); + printf( " 1 1.5 1.5\n\n" ); + printf( + " Note that some segments are missing from the outer square, so one must\n" ); + printf( + " use the `-c' switch. After `triangle -pqc box.poly', here is the output\n" + ); + printf( + " file `box.1.node', with twelve points. The last four points were added\n" ); + printf( + " to meet the angle constraint. Points 1, 2, and 9 have markers from\n" ); + printf( + " segment 1. Points 6 and 8 have markers from segment 4. All the other\n" ); + printf( + " points but 4 have been marked to indicate that they lie on a boundary.\n" ); + printf( "\n" ); + printf( " 12 2 0 1\n" ); + printf( " 1 0 0 5\n" ); + printf( " 2 0 3 5\n" ); + printf( " 3 3 0 1\n" ); + printf( " 4 3 3 33\n" ); + printf( " 5 1 1 1\n" ); + printf( " 6 1 2 10\n" ); + printf( " 7 2 1 1\n" ); + printf( " 8 2 2 10\n" ); + printf( " 9 0 1.5 5\n" ); + printf( " 10 1.5 0 1\n" ); + printf( " 11 3 1.5 1\n" ); + printf( " 12 1.5 3 1\n" ); + printf( " # Generated by triangle -pqc box.poly\n\n" ); + printf( " Here is the output file `box.1.ele', with twelve triangles.\n\n" ); + printf( " 12 3 0\n" ); + printf( " 1 5 6 9\n" ); + printf( " 2 10 3 7\n" ); + printf( " 3 6 8 12\n" ); + printf( " 4 9 1 5\n" ); + printf( " 5 6 2 9\n" ); + printf( " 6 7 3 11\n" ); + printf( " 7 11 4 8\n" ); + printf( " 8 7 5 10\n" ); + printf( " 9 12 2 6\n" ); + printf( " 10 8 7 11\n" ); + printf( " 11 5 1 10\n" ); + printf( " 12 8 4 12\n" ); + printf( " # Generated by triangle -pqc box.poly\n\n" ); + printf( + " Here is the output file `box.1.poly'. Note that segments have been added\n" + ); + printf( + " to represent the convex hull, and some segments have been split by newly\n" + ); + printf( + " added points. Note also that <# of points> is set to zero to indicate\n" ); + printf( " that the points should be read from the .node file.\n\n" ); + printf( " 0 2 0 1\n" ); + printf( " 12 1\n" ); + printf( " 1 1 9 5\n" ); + printf( " 2 5 7 1\n" ); + printf( " 3 8 7 1\n" ); + printf( " 4 6 8 10\n" ); + printf( " 5 5 6 1\n" ); + printf( " 6 3 10 1\n" ); + printf( " 7 4 11 1\n" ); + printf( " 8 2 12 1\n" ); + printf( " 9 9 2 5\n" ); + printf( " 10 10 1 1\n" ); + printf( " 11 11 3 1\n" ); + printf( " 12 12 4 1\n" ); + printf( " 1\n" ); + printf( " 1 1.5 1.5\n" ); + printf( " # Generated by triangle -pqc box.poly\n\n" ); + printf( "Refinement and Area Constraints:\n\n" ); + printf( + " The -r switch causes a mesh (.node and .ele files) to be read and\n" ); + printf( + " refined. If the -p switch is also used, a .poly file is read and used to\n" + ); + printf( + " specify edges that are constrained and cannot be eliminated (although\n" ); + printf( + " they can be divided into smaller edges) by the refinement process.\n" ); + printf( "\n" ); + printf( + " When you refine a mesh, you generally want to impose tighter quality\n" ); + printf( + " constraints. One way to accomplish this is to use -q with a larger\n" ); + printf( + " angle, or -a followed by a smaller area than you used to generate the\n" ); + printf( + " mesh you are refining. Another way to do this is to create an .area\n" ); + printf( + " file, which specifies a maximum area for each triangle, and use the -a\n" ); + printf( + " switch (without a number following). Each triangle's area constraint is\n" + ); + printf( + " applied to that triangle. Area constraints tend to diffuse as the mesh\n" ); + printf( + " is refined, so if there are large variations in area constraint between\n" ); + printf( " adjacent triangles, you may not get the results you want.\n\n" ); + printf( + " If you are refining a mesh composed of linear (three-node) elements, the\n" + ); + printf( + " output mesh will contain all the nodes present in the input mesh, in the\n" + ); + printf( + " same order, with new nodes added at the end of the .node file. However,\n" + ); + printf( + " there is no guarantee that each output element is contained in a single\n" ); + printf( + " input element. Often, output elements will overlap two input elements,\n" ); + printf( + " and input edges are not present in the output mesh. Hence, a sequence of\n" + ); + printf( + " refined meshes will form a hierarchy of nodes, but not a hierarchy of\n" ); + printf( + " elements. If you a refining a mesh of higher-order elements, the\n" ); + printf( + " hierarchical property applies only to the nodes at the corners of an\n" ); + printf( " element; other nodes may not be present in the refined mesh.\n\n" ); + printf( + " It is important to understand that maximum area constraints in .poly\n" ); + printf( + " files are handled differently from those in .area files. A maximum area\n" + ); + printf( + " in a .poly file applies to the whole (segment-bounded) region in which a\n" + ); + printf( + " point falls, whereas a maximum area in an .area file applies to only one\n" + ); + printf( + " triangle. Area constraints in .poly files are used only when a mesh is\n" ); + printf( + " first generated, whereas area constraints in .area files are used only to\n" + ); + printf( + " refine an existing mesh, and are typically based on a posteriori error\n" ); + printf( + " estimates resulting from a finite element simulation on that mesh.\n" ); + printf( "\n" ); + printf( + " `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n" + ); + printf( + " refine the triangulation to enforce a 25 degree minimum angle, and then\n" ); + printf( + " write the refined triangulation to object.2.node and object.2.ele.\n" ); + printf( "\n" ); + printf( + " `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n" ); + printf( + " z.3.area. After reconstructing the mesh and its segments, Triangle will\n" + ); + printf( + " refine the mesh so that no triangle has area greater than 6.2, and\n" ); + printf( + " furthermore the triangles satisfy the maximum area constraints in\n" ); + printf( + " z.3.area. The output is written to z.4.node, z.4.ele, and z.4.poly.\n" ); + printf( "\n" ); + printf( + " The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n" ); + printf( + " x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n" ); + printf( " suitable for multigrid.\n\n" ); + printf( "Convex Hulls and Mesh Boundaries:\n\n" ); + printf( + " If the input is a point set (rather than a PSLG), Triangle produces its\n" ); + printf( + " convex hull as a by-product in the output .poly file if you use the -c\n" ); + printf( + " switch. There are faster algorithms for finding a two-dimensional convex\n" + ); + printf( + " hull than triangulation, of course, but this one comes for free. If the\n" + ); + printf( + " input is an unconstrained mesh (you are using the -r switch but not the\n" ); + printf( + " -p switch), Triangle produces a list of its boundary edges (including\n" ); + printf( " hole boundaries) as a by-product if you use the -c switch.\n\n" ); + printf( "Voronoi Diagrams:\n\n" ); + printf( + " The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n" ); + printf( + " .v.edge. For example, `triangle -v points' will read points.node,\n" ); + printf( + " produce its Delaunay triangulation in points.1.node and points.1.ele,\n" ); + printf( + " and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n" ); + printf( + " The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n" + ); + printf( + " file contains a list of all Voronoi edges, some of which may be infinite\n" + ); + printf( + " rays. (The choice of filenames makes it easy to run the set of Voronoi\n" ); + printf( " vertices through Triangle, if so desired.)\n\n" ); + printf( + " This implementation does not use exact arithmetic to compute the Voronoi\n" + ); + printf( + " vertices, and does not check whether neighboring vertices are identical.\n" + ); + printf( + " Be forewarned that if the Delaunay triangulation is degenerate or\n" ); + printf( + " near-degenerate, the Voronoi diagram may have duplicate points, crossing\n" + ); + printf( + " edges, or infinite rays whose direction vector is zero. Also, if you\n" ); + printf( + " generate a constrained (as opposed to conforming) Delaunay triangulation,\n" + ); + printf( + " or if the triangulation has holes, the corresponding Voronoi diagram is\n" ); + printf( " likely to have crossing edges and unlikely to make sense.\n\n" ); + printf( "Mesh Topology:\n\n" ); + printf( + " You may wish to know which triangles are adjacent to a certain Delaunay\n" ); + printf( + " edge in an .edge file, which Voronoi regions are adjacent to a certain\n" ); + printf( + " Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n" + ); + printf( + " each other. All of this information can be found by cross-referencing\n" ); + printf( + " output files with the recollection that the Delaunay triangulation and\n" ); + printf( " the Voronoi diagrams are planar duals.\n\n" ); + printf( + " Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n" ); + printf( + " the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n" ); + printf( + " wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n" ); + printf( + " vertex j of the corresponding .v.node file; and Voronoi region k is the\n" ); + printf( " dual of point k of the corresponding .node file.\n\n" ); + printf( + " Hence, to find the triangles adjacent to a Delaunay edge, look at the\n" ); + printf( + " vertices of the corresponding Voronoi edge; their dual triangles are on\n" ); + printf( + " the left and right of the Delaunay edge, respectively. To find the\n" ); + printf( + " Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n" + ); + printf( + " corresponding Delaunay edge; their dual regions are on the right and left\n" + ); + printf( + " of the Voronoi edge, respectively. To find which Voronoi regions are\n" ); + printf( " adjacent to each other, just read the list of Delaunay edges.\n" ); + printf( "\n" ); + printf( "Statistics:\n" ); + printf( "\n" ); + printf( + " After generating a mesh, Triangle prints a count of the number of points,\n" + ); + printf( + " triangles, edges, boundary edges, and segments in the output mesh. If\n" ); + printf( + " you've forgotten the statistics for an existing mesh, the -rNEP switches\n" + ); + printf( + " (or -rpNEP if you've got a .poly file for the existing mesh) will\n" ); + printf( " regenerate these statistics without writing any output.\n\n" ); + printf( + " The -V switch produces extended statistics, including a rough estimate\n" ); + printf( + " of memory use and a histogram of triangle aspect ratios and angles in the\n" + ); + printf( " mesh.\n\n" ); + printf( "Exact Arithmetic:\n\n" ); + printf( + " Triangle uses adaptive exact arithmetic to perform what computational\n" ); + printf( + " geometers call the `orientation' and `incircle' tests. If the floating-\n" + ); + printf( + " point arithmetic of your machine conforms to the IEEE 754 standard (as\n" ); + printf( + " most workstations do), and does not use extended precision internal\n" ); + printf( + " registers, then your output is guaranteed to be an absolutely true\n" ); + printf( " Delaunay or conforming Delaunay triangulation, roundoff error\n" ); + printf( + " notwithstanding. The word `adaptive' implies that these arithmetic\n" ); + printf( + " routines compute the result only to the precision necessary to guarantee\n" + ); + printf( + " correctness, so they are usually nearly as fast as their approximate\n" ); + printf( + " counterparts. The exact tests can be disabled with the -X switch. On\n" ); + printf( + " most inputs, this switch will reduce the computation time by about eight\n" + ); + printf( + " percent - it's not worth the risk. There are rare difficult inputs\n" ); + printf( + " (having many collinear and cocircular points), however, for which the\n" ); + printf( + " difference could be a factor of two. These are precisely the inputs most\n" + ); + printf( " likely to cause errors if you use the -X switch.\n\n" ); + printf( + " Unfortunately, these routines don't solve every numerical problem. Exact\n" + ); + printf( + " arithmetic is not used to compute the positions of points, because the\n" ); + printf( + " bit complexity of point coordinates would grow without bound. Hence,\n" ); + printf( + " segment intersections aren't computed exactly; in very unusual cases,\n" ); + printf( + " roundoff error in computing an intersection point might actually lead to\n" + ); + printf( + " an inverted triangle and an invalid triangulation. (This is one reason\n" ); + printf( + " to compute your own intersection points in your .poly files.) Similarly,\n" + ); + printf( + " exact arithmetic is not used to compute the vertices of the Voronoi\n" ); + printf( " diagram.\n\n" ); + printf( + " Underflow and overflow can also cause difficulties; the exact arithmetic\n" + ); + printf( + " routines do not ameliorate out-of-bounds exponents, which can arise\n" ); + printf( + " during the orientation and incircle tests. As a rule of thumb, you\n" ); + printf( + " should ensure that your input values are within a range such that their\n" ); + printf( + " third powers can be taken without underflow or overflow. Underflow can\n" ); + printf( + " silently prevent the tests from being performed exactly, while overflow\n" ); + printf( " will typically cause a floating exception.\n\n" ); + printf( "Calling Triangle from Another Program:\n\n" ); + printf( " Read the file triangle.h for details.\n\n" ); + printf( "Troubleshooting:\n\n" ); + printf( " Please read this section before mailing me bugs.\n\n" ); + printf( " `My output mesh has no triangles!'\n\n" ); + printf( + " If you're using a PSLG, you've probably failed to specify a proper set\n" + ); + printf( + " of bounding segments, or forgotten to use the -c switch. Or you may\n" ); + printf( + " have placed a hole badly. To test these possibilities, try again with\n" + ); + printf( + " the -c and -O switches. Alternatively, all your input points may be\n" ); + printf( + " collinear, in which case you can hardly expect to triangulate them.\n" ); + printf( "\n" ); + printf( " `Triangle doesn't terminate, or just crashes.'\n" ); + printf( "\n" ); + printf( + " Bad things can happen when triangles get so small that the distance\n" ); + printf( + " between their vertices isn't much larger than the precision of your\n" ); + printf( + " machine's arithmetic. If you've compiled Triangle for single-precision\n" + ); + printf( + " arithmetic, you might do better by recompiling it for double-precision.\n" + ); + printf( + " Then again, you might just have to settle for more lenient constraints\n" + ); + printf( + " on the minimum angle and the maximum area than you had planned.\n" ); + printf( "\n" ); + printf( + " You can minimize precision problems by ensuring that the origin lies\n" ); + printf( + " inside your point set, or even inside the densest part of your\n" ); + printf( + " mesh. On the other hand, if you're triangulating an object whose x\n" ); + printf( + " coordinates all fall between 6247133 and 6247134, you're not leaving\n" ); + printf( " much floating-point precision for Triangle to work with.\n\n" ); + printf( + " Precision problems can occur covertly if the input PSLG contains two\n" ); + printf( + " segments that meet (or intersect) at a very small angle, or if such an\n" + ); + printf( + " angle is introduced by the -c switch, which may occur if a point lies\n" ); + printf( + " ever-so-slightly inside the convex hull, and is connected by a PSLG\n" ); + printf( + " segment to a point on the convex hull. If you don't realize that a\n" ); + printf( + " small angle is being formed, you might never discover why Triangle is\n" ); + printf( + " crashing. To check for this possibility, use the -S switch (with an\n" ); + printf( + " appropriate limit on the number of Steiner points, found by trial-and-\n" + ); + printf( + " error) to stop Triangle early, and view the output .poly file with\n" ); + printf( + " Show Me (described below). Look carefully for small angles between\n" ); + printf( + " segments; zoom in closely, as such segments might look like a single\n" ); + printf( " segment from a distance.\n\n" ); + printf( + " If some of the input values are too large, Triangle may suffer a\n" ); + printf( + " floating exception due to overflow when attempting to perform an\n" ); + printf( + " orientation or incircle test. (Read the section on exact arithmetic\n" ); + printf( + " above.) Again, I recommend compiling Triangle for double (rather\n" ); + printf( " than single) precision arithmetic.\n\n" ); + printf( + " `The numbering of the output points doesn't match the input points.'\n" ); + printf( "\n" ); + printf( + " You may have eaten some of your input points with a hole, or by placing\n" + ); + printf( " them outside the area enclosed by segments.\n\n" ); + printf( + " `Triangle executes without incident, but when I look at the resulting\n" ); + printf( + " mesh, it has overlapping triangles or other geometric inconsistencies.'\n" ); + printf( "\n" ); + printf( + " If you select the -X switch, Triangle's divide-and-conquer Delaunay\n" ); + printf( + " triangulation algorithm occasionally makes mistakes due to floating-\n" ); + printf( + " point roundoff error. Although these errors are rare, don't use the -X\n" + ); + printf( " switch. If you still have problems, please report the bug.\n" ); + printf( "\n" ); + printf( + " Strange things can happen if you've taken liberties with your PSLG. Do\n" ); + printf( + " you have a point lying in the middle of a segment? Triangle sometimes\n" ); + printf( + " copes poorly with that sort of thing. Do you want to lay out a collinear\n" + ); + printf( + " row of evenly spaced, segment-connected points? Have you simply defined\n" + ); + printf( + " one long segment connecting the leftmost point to the rightmost point,\n" ); + printf( + " and a bunch of points lying along it? This method occasionally works,\n" ); + printf( + " especially with horizontal and vertical lines, but often it doesn't, and\n" + ); + printf( + " you'll have to connect each adjacent pair of points with a separate\n" ); + printf( " segment. If you don't like it, tough.\n\n" ); + printf( + " Furthermore, if you have segments that intersect other than at their\n" ); + printf( + " endpoints, try not to let the intersections fall extremely close to PSLG\n" + ); + printf( " points or each other.\n\n" ); + printf( + " If you have problems refining a triangulation not produced by Triangle:\n" ); + printf( + " Are you sure the triangulation is geometrically valid? Is it formatted\n" ); + printf( + " correctly for Triangle? Are the triangles all listed so the first three\n" + ); + printf( " points are their corners in counterclockwise order?\n\n" ); + printf( "Show Me:\n\n" ); + printf( + " Triangle comes with a separate program named `Show Me', whose primary\n" ); + printf( + " purpose is to draw meshes on your screen or in PostScript. Its secondary\n" + ); + printf( + " purpose is to check the validity of your input files, and do so more\n" ); + printf( + " thoroughly than Triangle does. Show Me requires that you have the X\n" ); + printf( + " Windows system. If you didn't receive Show Me with Triangle, complain to\n" + ); + printf( " whomever you obtained Triangle from, then send me mail.\n\n" ); + printf( "Triangle on the Web:\n\n" ); + printf( + " To see an illustrated, updated version of these instructions, check out\n" ); + printf( "\n" ); + printf( " http://www.cs.cmu.edu/~quake/triangle.html\n" ); + printf( "\n" ); + printf( "A Brief Plea:\n" ); + printf( "\n" ); + printf( + " If you use Triangle, and especially if you use it to accomplish real\n" ); + printf( + " work, I would like very much to hear from you. A short letter or email\n" ); + printf( + " (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n" ); + printf( + " me. The more people I know are using this program, the more easily I can\n" + ); + printf( + " justify spending time on improvements and on the three-dimensional\n" ); + printf( + " successor to Triangle, which in turn will benefit you. Also, I can put\n" ); + printf( + " you on a list to receive email whenever a new version of Triangle is\n" ); + printf( " available.\n\n" ); + printf( + " If you use a mesh generated by Triangle in a publication, please include\n" + ); + printf( " an acknowledgment as well.\n\n" ); + printf( "Research credit:\n\n" ); + printf( + " Of course, I can take credit for only a fraction of the ideas that made\n" ); + printf( + " this mesh generator possible. Triangle owes its existence to the efforts\n" + ); + printf( + " of many fine computational geometers and other researchers, including\n" ); + printf( + " Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n" ); + printf( + " Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n" ); + printf( + " Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n" ); + printf( + " Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n" + ); + printf( + " J. Van Wyk, David F. Watson, and Binhai Zhu. See the comments at the\n" ); + printf( " beginning of the source code for references.\n\n" ); + exit( 0 ); } #endif /* not TRILIBRARY */ @@ -2655,12 +2653,11 @@ void info() /* */ /*****************************************************************************/ -void internalerror() -{ - printf(" Please report this bug to jrs@cs.cmu.edu\n"); - printf(" Include the message above, your input data set, and the exact\n"); - printf(" command line you used to run Triangle.\n"); - exit(1); +void internalerror(){ + printf( " Please report this bug to jrs@cs.cmu.edu\n" ); + printf( " Include the message above, your input data set, and the exact\n" ); + printf( " command line you used to run Triangle.\n" ); + exit( 1 ); } /*****************************************************************************/ @@ -2672,7 +2669,7 @@ void internalerror() /* */ /*****************************************************************************/ -void parsecommandline(argc, argv) +void parsecommandline( argc, argv ) int argc; char **argv; { @@ -2680,315 +2677,320 @@ char **argv; #define STARTINDEX 0 #else /* not TRILIBRARY */ #define STARTINDEX 1 - int increment; - int meshnumber; + int increment; + int meshnumber; #endif /* not TRILIBRARY */ - int i, j; + int i, j; #ifndef CDT_ONLY - int k; - char workstring[FILENAMESIZE]; + int k; + char workstring[FILENAMESIZE]; #endif - poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0; - firstnumber = 1; - edgesout = voronoi = neighbors = geomview = 0; - nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0; - noholes = noexact = 0; - incremental = sweepline = 0; - dwyer = 1; - splitseg = 0; - docheck = 0; - nobisect = 0; - steiner = -1; - order = 1; - minangle = 0.0; - maxarea = -1.0; - quiet = verbose = 0; + poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0; + firstnumber = 1; + edgesout = voronoi = neighbors = geomview = 0; + nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0; + noholes = noexact = 0; + incremental = sweepline = 0; + dwyer = 1; + splitseg = 0; + docheck = 0; + nobisect = 0; + steiner = -1; + order = 1; + minangle = 0.0; + maxarea = -1.0; + quiet = verbose = 0; #ifndef TRILIBRARY - innodefilename[0] = '\0'; + innodefilename[0] = '\0'; #endif /* not TRILIBRARY */ - for (i = STARTINDEX; i < argc; i++) { + for ( i = STARTINDEX; i < argc; i++ ) { #ifndef TRILIBRARY - if (argv[i][0] == '-') { + if ( argv[i][0] == '-' ) { #endif /* not TRILIBRARY */ - for (j = STARTINDEX; argv[i][j] != '\0'; j++) { - if (argv[i][j] == 'p') { - poly = 1; - } + for ( j = STARTINDEX; argv[i][j] != '\0'; j++ ) { + if ( argv[i][j] == 'p' ) { + poly = 1; + } #ifndef CDT_ONLY - if (argv[i][j] == 'r') { - refine = 1; - } - if (argv[i][j] == 'q') { - quality = 1; - if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - k = 0; - while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - j++; - workstring[k] = argv[i][j]; - k++; - } - workstring[k] = '\0'; - minangle = (REAL) strtod(workstring, (char **) NULL); - } else { - minangle = 20.0; - } - } - if (argv[i][j] == 'a') { - quality = 1; - if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - fixedarea = 1; - k = 0; - while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - j++; - workstring[k] = argv[i][j]; - k++; - } - workstring[k] = '\0'; - maxarea = (REAL) strtod(workstring, (char **) NULL); - if (maxarea <= 0.0) { - printf("Error: Maximum area must be greater than zero.\n"); - exit(1); - } - } else { - vararea = 1; - } - } + if ( argv[i][j] == 'r' ) { + refine = 1; + } + if ( argv[i][j] == 'q' ) { + quality = 1; + if ( ( ( argv[i][j + 1] >= '0' ) && ( argv[i][j + 1] <= '9' ) ) || + ( argv[i][j + 1] == '.' ) ) { + k = 0; + while ( ( ( argv[i][j + 1] >= '0' ) && ( argv[i][j + 1] <= '9' ) ) || + ( argv[i][j + 1] == '.' ) ) { + j++; + workstring[k] = argv[i][j]; + k++; + } + workstring[k] = '\0'; + minangle = (REAL) strtod( workstring, (char **) NULL ); + } + else { + minangle = 20.0; + } + } + if ( argv[i][j] == 'a' ) { + quality = 1; + if ( ( ( argv[i][j + 1] >= '0' ) && ( argv[i][j + 1] <= '9' ) ) || + ( argv[i][j + 1] == '.' ) ) { + fixedarea = 1; + k = 0; + while ( ( ( argv[i][j + 1] >= '0' ) && ( argv[i][j + 1] <= '9' ) ) || + ( argv[i][j + 1] == '.' ) ) { + j++; + workstring[k] = argv[i][j]; + k++; + } + workstring[k] = '\0'; + maxarea = (REAL) strtod( workstring, (char **) NULL ); + if ( maxarea <= 0.0 ) { + printf( "Error: Maximum area must be greater than zero.\n" ); + exit( 1 ); + } + } + else { + vararea = 1; + } + } #endif /* not CDT_ONLY */ - if (argv[i][j] == 'A') { - regionattrib = 1; - } - if (argv[i][j] == 'c') { - convex = 1; - } - if (argv[i][j] == 'z') { - firstnumber = 0; - } - if (argv[i][j] == 'e') { - edgesout = 1; - } - if (argv[i][j] == 'v') { - voronoi = 1; - } - if (argv[i][j] == 'n') { - neighbors = 1; - } - if (argv[i][j] == 'g') { - geomview = 1; - } - if (argv[i][j] == 'B') { - nobound = 1; - } - if (argv[i][j] == 'P') { - nopolywritten = 1; - } - if (argv[i][j] == 'N') { - nonodewritten = 1; - } - if (argv[i][j] == 'E') { - noelewritten = 1; - } + if ( argv[i][j] == 'A' ) { + regionattrib = 1; + } + if ( argv[i][j] == 'c' ) { + convex = 1; + } + if ( argv[i][j] == 'z' ) { + firstnumber = 0; + } + if ( argv[i][j] == 'e' ) { + edgesout = 1; + } + if ( argv[i][j] == 'v' ) { + voronoi = 1; + } + if ( argv[i][j] == 'n' ) { + neighbors = 1; + } + if ( argv[i][j] == 'g' ) { + geomview = 1; + } + if ( argv[i][j] == 'B' ) { + nobound = 1; + } + if ( argv[i][j] == 'P' ) { + nopolywritten = 1; + } + if ( argv[i][j] == 'N' ) { + nonodewritten = 1; + } + if ( argv[i][j] == 'E' ) { + noelewritten = 1; + } #ifndef TRILIBRARY - if (argv[i][j] == 'I') { - noiterationnum = 1; - } + if ( argv[i][j] == 'I' ) { + noiterationnum = 1; + } #endif /* not TRILIBRARY */ - if (argv[i][j] == 'O') { - noholes = 1; - } - if (argv[i][j] == 'X') { - noexact = 1; - } - if (argv[i][j] == 'o') { - if (argv[i][j + 1] == '2') { - j++; - order = 2; - } - } + if ( argv[i][j] == 'O' ) { + noholes = 1; + } + if ( argv[i][j] == 'X' ) { + noexact = 1; + } + if ( argv[i][j] == 'o' ) { + if ( argv[i][j + 1] == '2' ) { + j++; + order = 2; + } + } #ifndef CDT_ONLY - if (argv[i][j] == 'Y') { - nobisect++; - } - if (argv[i][j] == 'S') { - steiner = 0; - while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) { - j++; - steiner = steiner * 10 + (int) (argv[i][j] - '0'); - } - } + if ( argv[i][j] == 'Y' ) { + nobisect++; + } + if ( argv[i][j] == 'S' ) { + steiner = 0; + while ( ( argv[i][j + 1] >= '0' ) && ( argv[i][j + 1] <= '9' ) ) { + j++; + steiner = steiner * 10 + (int) ( argv[i][j] - '0' ); + } + } #endif /* not CDT_ONLY */ #ifndef REDUCED - if (argv[i][j] == 'i') { - incremental = 1; - } - if (argv[i][j] == 'F') { - sweepline = 1; - } + if ( argv[i][j] == 'i' ) { + incremental = 1; + } + if ( argv[i][j] == 'F' ) { + sweepline = 1; + } #endif /* not REDUCED */ - if (argv[i][j] == 'l') { - dwyer = 0; - } + if ( argv[i][j] == 'l' ) { + dwyer = 0; + } #ifndef REDUCED #ifndef CDT_ONLY - if (argv[i][j] == 's') { - splitseg = 1; - } + if ( argv[i][j] == 's' ) { + splitseg = 1; + } #endif /* not CDT_ONLY */ - if (argv[i][j] == 'C') { - docheck = 1; - } + if ( argv[i][j] == 'C' ) { + docheck = 1; + } #endif /* not REDUCED */ - if (argv[i][j] == 'Q') { - quiet = 1; - } - if (argv[i][j] == 'V') { - verbose++; - } + if ( argv[i][j] == 'Q' ) { + quiet = 1; + } + if ( argv[i][j] == 'V' ) { + verbose++; + } #ifndef TRILIBRARY - if ((argv[i][j] == 'h') || (argv[i][j] == 'H') || - (argv[i][j] == '?')) { - info(); - } + if ( ( argv[i][j] == 'h' ) || ( argv[i][j] == 'H' ) || + ( argv[i][j] == '?' ) ) { + info(); + } #endif /* not TRILIBRARY */ - } + } #ifndef TRILIBRARY - } else { - strncpy(innodefilename, argv[i], FILENAMESIZE - 1); - innodefilename[FILENAMESIZE - 1] = '\0'; - } + } else { + strncpy( innodefilename, argv[i], FILENAMESIZE - 1 ); + innodefilename[FILENAMESIZE - 1] = '\0'; + } #endif /* not TRILIBRARY */ - } + } #ifndef TRILIBRARY - if (innodefilename[0] == '\0') { - syntax(); - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - poly = 1; - } + if ( innodefilename[0] == '\0' ) { + syntax(); + } + if ( !strcmp( &innodefilename[strlen( innodefilename ) - 5], ".node" ) ) { + innodefilename[strlen( innodefilename ) - 5] = '\0'; + } + if ( !strcmp( &innodefilename[strlen( innodefilename ) - 5], ".poly" ) ) { + innodefilename[strlen( innodefilename ) - 5] = '\0'; + poly = 1; + } #ifndef CDT_ONLY - if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) { - innodefilename[strlen(innodefilename) - 4] = '\0'; - refine = 1; - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - refine = 1; - quality = 1; - vararea = 1; - } + if ( !strcmp( &innodefilename[strlen( innodefilename ) - 4], ".ele" ) ) { + innodefilename[strlen( innodefilename ) - 4] = '\0'; + refine = 1; + } + if ( !strcmp( &innodefilename[strlen( innodefilename ) - 5], ".area" ) ) { + innodefilename[strlen( innodefilename ) - 5] = '\0'; + refine = 1; + quality = 1; + vararea = 1; + } #endif /* not CDT_ONLY */ #endif /* not TRILIBRARY */ - steinerleft = steiner; - useshelles = poly || refine || quality || convex; - goodangle = (REAL)cos(minangle * PI / 180.0); - goodangle *= goodangle; - if (refine && noiterationnum) { - printf( - "Error: You cannot use the -I switch when refining a triangulation.\n"); - exit(1); - } - /* Be careful not to allocate space for element area constraints that */ - /* will never be assigned any value (other than the default -1.0). */ - if (!refine && !poly) { - vararea = 0; - } - /* Be careful not to add an extra attribute to each element unless the */ - /* input supports it (PSLG in, but not refining a preexisting mesh). */ - if (refine || !poly) { - regionattrib = 0; - } + steinerleft = steiner; + useshelles = poly || refine || quality || convex; + goodangle = (REAL)cos( minangle * PI / 180.0 ); + goodangle *= goodangle; + if ( refine && noiterationnum ) { + printf( + "Error: You cannot use the -I switch when refining a triangulation.\n" ); + exit( 1 ); + } + /* Be careful not to allocate space for element area constraints that */ + /* will never be assigned any value (other than the default -1.0). */ + if ( !refine && !poly ) { + vararea = 0; + } + /* Be careful not to add an extra attribute to each element unless the */ + /* input supports it (PSLG in, but not refining a preexisting mesh). */ + if ( refine || !poly ) { + regionattrib = 0; + } #ifndef TRILIBRARY - strcpy(inpolyfilename, innodefilename); - strcpy(inelefilename, innodefilename); - strcpy(areafilename, innodefilename); - increment = 0; - strcpy(workstring, innodefilename); - j = 1; - while (workstring[j] != '\0') { - if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) { - increment = j + 1; - } - j++; - } - meshnumber = 0; - if (increment > 0) { - j = increment; - do { - if ((workstring[j] >= '0') && (workstring[j] <= '9')) { - meshnumber = meshnumber * 10 + (int) (workstring[j] - '0'); - } else { - increment = 0; - } - j++; - } while (workstring[j] != '\0'); - } - if (noiterationnum) { - strcpy(outnodefilename, innodefilename); - strcpy(outelefilename, innodefilename); - strcpy(edgefilename, innodefilename); - strcpy(vnodefilename, innodefilename); - strcpy(vedgefilename, innodefilename); - strcpy(neighborfilename, innodefilename); - strcpy(offfilename, innodefilename); - strcat(outnodefilename, ".node"); - strcat(outelefilename, ".ele"); - strcat(edgefilename, ".edge"); - strcat(vnodefilename, ".v.node"); - strcat(vedgefilename, ".v.edge"); - strcat(neighborfilename, ".neigh"); - strcat(offfilename, ".off"); - } else if (increment == 0) { - strcpy(outnodefilename, innodefilename); - strcpy(outpolyfilename, innodefilename); - strcpy(outelefilename, innodefilename); - strcpy(edgefilename, innodefilename); - strcpy(vnodefilename, innodefilename); - strcpy(vedgefilename, innodefilename); - strcpy(neighborfilename, innodefilename); - strcpy(offfilename, innodefilename); - strcat(outnodefilename, ".1.node"); - strcat(outpolyfilename, ".1.poly"); - strcat(outelefilename, ".1.ele"); - strcat(edgefilename, ".1.edge"); - strcat(vnodefilename, ".1.v.node"); - strcat(vedgefilename, ".1.v.edge"); - strcat(neighborfilename, ".1.neigh"); - strcat(offfilename, ".1.off"); - } else { - workstring[increment] = '%'; - workstring[increment + 1] = 'd'; - workstring[increment + 2] = '\0'; - sprintf(outnodefilename, workstring, meshnumber + 1); - strcpy(outpolyfilename, outnodefilename); - strcpy(outelefilename, outnodefilename); - strcpy(edgefilename, outnodefilename); - strcpy(vnodefilename, outnodefilename); - strcpy(vedgefilename, outnodefilename); - strcpy(neighborfilename, outnodefilename); - strcpy(offfilename, outnodefilename); - strcat(outnodefilename, ".node"); - strcat(outpolyfilename, ".poly"); - strcat(outelefilename, ".ele"); - strcat(edgefilename, ".edge"); - strcat(vnodefilename, ".v.node"); - strcat(vedgefilename, ".v.edge"); - strcat(neighborfilename, ".neigh"); - strcat(offfilename, ".off"); - } - strcat(innodefilename, ".node"); - strcat(inpolyfilename, ".poly"); - strcat(inelefilename, ".ele"); - strcat(areafilename, ".area"); + strcpy( inpolyfilename, innodefilename ); + strcpy( inelefilename, innodefilename ); + strcpy( areafilename, innodefilename ); + increment = 0; + strcpy( workstring, innodefilename ); + j = 1; + while ( workstring[j] != '\0' ) { + if ( ( workstring[j] == '.' ) && ( workstring[j + 1] != '\0' ) ) { + increment = j + 1; + } + j++; + } + meshnumber = 0; + if ( increment > 0 ) { + j = increment; + do { + if ( ( workstring[j] >= '0' ) && ( workstring[j] <= '9' ) ) { + meshnumber = meshnumber * 10 + (int) ( workstring[j] - '0' ); + } + else { + increment = 0; + } + j++; + } while ( workstring[j] != '\0' ); + } + if ( noiterationnum ) { + strcpy( outnodefilename, innodefilename ); + strcpy( outelefilename, innodefilename ); + strcpy( edgefilename, innodefilename ); + strcpy( vnodefilename, innodefilename ); + strcpy( vedgefilename, innodefilename ); + strcpy( neighborfilename, innodefilename ); + strcpy( offfilename, innodefilename ); + strcat( outnodefilename, ".node" ); + strcat( outelefilename, ".ele" ); + strcat( edgefilename, ".edge" ); + strcat( vnodefilename, ".v.node" ); + strcat( vedgefilename, ".v.edge" ); + strcat( neighborfilename, ".neigh" ); + strcat( offfilename, ".off" ); + } + else if ( increment == 0 ) { + strcpy( outnodefilename, innodefilename ); + strcpy( outpolyfilename, innodefilename ); + strcpy( outelefilename, innodefilename ); + strcpy( edgefilename, innodefilename ); + strcpy( vnodefilename, innodefilename ); + strcpy( vedgefilename, innodefilename ); + strcpy( neighborfilename, innodefilename ); + strcpy( offfilename, innodefilename ); + strcat( outnodefilename, ".1.node" ); + strcat( outpolyfilename, ".1.poly" ); + strcat( outelefilename, ".1.ele" ); + strcat( edgefilename, ".1.edge" ); + strcat( vnodefilename, ".1.v.node" ); + strcat( vedgefilename, ".1.v.edge" ); + strcat( neighborfilename, ".1.neigh" ); + strcat( offfilename, ".1.off" ); + } + else { + workstring[increment] = '%'; + workstring[increment + 1] = 'd'; + workstring[increment + 2] = '\0'; + sprintf( outnodefilename, workstring, meshnumber + 1 ); + strcpy( outpolyfilename, outnodefilename ); + strcpy( outelefilename, outnodefilename ); + strcpy( edgefilename, outnodefilename ); + strcpy( vnodefilename, outnodefilename ); + strcpy( vedgefilename, outnodefilename ); + strcpy( neighborfilename, outnodefilename ); + strcpy( offfilename, outnodefilename ); + strcat( outnodefilename, ".node" ); + strcat( outpolyfilename, ".poly" ); + strcat( outelefilename, ".ele" ); + strcat( edgefilename, ".edge" ); + strcat( vnodefilename, ".v.node" ); + strcat( vedgefilename, ".v.edge" ); + strcat( neighborfilename, ".neigh" ); + strcat( offfilename, ".off" ); + } + strcat( innodefilename, ".node" ); + strcat( inpolyfilename, ".poly" ); + strcat( inelefilename, ".ele" ); + strcat( areafilename, ".area" ); #endif /* not TRILIBRARY */ } @@ -3011,77 +3013,86 @@ char **argv; /* */ /*****************************************************************************/ -void printtriangle(t) +void printtriangle( t ) struct triedge *t; { - struct triedge printtri; - struct edge printsh; - point printpoint; - - printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri, - t->orient); - decode(t->tri[0], printtri); - if (printtri.tri == dummytri) { - printf(" [0] = Outer space\n"); - } else { - printf(" [0] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(t->tri[1], printtri); - if (printtri.tri == dummytri) { - printf(" [1] = Outer space\n"); - } else { - printf(" [1] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(t->tri[2], printtri); - if (printtri.tri == dummytri) { - printf(" [2] = Outer space\n"); - } else { - printf(" [2] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - org(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3); - else - printf(" Origin[%d] = x%lx (%.12g, %.12g)\n", - (t->orient + 1) % 3 + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - dest(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Dest [%d] = NULL\n", (t->orient + 2) % 3 + 3); - else - printf(" Dest [%d] = x%lx (%.12g, %.12g)\n", - (t->orient + 2) % 3 + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - apex(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Apex [%d] = NULL\n", t->orient + 3); - else - printf(" Apex [%d] = x%lx (%.12g, %.12g)\n", - t->orient + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - if (useshelles) { - sdecode(t->tri[6], printsh); - if (printsh.sh != dummysh) { - printf(" [6] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(t->tri[7], printsh); - if (printsh.sh != dummysh) { - printf(" [7] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(t->tri[8], printsh); - if (printsh.sh != dummysh) { - printf(" [8] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - } - if (vararea) { - printf(" Area constraint: %.4g\n", areabound(*t)); - } + struct triedge printtri; + struct edge printsh; + point printpoint; + + printf( "triangle x%lx with orientation %d:\n", (unsigned long) t->tri, + t->orient ); + decode( t->tri[0], printtri ); + if ( printtri.tri == dummytri ) { + printf( " [0] = Outer space\n" ); + } + else { + printf( " [0] = x%lx %d\n", (unsigned long) printtri.tri, + printtri.orient ); + } + decode( t->tri[1], printtri ); + if ( printtri.tri == dummytri ) { + printf( " [1] = Outer space\n" ); + } + else { + printf( " [1] = x%lx %d\n", (unsigned long) printtri.tri, + printtri.orient ); + } + decode( t->tri[2], printtri ); + if ( printtri.tri == dummytri ) { + printf( " [2] = Outer space\n" ); + } + else { + printf( " [2] = x%lx %d\n", (unsigned long) printtri.tri, + printtri.orient ); + } + org( *t, printpoint ); + if ( printpoint == (point) NULL ) { + printf( " Origin[%d] = NULL\n", ( t->orient + 1 ) % 3 + 3 ); + } + else{ + printf( " Origin[%d] = x%lx (%.12g, %.12g)\n", + ( t->orient + 1 ) % 3 + 3, (unsigned long) printpoint, + printpoint[0], printpoint[1] ); + } + dest( *t, printpoint ); + if ( printpoint == (point) NULL ) { + printf( " Dest [%d] = NULL\n", ( t->orient + 2 ) % 3 + 3 ); + } + else{ + printf( " Dest [%d] = x%lx (%.12g, %.12g)\n", + ( t->orient + 2 ) % 3 + 3, (unsigned long) printpoint, + printpoint[0], printpoint[1] ); + } + apex( *t, printpoint ); + if ( printpoint == (point) NULL ) { + printf( " Apex [%d] = NULL\n", t->orient + 3 ); + } + else{ + printf( " Apex [%d] = x%lx (%.12g, %.12g)\n", + t->orient + 3, (unsigned long) printpoint, + printpoint[0], printpoint[1] ); + } + if ( useshelles ) { + sdecode( t->tri[6], printsh ); + if ( printsh.sh != dummysh ) { + printf( " [6] = x%lx %d\n", (unsigned long) printsh.sh, + printsh.shorient ); + } + sdecode( t->tri[7], printsh ); + if ( printsh.sh != dummysh ) { + printf( " [7] = x%lx %d\n", (unsigned long) printsh.sh, + printsh.shorient ); + } + sdecode( t->tri[8], printsh ); + if ( printsh.sh != dummysh ) { + printf( " [8] = x%lx %d\n", (unsigned long) printsh.sh, + printsh.shorient ); + } + } + if ( vararea ) { + printf( " Area constraint: %.4g\n", areabound( *t ) ); + } } /*****************************************************************************/ @@ -3095,57 +3106,65 @@ struct triedge *t; /* */ /*****************************************************************************/ -void printshelle(s) +void printshelle( s ) struct edge *s; { - struct edge printsh; - struct triedge printtri; - point printpoint; - - printf("shell edge x%lx with orientation %d and mark %d:\n", - (unsigned long) s->sh, s->shorient, mark(*s)); - sdecode(s->sh[0], printsh); - if (printsh.sh == dummysh) { - printf(" [0] = No shell\n"); - } else { - printf(" [0] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(s->sh[1], printsh); - if (printsh.sh == dummysh) { - printf(" [1] = No shell\n"); - } else { - printf(" [1] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sorg(*s, printpoint); - if (printpoint == (point) NULL) - printf(" Origin[%d] = NULL\n", 2 + s->shorient); - else - printf(" Origin[%d] = x%lx (%.12g, %.12g)\n", - 2 + s->shorient, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - sdest(*s, printpoint); - if (printpoint == (point) NULL) - printf(" Dest [%d] = NULL\n", 3 - s->shorient); - else - printf(" Dest [%d] = x%lx (%.12g, %.12g)\n", - 3 - s->shorient, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - decode(s->sh[4], printtri); - if (printtri.tri == dummytri) { - printf(" [4] = Outer space\n"); - } else { - printf(" [4] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(s->sh[5], printtri); - if (printtri.tri == dummytri) { - printf(" [5] = Outer space\n"); - } else { - printf(" [5] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } + struct edge printsh; + struct triedge printtri; + point printpoint; + + printf( "shell edge x%lx with orientation %d and mark %d:\n", + (unsigned long) s->sh, s->shorient, mark( *s ) ); + sdecode( s->sh[0], printsh ); + if ( printsh.sh == dummysh ) { + printf( " [0] = No shell\n" ); + } + else { + printf( " [0] = x%lx %d\n", (unsigned long) printsh.sh, + printsh.shorient ); + } + sdecode( s->sh[1], printsh ); + if ( printsh.sh == dummysh ) { + printf( " [1] = No shell\n" ); + } + else { + printf( " [1] = x%lx %d\n", (unsigned long) printsh.sh, + printsh.shorient ); + } + sorg( *s, printpoint ); + if ( printpoint == (point) NULL ) { + printf( " Origin[%d] = NULL\n", 2 + s->shorient ); + } + else{ + printf( " Origin[%d] = x%lx (%.12g, %.12g)\n", + 2 + s->shorient, (unsigned long) printpoint, + printpoint[0], printpoint[1] ); + } + sdest( *s, printpoint ); + if ( printpoint == (point) NULL ) { + printf( " Dest [%d] = NULL\n", 3 - s->shorient ); + } + else{ + printf( " Dest [%d] = x%lx (%.12g, %.12g)\n", + 3 - s->shorient, (unsigned long) printpoint, + printpoint[0], printpoint[1] ); + } + decode( s->sh[4], printtri ); + if ( printtri.tri == dummytri ) { + printf( " [4] = Outer space\n" ); + } + else { + printf( " [4] = x%lx %d\n", (unsigned long) printtri.tri, + printtri.orient ); + } + decode( s->sh[5], printtri ); + if ( printtri.tri == dummytri ) { + printf( " [5] = Outer space\n" ); + } + else { + printf( " [5] = x%lx %d\n", (unsigned long) printtri.tri, + printtri.orient ); + } } /** **/ @@ -3175,48 +3194,49 @@ struct edge *s; /* */ /*****************************************************************************/ -void poolinit(pool, bytecount, itemcount, wtype, alignment) +void poolinit( pool, bytecount, itemcount, wtype, alignment ) struct memorypool *pool; int bytecount; int itemcount; enum wordtype wtype; int alignment; { - int wordsize; - - /* Initialize values in the pool. */ - pool->itemwordtype = wtype; - wordsize = (pool->itemwordtype == POINTER) ? sizeof(VOID *) : sizeof(REAL); - /* Find the proper alignment, which must be at least as large as: */ - /* - The parameter `alignment'. */ - /* - The primary word type, to avoid unaligned accesses. */ - /* - sizeof(VOID *), so the stack of dead items can be maintained */ - /* without unaligned accesses. */ - if (alignment > wordsize) { - pool->alignbytes = alignment; - } else { - pool->alignbytes = wordsize; - } - if (sizeof(VOID *) > pool->alignbytes) { - pool->alignbytes = sizeof(VOID *); - } - pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes) - * (pool->alignbytes / wordsize); - pool->itembytes = pool->itemwords * wordsize; - pool->itemsperblock = itemcount; - - /* Allocate a block of items. Space for `itemsperblock' items and one */ - /* pointer (to point to the next block) are allocated, as well as space */ - /* to ensure alignment of the items. */ - pool->firstblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes - + sizeof(VOID *) + pool->alignbytes); - if (pool->firstblock == (VOID **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Set the next block pointer to NULL. */ - *(pool->firstblock) = (VOID *) NULL; - poolrestart(pool); + int wordsize; + + /* Initialize values in the pool. */ + pool->itemwordtype = wtype; + wordsize = ( pool->itemwordtype == POINTER ) ? sizeof( VOID * ) : sizeof( REAL ); + /* Find the proper alignment, which must be at least as large as: */ + /* - The parameter `alignment'. */ + /* - The primary word type, to avoid unaligned accesses. */ + /* - sizeof(VOID *), so the stack of dead items can be maintained */ + /* without unaligned accesses. */ + if ( alignment > wordsize ) { + pool->alignbytes = alignment; + } + else { + pool->alignbytes = wordsize; + } + if ( sizeof( VOID * ) > pool->alignbytes ) { + pool->alignbytes = sizeof( VOID * ); + } + pool->itemwords = ( ( bytecount + pool->alignbytes - 1 ) / pool->alignbytes ) + * ( pool->alignbytes / wordsize ); + pool->itembytes = pool->itemwords * wordsize; + pool->itemsperblock = itemcount; + + /* Allocate a block of items. Space for `itemsperblock' items and one */ + /* pointer (to point to the next block) are allocated, as well as space */ + /* to ensure alignment of the items. */ + pool->firstblock = (VOID **) malloc( pool->itemsperblock * pool->itembytes + + sizeof( VOID * ) + pool->alignbytes ); + if ( pool->firstblock == (VOID **) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + /* Set the next block pointer to NULL. */ + *( pool->firstblock ) = (VOID *) NULL; + poolrestart( pool ); } /*****************************************************************************/ @@ -3229,26 +3249,26 @@ int alignment; /* */ /*****************************************************************************/ -void poolrestart(pool) +void poolrestart( pool ) struct memorypool *pool; { - unsigned long alignptr; - - pool->items = 0; - pool->maxitems = 0; - - /* Set the currently active block. */ - pool->nowblock = pool->firstblock; - /* Find the first item in the pool. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->nowblock + 1); - /* Align the item on an `alignbytes'-byte boundary. */ - pool->nextitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* There are lots of unallocated items left in this block. */ - pool->unallocateditems = pool->itemsperblock; - /* The stack of deallocated items is empty. */ - pool->deaditemstack = (VOID *) NULL; + unsigned long alignptr; + + pool->items = 0; + pool->maxitems = 0; + + /* Set the currently active block. */ + pool->nowblock = pool->firstblock; + /* Find the first item in the pool. Increment by the size of (VOID *). */ + alignptr = (unsigned long) ( pool->nowblock + 1 ); + /* Align the item on an `alignbytes'-byte boundary. */ + pool->nextitem = (VOID *) + ( alignptr + (unsigned long) pool->alignbytes + - ( alignptr % (unsigned long) pool->alignbytes ) ); + /* There are lots of unallocated items left in this block. */ + pool->unallocateditems = pool->itemsperblock; + /* The stack of deallocated items is empty. */ + pool->deaditemstack = (VOID *) NULL; } /*****************************************************************************/ @@ -3257,14 +3277,14 @@ struct memorypool *pool; /* */ /*****************************************************************************/ -void pooldeinit(pool) +void pooldeinit( pool ) struct memorypool *pool; { - while (pool->firstblock != (VOID **) NULL) { - pool->nowblock = (VOID **) *(pool->firstblock); - free(pool->firstblock); - pool->firstblock = pool->nowblock; - } + while ( pool->firstblock != (VOID **) NULL ) { + pool->nowblock = (VOID **) *( pool->firstblock ); + free( pool->firstblock ); + pool->firstblock = pool->nowblock; + } } /*****************************************************************************/ @@ -3273,59 +3293,61 @@ struct memorypool *pool; /* */ /*****************************************************************************/ -VOID *poolalloc(pool) +VOID *poolalloc( pool ) struct memorypool *pool; { - VOID *newitem; - VOID **newblock; - unsigned long alignptr; - - /* First check the linked list of dead items. If the list is not */ - /* empty, allocate an item from the list rather than a fresh one. */ - if (pool->deaditemstack != (VOID *) NULL) { - newitem = pool->deaditemstack; /* Take first item in list. */ - pool->deaditemstack = * (VOID **) pool->deaditemstack; - } else { - /* Check if there are any free items left in the current block. */ - if (pool->unallocateditems == 0) { - /* Check if another block must be allocated. */ - if (*(pool->nowblock) == (VOID *) NULL) { - /* Allocate a new block of items, pointed to by the previous block. */ - newblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes - + sizeof(VOID *) + pool->alignbytes); - if (newblock == (VOID **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - *(pool->nowblock) = (VOID *) newblock; - /* The next block pointer is NULL. */ - *newblock = (VOID *) NULL; - } - /* Move to the new block. */ - pool->nowblock = (VOID **) *(pool->nowblock); - /* Find the first item in the block. */ - /* Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->nowblock + 1); - /* Align the item on an `alignbytes'-byte boundary. */ - pool->nextitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* There are lots of unallocated items left in this block. */ - pool->unallocateditems = pool->itemsperblock; - } - /* Allocate a new item. */ - newitem = pool->nextitem; - /* Advance `nextitem' pointer to next free item in block. */ - if (pool->itemwordtype == POINTER) { - pool->nextitem = (VOID *) ((VOID **) pool->nextitem + pool->itemwords); - } else { - pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords); - } - pool->unallocateditems--; - pool->maxitems++; - } - pool->items++; - return newitem; + VOID *newitem; + VOID **newblock; + unsigned long alignptr; + + /* First check the linked list of dead items. If the list is not */ + /* empty, allocate an item from the list rather than a fresh one. */ + if ( pool->deaditemstack != (VOID *) NULL ) { + newitem = pool->deaditemstack; /* Take first item in list. */ + pool->deaditemstack = *(VOID **) pool->deaditemstack; + } + else { + /* Check if there are any free items left in the current block. */ + if ( pool->unallocateditems == 0 ) { + /* Check if another block must be allocated. */ + if ( *( pool->nowblock ) == (VOID *) NULL ) { + /* Allocate a new block of items, pointed to by the previous block. */ + newblock = (VOID **) malloc( pool->itemsperblock * pool->itembytes + + sizeof( VOID * ) + pool->alignbytes ); + if ( newblock == (VOID **) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + *( pool->nowblock ) = (VOID *) newblock; + /* The next block pointer is NULL. */ + *newblock = (VOID *) NULL; + } + /* Move to the new block. */ + pool->nowblock = (VOID **) *( pool->nowblock ); + /* Find the first item in the block. */ + /* Increment by the size of (VOID *). */ + alignptr = (unsigned long) ( pool->nowblock + 1 ); + /* Align the item on an `alignbytes'-byte boundary. */ + pool->nextitem = (VOID *) + ( alignptr + (unsigned long) pool->alignbytes + - ( alignptr % (unsigned long) pool->alignbytes ) ); + /* There are lots of unallocated items left in this block. */ + pool->unallocateditems = pool->itemsperblock; + } + /* Allocate a new item. */ + newitem = pool->nextitem; + /* Advance `nextitem' pointer to next free item in block. */ + if ( pool->itemwordtype == POINTER ) { + pool->nextitem = (VOID *) ( (VOID **) pool->nextitem + pool->itemwords ); + } + else { + pool->nextitem = (VOID *) ( (REAL *) pool->nextitem + pool->itemwords ); + } + pool->unallocateditems--; + pool->maxitems++; + } + pool->items++; + return newitem; } /*****************************************************************************/ @@ -3336,14 +3358,14 @@ struct memorypool *pool; /* */ /*****************************************************************************/ -void pooldealloc(pool, dyingitem) +void pooldealloc( pool, dyingitem ) struct memorypool *pool; VOID *dyingitem; { - /* Push freshly killed item onto stack. */ - *((VOID **) dyingitem) = pool->deaditemstack; - pool->deaditemstack = dyingitem; - pool->items--; + /* Push freshly killed item onto stack. */ + *( (VOID **) dyingitem ) = pool->deaditemstack; + pool->deaditemstack = dyingitem; + pool->items--; } /*****************************************************************************/ @@ -3354,21 +3376,21 @@ VOID *dyingitem; /* */ /*****************************************************************************/ -void traversalinit(pool) +void traversalinit( pool ) struct memorypool *pool; { - unsigned long alignptr; - - /* Begin the traversal in the first block. */ - pool->pathblock = pool->firstblock; - /* Find the first item in the block. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->pathblock + 1); - /* Align with item on an `alignbytes'-byte boundary. */ - pool->pathitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* Set the number of items left in the current block. */ - pool->pathitemsleft = pool->itemsperblock; + unsigned long alignptr; + + /* Begin the traversal in the first block. */ + pool->pathblock = pool->firstblock; + /* Find the first item in the block. Increment by the size of (VOID *). */ + alignptr = (unsigned long) ( pool->pathblock + 1 ); + /* Align with item on an `alignbytes'-byte boundary. */ + pool->pathitem = (VOID *) + ( alignptr + (unsigned long) pool->alignbytes + - ( alignptr % (unsigned long) pool->alignbytes ) ); + /* Set the number of items left in the current block. */ + pool->pathitemsleft = pool->itemsperblock; } /*****************************************************************************/ @@ -3385,38 +3407,39 @@ struct memorypool *pool; /* */ /*****************************************************************************/ -VOID *traverse(pool) +VOID *traverse( pool ) struct memorypool *pool; { - VOID *newitem; - unsigned long alignptr; - - /* Stop upon exhausting the list of items. */ - if (pool->pathitem == pool->nextitem) { - return (VOID *) NULL; - } - /* Check whether any untraversed items remain in the current block. */ - if (pool->pathitemsleft == 0) { - /* Find the next block. */ - pool->pathblock = (VOID **) *(pool->pathblock); - /* Find the first item in the block. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->pathblock + 1); - /* Align with item on an `alignbytes'-byte boundary. */ - pool->pathitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* Set the number of items left in the current block. */ - pool->pathitemsleft = pool->itemsperblock; - } - newitem = pool->pathitem; - /* Find the next item in the block. */ - if (pool->itemwordtype == POINTER) { - pool->pathitem = (VOID *) ((VOID **) pool->pathitem + pool->itemwords); - } else { - pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords); - } - pool->pathitemsleft--; - return newitem; + VOID *newitem; + unsigned long alignptr; + + /* Stop upon exhausting the list of items. */ + if ( pool->pathitem == pool->nextitem ) { + return (VOID *) NULL; + } + /* Check whether any untraversed items remain in the current block. */ + if ( pool->pathitemsleft == 0 ) { + /* Find the next block. */ + pool->pathblock = (VOID **) *( pool->pathblock ); + /* Find the first item in the block. Increment by the size of (VOID *). */ + alignptr = (unsigned long) ( pool->pathblock + 1 ); + /* Align with item on an `alignbytes'-byte boundary. */ + pool->pathitem = (VOID *) + ( alignptr + (unsigned long) pool->alignbytes + - ( alignptr % (unsigned long) pool->alignbytes ) ); + /* Set the number of items left in the current block. */ + pool->pathitemsleft = pool->itemsperblock; + } + newitem = pool->pathitem; + /* Find the next item in the block. */ + if ( pool->itemwordtype == POINTER ) { + pool->pathitem = (VOID *) ( (VOID **) pool->pathitem + pool->itemwords ); + } + else { + pool->pathitem = (VOID *) ( (REAL *) pool->pathitem + pool->itemwords ); + } + pool->pathitemsleft--; + return newitem; } /*****************************************************************************/ @@ -3436,77 +3459,77 @@ struct memorypool *pool; /* */ /*****************************************************************************/ -void dummyinit(trianglewords, shellewords) +void dummyinit( trianglewords, shellewords ) int trianglewords; int shellewords; { - unsigned long alignptr; - - /* `triwords' and `shwords' are used by the mesh manipulation primitives */ - /* to extract orientations of triangles and shell edges from pointers. */ - triwords = trianglewords; /* Initialize `triwords' once and for all. */ - shwords = shellewords; /* Initialize `shwords' once and for all. */ - - /* Set up `dummytri', the `triangle' that occupies "outer space". */ - dummytribase = (triangle *) malloc(triwords * sizeof(triangle) - + triangles.alignbytes); - if (dummytribase == (triangle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */ - alignptr = (unsigned long) dummytribase; - dummytri = (triangle *) - (alignptr + (unsigned long) triangles.alignbytes - - (alignptr % (unsigned long) triangles.alignbytes)); - /* Initialize the three adjoining triangles to be "outer space". These */ - /* will eventually be changed by various bonding operations, but their */ - /* values don't really matter, as long as they can legally be */ - /* dereferenced. */ - dummytri[0] = (triangle) dummytri; - dummytri[1] = (triangle) dummytri; - dummytri[2] = (triangle) dummytri; - /* Three NULL vertex points. */ - dummytri[3] = (triangle) NULL; - dummytri[4] = (triangle) NULL; - dummytri[5] = (triangle) NULL; - - if (useshelles) { - /* Set up `dummysh', the omnipresent "shell edge" pointed to by any */ - /* triangle side or shell edge end that isn't attached to a real shell */ - /* edge. */ - dummyshbase = (shelle *) malloc(shwords * sizeof(shelle) - + shelles.alignbytes); - if (dummyshbase == (shelle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */ - alignptr = (unsigned long) dummyshbase; - dummysh = (shelle *) - (alignptr + (unsigned long) shelles.alignbytes - - (alignptr % (unsigned long) shelles.alignbytes)); - /* Initialize the two adjoining shell edges to be the omnipresent shell */ - /* edge. These will eventually be changed by various bonding */ - /* operations, but their values don't really matter, as long as they */ - /* can legally be dereferenced. */ - dummysh[0] = (shelle) dummysh; - dummysh[1] = (shelle) dummysh; - /* Two NULL vertex points. */ - dummysh[2] = (shelle) NULL; - dummysh[3] = (shelle) NULL; - /* Initialize the two adjoining triangles to be "outer space". */ - dummysh[4] = (shelle) dummytri; - dummysh[5] = (shelle) dummytri; - /* Set the boundary marker to zero. */ - * (int *) (dummysh + 6) = 0; - - /* Initialize the three adjoining shell edges of `dummytri' to be */ - /* the omnipresent shell edge. */ - dummytri[6] = (triangle) dummysh; - dummytri[7] = (triangle) dummysh; - dummytri[8] = (triangle) dummysh; - } + unsigned long alignptr; + + /* `triwords' and `shwords' are used by the mesh manipulation primitives */ + /* to extract orientations of triangles and shell edges from pointers. */ + triwords = trianglewords; /* Initialize `triwords' once and for all. */ + shwords = shellewords; /* Initialize `shwords' once and for all. */ + + /* Set up `dummytri', the `triangle' that occupies "outer space". */ + dummytribase = (triangle *) malloc( triwords * sizeof( triangle ) + + triangles.alignbytes ); + if ( dummytribase == (triangle *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */ + alignptr = (unsigned long) dummytribase; + dummytri = (triangle *) + ( alignptr + (unsigned long) triangles.alignbytes + - ( alignptr % (unsigned long) triangles.alignbytes ) ); + /* Initialize the three adjoining triangles to be "outer space". These */ + /* will eventually be changed by various bonding operations, but their */ + /* values don't really matter, as long as they can legally be */ + /* dereferenced. */ + dummytri[0] = (triangle) dummytri; + dummytri[1] = (triangle) dummytri; + dummytri[2] = (triangle) dummytri; + /* Three NULL vertex points. */ + dummytri[3] = (triangle) NULL; + dummytri[4] = (triangle) NULL; + dummytri[5] = (triangle) NULL; + + if ( useshelles ) { + /* Set up `dummysh', the omnipresent "shell edge" pointed to by any */ + /* triangle side or shell edge end that isn't attached to a real shell */ + /* edge. */ + dummyshbase = (shelle *) malloc( shwords * sizeof( shelle ) + + shelles.alignbytes ); + if ( dummyshbase == (shelle *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */ + alignptr = (unsigned long) dummyshbase; + dummysh = (shelle *) + ( alignptr + (unsigned long) shelles.alignbytes + - ( alignptr % (unsigned long) shelles.alignbytes ) ); + /* Initialize the two adjoining shell edges to be the omnipresent shell */ + /* edge. These will eventually be changed by various bonding */ + /* operations, but their values don't really matter, as long as they */ + /* can legally be dereferenced. */ + dummysh[0] = (shelle) dummysh; + dummysh[1] = (shelle) dummysh; + /* Two NULL vertex points. */ + dummysh[2] = (shelle) NULL; + dummysh[3] = (shelle) NULL; + /* Initialize the two adjoining triangles to be "outer space". */ + dummysh[4] = (shelle) dummytri; + dummysh[5] = (shelle) dummytri; + /* Set the boundary marker to zero. */ + *(int *) ( dummysh + 6 ) = 0; + + /* Initialize the three adjoining shell edges of `dummytri' to be */ + /* the omnipresent shell edge. */ + dummytri[6] = (triangle) dummysh; + dummytri[7] = (triangle) dummysh; + dummytri[8] = (triangle) dummysh; + } } /*****************************************************************************/ @@ -3519,24 +3542,23 @@ int shellewords; /* */ /*****************************************************************************/ -void initializepointpool() -{ - int pointsize; - - /* The index within each point at which the boundary marker is found. */ - /* Ensure the point marker is aligned to a sizeof(int)-byte address. */ - pointmarkindex = ((mesh_dim + nextras) * sizeof(REAL) + sizeof(int) - 1) - / sizeof(int); - pointsize = (pointmarkindex + 1) * sizeof(int); - if (poly) { - /* The index within each point at which a triangle pointer is found. */ - /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */ - point2triindex = (pointsize + sizeof(triangle) - 1) / sizeof(triangle); - pointsize = (point2triindex + 1) * sizeof(triangle); - } - /* Initialize the pool of points. */ - poolinit(&points, pointsize, POINTPERBLOCK, - (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0); +void initializepointpool(){ + int pointsize; + + /* The index within each point at which the boundary marker is found. */ + /* Ensure the point marker is aligned to a sizeof(int)-byte address. */ + pointmarkindex = ( ( mesh_dim + nextras ) * sizeof( REAL ) + sizeof( int ) - 1 ) + / sizeof( int ); + pointsize = ( pointmarkindex + 1 ) * sizeof( int ); + if ( poly ) { + /* The index within each point at which a triangle pointer is found. */ + /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */ + point2triindex = ( pointsize + sizeof( triangle ) - 1 ) / sizeof( triangle ); + pointsize = ( point2triindex + 1 ) * sizeof( triangle ); + } + /* Initialize the pool of points. */ + poolinit( &points, pointsize, POINTPERBLOCK, + ( sizeof( REAL ) >= sizeof( triangle ) ) ? FLOATINGPOINT : POINTER, 0 ); } /*****************************************************************************/ @@ -3550,54 +3572,55 @@ void initializepointpool() /* */ /*****************************************************************************/ -void initializetrisegpools() -{ - int trisize; - - /* The index within each triangle at which the extra nodes (above three) */ - /* associated with high order elements are found. There are three */ - /* pointers to other triangles, three pointers to corners, and possibly */ - /* three pointers to shell edges before the extra nodes. */ - highorderindex = 6 + (useshelles * 3); - /* The number of bytes occupied by a triangle. */ - trisize = ((order + 1) * (order + 2) / 2 + (highorderindex - 3)) * - sizeof(triangle); - /* The index within each triangle at which its attributes are found, */ - /* where the index is measured in REALs. */ - elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL); - /* The index within each triangle at which the maximum area constraint */ - /* is found, where the index is measured in REALs. Note that if the */ - /* `regionattrib' flag is set, an additional attribute will be added. */ - areaboundindex = elemattribindex + eextras + regionattrib; - /* If triangle attributes or an area bound are needed, increase the number */ - /* of bytes occupied by a triangle. */ - if (vararea) { - trisize = (areaboundindex + 1) * sizeof(REAL); - } else if (eextras + regionattrib > 0) { - trisize = areaboundindex * sizeof(REAL); - } - /* If a Voronoi diagram or triangle neighbor graph is requested, make */ - /* sure there's room to store an integer index in each triangle. This */ - /* integer index can occupy the same space as the shell edges or */ - /* attributes or area constraint or extra nodes. */ - if ((voronoi || neighbors) && - (trisize < 6 * sizeof(triangle) + sizeof(int))) { - trisize = 6 * sizeof(triangle) + sizeof(int); - } - /* Having determined the memory size of a triangle, initialize the pool. */ - poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4); - - if (useshelles) { - /* Initialize the pool of shell edges. */ - poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK, - POINTER, 4); - - /* Initialize the "outer space" triangle and omnipresent shell edge. */ - dummyinit(triangles.itemwords, shelles.itemwords); - } else { - /* Initialize the "outer space" triangle. */ - dummyinit(triangles.itemwords, 0); - } +void initializetrisegpools(){ + int trisize; + + /* The index within each triangle at which the extra nodes (above three) */ + /* associated with high order elements are found. There are three */ + /* pointers to other triangles, three pointers to corners, and possibly */ + /* three pointers to shell edges before the extra nodes. */ + highorderindex = 6 + ( useshelles * 3 ); + /* The number of bytes occupied by a triangle. */ + trisize = ( ( order + 1 ) * ( order + 2 ) / 2 + ( highorderindex - 3 ) ) * + sizeof( triangle ); + /* The index within each triangle at which its attributes are found, */ + /* where the index is measured in REALs. */ + elemattribindex = ( trisize + sizeof( REAL ) - 1 ) / sizeof( REAL ); + /* The index within each triangle at which the maximum area constraint */ + /* is found, where the index is measured in REALs. Note that if the */ + /* `regionattrib' flag is set, an additional attribute will be added. */ + areaboundindex = elemattribindex + eextras + regionattrib; + /* If triangle attributes or an area bound are needed, increase the number */ + /* of bytes occupied by a triangle. */ + if ( vararea ) { + trisize = ( areaboundindex + 1 ) * sizeof( REAL ); + } + else if ( eextras + regionattrib > 0 ) { + trisize = areaboundindex * sizeof( REAL ); + } + /* If a Voronoi diagram or triangle neighbor graph is requested, make */ + /* sure there's room to store an integer index in each triangle. This */ + /* integer index can occupy the same space as the shell edges or */ + /* attributes or area constraint or extra nodes. */ + if ( ( voronoi || neighbors ) && + ( trisize < 6 * sizeof( triangle ) + sizeof( int ) ) ) { + trisize = 6 * sizeof( triangle ) + sizeof( int ); + } + /* Having determined the memory size of a triangle, initialize the pool. */ + poolinit( &triangles, trisize, TRIPERBLOCK, POINTER, 4 ); + + if ( useshelles ) { + /* Initialize the pool of shell edges. */ + poolinit( &shelles, 6 * sizeof( triangle ) + sizeof( int ), SHELLEPERBLOCK, + POINTER, 4 ); + + /* Initialize the "outer space" triangle and omnipresent shell edge. */ + dummyinit( triangles.itemwords, shelles.itemwords ); + } + else { + /* Initialize the "outer space" triangle. */ + dummyinit( triangles.itemwords, 0 ); + } } /*****************************************************************************/ @@ -3606,15 +3629,15 @@ void initializetrisegpools() /* */ /*****************************************************************************/ -void triangledealloc(dyingtriangle) -triangle *dyingtriangle; +void triangledealloc( dyingtriangle ) +triangle * dyingtriangle; { - /* Set triangle's vertices to NULL. This makes it possible to */ - /* detect dead triangles when traversing the list of all triangles. */ - dyingtriangle[3] = (triangle) NULL; - dyingtriangle[4] = (triangle) NULL; - dyingtriangle[5] = (triangle) NULL; - pooldealloc(&triangles, (VOID *) dyingtriangle); + /* Set triangle's vertices to NULL. This makes it possible to */ + /* detect dead triangles when traversing the list of all triangles. */ + dyingtriangle[3] = (triangle) NULL; + dyingtriangle[4] = (triangle) NULL; + dyingtriangle[5] = (triangle) NULL; + pooldealloc( &triangles, (VOID *) dyingtriangle ); } /*****************************************************************************/ @@ -3623,17 +3646,16 @@ triangle *dyingtriangle; /* */ /*****************************************************************************/ -triangle *triangletraverse() -{ - triangle *newtriangle; - - do { - newtriangle = (triangle *) traverse(&triangles); - if (newtriangle == (triangle *) NULL) { - return (triangle *) NULL; - } - } while (newtriangle[3] == (triangle) NULL); /* Skip dead ones. */ - return newtriangle; +triangle *triangletraverse(){ + triangle *newtriangle; + + do { + newtriangle = (triangle *) traverse( &triangles ); + if ( newtriangle == (triangle *) NULL ) { + return (triangle *) NULL; + } + } while ( newtriangle[3] == (triangle) NULL ); /* Skip dead ones. */ + return newtriangle; } /*****************************************************************************/ @@ -3642,14 +3664,14 @@ triangle *triangletraverse() /* */ /*****************************************************************************/ -void shelledealloc(dyingshelle) -shelle *dyingshelle; +void shelledealloc( dyingshelle ) +shelle * dyingshelle; { - /* Set shell edge's vertices to NULL. This makes it possible to */ - /* detect dead shells when traversing the list of all shells. */ - dyingshelle[2] = (shelle) NULL; - dyingshelle[3] = (shelle) NULL; - pooldealloc(&shelles, (VOID *) dyingshelle); + /* Set shell edge's vertices to NULL. This makes it possible to */ + /* detect dead shells when traversing the list of all shells. */ + dyingshelle[2] = (shelle) NULL; + dyingshelle[3] = (shelle) NULL; + pooldealloc( &shelles, (VOID *) dyingshelle ); } /*****************************************************************************/ @@ -3658,17 +3680,16 @@ shelle *dyingshelle; /* */ /*****************************************************************************/ -shelle *shelletraverse() -{ - shelle *newshelle; - - do { - newshelle = (shelle *) traverse(&shelles); - if (newshelle == (shelle *) NULL) { - return (shelle *) NULL; - } - } while (newshelle[2] == (shelle) NULL); /* Skip dead ones. */ - return newshelle; +shelle *shelletraverse(){ + shelle *newshelle; + + do { + newshelle = (shelle *) traverse( &shelles ); + if ( newshelle == (shelle *) NULL ) { + return (shelle *) NULL; + } + } while ( newshelle[2] == (shelle) NULL ); /* Skip dead ones. */ + return newshelle; } /*****************************************************************************/ @@ -3677,13 +3698,13 @@ shelle *shelletraverse() /* */ /*****************************************************************************/ -void pointdealloc(dyingpoint) +void pointdealloc( dyingpoint ) point dyingpoint; { - /* Mark the point as dead. This makes it possible to detect dead points */ - /* when traversing the list of all points. */ - setpointmark(dyingpoint, DEADPOINT); - pooldealloc(&points, (VOID *) dyingpoint); + /* Mark the point as dead. This makes it possible to detect dead points */ + /* when traversing the list of all points. */ + setpointmark( dyingpoint, DEADPOINT ); + pooldealloc( &points, (VOID *) dyingpoint ); } /*****************************************************************************/ @@ -3692,17 +3713,16 @@ point dyingpoint; /* */ /*****************************************************************************/ -point pointtraverse() -{ - point newpoint; - - do { - newpoint = (point) traverse(&points); - if (newpoint == (point) NULL) { - return (point) NULL; - } - } while (pointmark(newpoint) == DEADPOINT); /* Skip dead ones. */ - return newpoint; +point pointtraverse(){ + point newpoint; + + do { + newpoint = (point) traverse( &points ); + if ( newpoint == (point) NULL ) { + return (point) NULL; + } + } while ( pointmark( newpoint ) == DEADPOINT ); /* Skip dead ones. */ + return newpoint; } /*****************************************************************************/ @@ -3714,13 +3734,13 @@ point pointtraverse() #ifndef CDT_ONLY -void badsegmentdealloc(dyingseg) +void badsegmentdealloc( dyingseg ) struct edge *dyingseg; { - /* Set segment's orientation to -1. This makes it possible to */ - /* detect dead segments when traversing the list of all segments. */ - dyingseg->shorient = -1; - pooldealloc(&badsegments, (VOID *) dyingseg); + /* Set segment's orientation to -1. This makes it possible to */ + /* detect dead segments when traversing the list of all segments. */ + dyingseg->shorient = -1; + pooldealloc( &badsegments, (VOID *) dyingseg ); } #endif /* not CDT_ONLY */ @@ -3733,17 +3753,16 @@ struct edge *dyingseg; #ifndef CDT_ONLY -struct edge *badsegmenttraverse() -{ - struct edge *newseg; - - do { - newseg = (struct edge *) traverse(&badsegments); - if (newseg == (struct edge *) NULL) { - return (struct edge *) NULL; - } - } while (newseg->shorient == -1); /* Skip dead ones. */ - return newseg; +struct edge *badsegmenttraverse(){ + struct edge *newseg; + + do { + newseg = (struct edge *) traverse( &badsegments ); + if ( newseg == (struct edge *) NULL ) { + return (struct edge *) NULL; + } + } while ( newseg->shorient == -1 ); /* Skip dead ones. */ + return newseg; } #endif /* not CDT_ONLY */ @@ -3760,30 +3779,30 @@ struct edge *badsegmenttraverse() /* */ /*****************************************************************************/ -point getpoint(number) +point getpoint( number ) int number; { - VOID **getblock; - point foundpoint; - unsigned long alignptr; - int current; - - getblock = points.firstblock; - current = firstnumber; - /* Find the right block. */ - while (current + points.itemsperblock <= number) { - getblock = (VOID **) *getblock; - current += points.itemsperblock; - } - /* Now find the right point. */ - alignptr = (unsigned long) (getblock + 1); - foundpoint = (point) (alignptr + (unsigned long) points.alignbytes - - (alignptr % (unsigned long) points.alignbytes)); - while (current < number) { - foundpoint += points.itemwords; - current++; - } - return foundpoint; + VOID **getblock; + point foundpoint; + unsigned long alignptr; + int current; + + getblock = points.firstblock; + current = firstnumber; + /* Find the right block. */ + while ( current + points.itemsperblock <= number ) { + getblock = (VOID **) *getblock; + current += points.itemsperblock; + } + /* Now find the right point. */ + alignptr = (unsigned long) ( getblock + 1 ); + foundpoint = (point) ( alignptr + (unsigned long) points.alignbytes + - ( alignptr % (unsigned long) points.alignbytes ) ); + while ( current < number ) { + foundpoint += points.itemwords; + current++; + } + return foundpoint; } /*****************************************************************************/ @@ -3792,22 +3811,21 @@ int number; /* */ /*****************************************************************************/ -void triangledeinit() -{ - pooldeinit(&triangles); - free(dummytribase); - if (useshelles) { - pooldeinit(&shelles); - free(dummyshbase); - } - pooldeinit(&points); +void triangledeinit(){ + pooldeinit( &triangles ); + free( dummytribase ); + if ( useshelles ) { + pooldeinit( &shelles ); + free( dummyshbase ); + } + pooldeinit( &points ); #ifndef CDT_ONLY - if (quality) { - pooldeinit(&badsegments); - if ((minangle > 0.0) || vararea || fixedarea) { - pooldeinit(&badtriangles); - } - } + if ( quality ) { + pooldeinit( &badsegments ); + if ( ( minangle > 0.0 ) || vararea || fixedarea ) { + pooldeinit( &badtriangles ); + } + } #endif /* not CDT_ONLY */ } @@ -3825,35 +3843,35 @@ void triangledeinit() /* */ /*****************************************************************************/ -void maketriangle(newtriedge) +void maketriangle( newtriedge ) struct triedge *newtriedge; { - int i; - - newtriedge->tri = (triangle *) poolalloc(&triangles); - /* Initialize the three adjoining triangles to be "outer space". */ - newtriedge->tri[0] = (triangle) dummytri; - newtriedge->tri[1] = (triangle) dummytri; - newtriedge->tri[2] = (triangle) dummytri; - /* Three NULL vertex points. */ - newtriedge->tri[3] = (triangle) NULL; - newtriedge->tri[4] = (triangle) NULL; - newtriedge->tri[5] = (triangle) NULL; - /* Initialize the three adjoining shell edges to be the omnipresent */ - /* shell edge. */ - if (useshelles) { - newtriedge->tri[6] = (triangle) dummysh; - newtriedge->tri[7] = (triangle) dummysh; - newtriedge->tri[8] = (triangle) dummysh; - } - for (i = 0; i < eextras; i++) { - setelemattribute(*newtriedge, i, 0.0); - } - if (vararea) { - setareabound(*newtriedge, -1.0); - } - - newtriedge->orient = 0; + int i; + + newtriedge->tri = (triangle *) poolalloc( &triangles ); + /* Initialize the three adjoining triangles to be "outer space". */ + newtriedge->tri[0] = (triangle) dummytri; + newtriedge->tri[1] = (triangle) dummytri; + newtriedge->tri[2] = (triangle) dummytri; + /* Three NULL vertex points. */ + newtriedge->tri[3] = (triangle) NULL; + newtriedge->tri[4] = (triangle) NULL; + newtriedge->tri[5] = (triangle) NULL; + /* Initialize the three adjoining shell edges to be the omnipresent */ + /* shell edge. */ + if ( useshelles ) { + newtriedge->tri[6] = (triangle) dummysh; + newtriedge->tri[7] = (triangle) dummysh; + newtriedge->tri[8] = (triangle) dummysh; + } + for ( i = 0; i < eextras; i++ ) { + setelemattribute( *newtriedge, i, 0.0 ); + } + if ( vararea ) { + setareabound( *newtriedge, -1.0 ); + } + + newtriedge->orient = 0; } /*****************************************************************************/ @@ -3862,24 +3880,24 @@ struct triedge *newtriedge; /* */ /*****************************************************************************/ -void makeshelle(newedge) +void makeshelle( newedge ) struct edge *newedge; { - newedge->sh = (shelle *) poolalloc(&shelles); - /* Initialize the two adjoining shell edges to be the omnipresent */ - /* shell edge. */ - newedge->sh[0] = (shelle) dummysh; - newedge->sh[1] = (shelle) dummysh; - /* Two NULL vertex points. */ - newedge->sh[2] = (shelle) NULL; - newedge->sh[3] = (shelle) NULL; - /* Initialize the two adjoining triangles to be "outer space". */ - newedge->sh[4] = (shelle) dummytri; - newedge->sh[5] = (shelle) dummytri; - /* Set the boundary marker to zero. */ - setmark(*newedge, 0); - - newedge->shorient = 0; + newedge->sh = (shelle *) poolalloc( &shelles ); + /* Initialize the two adjoining shell edges to be the omnipresent */ + /* shell edge. */ + newedge->sh[0] = (shelle) dummysh; + newedge->sh[1] = (shelle) dummysh; + /* Two NULL vertex points. */ + newedge->sh[2] = (shelle) NULL; + newedge->sh[3] = (shelle) NULL; + /* Initialize the two adjoining triangles to be "outer space". */ + newedge->sh[4] = (shelle) dummytri; + newedge->sh[5] = (shelle) dummytri; + /* Set the boundary marker to zero. */ + setmark( *newedge, 0 ); + + newedge->shorient = 0; } /** **/ @@ -3900,7 +3918,7 @@ struct edge *newedge; /* which is disastrously slow. A faster way on IEEE machines might be to */ /* mask the appropriate bit, but that's difficult to do in C. */ -#define Absolute(a) ((a) >= 0.0 ? (a) : -(a)) +#define Absolute( a ) ( ( a ) >= 0.0 ? ( a ) : -( a ) ) /* #define Absolute(a) fabs(a) */ /* Many of the operations are broken up into two pieces, a main part that */ @@ -3916,95 +3934,95 @@ struct edge *newedge; /* The input parameter `x' (or the highest numbered `x_' parameter) must */ /* also be declared `INEXACT'. */ -#define Fast_Two_Sum_Tail(a, b, x, y) \ - bvirt = x - a; \ - y = b - bvirt - -#define Fast_Two_Sum(a, b, x, y) \ - x = (REAL) (a + b); \ - Fast_Two_Sum_Tail(a, b, x, y) - -#define Two_Sum_Tail(a, b, x, y) \ - bvirt = (REAL) (x - a); \ - avirt = x - bvirt; \ - bround = b - bvirt; \ - around = a - avirt; \ - y = around + bround - -#define Two_Sum(a, b, x, y) \ - x = (REAL) (a + b); \ - Two_Sum_Tail(a, b, x, y) - -#define Two_Diff_Tail(a, b, x, y) \ - bvirt = (REAL) (a - x); \ - avirt = x + bvirt; \ - bround = bvirt - b; \ - around = a - avirt; \ - y = around + bround - -#define Two_Diff(a, b, x, y) \ - x = (REAL) (a - b); \ - Two_Diff_Tail(a, b, x, y) - -#define Split(a, ahi, alo) \ - c = (REAL) (splitter * a); \ - abig = (REAL) (c - a); \ - ahi = (REAL)(c - abig); \ - alo = (REAL)(a - ahi) - -#define Two_Product_Tail(a, b, x, y) \ - Split(a, ahi, alo); \ - Split(b, bhi, blo); \ - err1 = x - (ahi * bhi); \ - err2 = err1 - (alo * bhi); \ - err3 = err2 - (ahi * blo); \ - y = (alo * blo) - err3 - -#define Two_Product(a, b, x, y) \ - x = (REAL) (a * b); \ - Two_Product_Tail(a, b, x, y) +#define Fast_Two_Sum_Tail( a, b, x, y ) \ + bvirt = x - a; \ + y = b - bvirt + +#define Fast_Two_Sum( a, b, x, y ) \ + x = (REAL) ( a + b ); \ + Fast_Two_Sum_Tail( a, b, x, y ) + +#define Two_Sum_Tail( a, b, x, y ) \ + bvirt = (REAL) ( x - a ); \ + avirt = x - bvirt; \ + bround = b - bvirt; \ + around = a - avirt; \ + y = around + bround + +#define Two_Sum( a, b, x, y ) \ + x = (REAL) ( a + b ); \ + Two_Sum_Tail( a, b, x, y ) + +#define Two_Diff_Tail( a, b, x, y ) \ + bvirt = (REAL) ( a - x ); \ + avirt = x + bvirt; \ + bround = bvirt - b; \ + around = a - avirt; \ + y = around + bround + +#define Two_Diff( a, b, x, y ) \ + x = (REAL) ( a - b ); \ + Two_Diff_Tail( a, b, x, y ) + +#define Split( a, ahi, alo ) \ + c = (REAL) ( splitter * a ); \ + abig = (REAL) ( c - a ); \ + ahi = (REAL)( c - abig ); \ + alo = (REAL)( a - ahi ) + +#define Two_Product_Tail( a, b, x, y ) \ + Split( a, ahi, alo ); \ + Split( b, bhi, blo ); \ + err1 = x - ( ahi * bhi ); \ + err2 = err1 - ( alo * bhi ); \ + err3 = err2 - ( ahi * blo ); \ + y = ( alo * blo ) - err3 + +#define Two_Product( a, b, x, y ) \ + x = (REAL) ( a * b ); \ + Two_Product_Tail( a, b, x, y ) /* Two_Product_Presplit() is Two_Product() where one of the inputs has */ /* already been split. Avoids redundant splitting. */ -#define Two_Product_Presplit(a, b, bhi, blo, x, y) \ - x = (REAL) (a * b); \ - Split(a, ahi, alo); \ - err1 = x - (ahi * bhi); \ - err2 = err1 - (alo * bhi); \ - err3 = err2 - (ahi * blo); \ - y = (alo * blo) - err3 +#define Two_Product_Presplit( a, b, bhi, blo, x, y ) \ + x = (REAL) ( a * b ); \ + Split( a, ahi, alo ); \ + err1 = x - ( ahi * bhi ); \ + err2 = err1 - ( alo * bhi ); \ + err3 = err2 - ( ahi * blo ); \ + y = ( alo * blo ) - err3 /* Square() can be done more quickly than Two_Product(). */ -#define Square_Tail(a, x, y) \ - Split(a, ahi, alo); \ - err1 = x - (ahi * ahi); \ - err3 = err1 - ((ahi + ahi) * alo); \ - y = (alo * alo) - err3 +#define Square_Tail( a, x, y ) \ + Split( a, ahi, alo ); \ + err1 = x - ( ahi * ahi ); \ + err3 = err1 - ( ( ahi + ahi ) * alo ); \ + y = ( alo * alo ) - err3 -#define Square(a, x, y) \ - x = (REAL) (a * a); \ - Square_Tail(a, x, y) +#define Square( a, x, y ) \ + x = (REAL) ( a * a ); \ + Square_Tail( a, x, y ) /* Macros for summing expansions of various fixed lengths. These are all */ /* unrolled versions of Expansion_Sum(). */ -#define Two_One_Sum(a1, a0, b, x2, x1, x0) \ - Two_Sum(a0, b , _i, x0); \ - Two_Sum(a1, _i, x2, x1) +#define Two_One_Sum( a1, a0, b, x2, x1, x0 ) \ + Two_Sum( a0, b, _i, x0 ); \ + Two_Sum( a1, _i, x2, x1 ) -#define Two_One_Diff(a1, a0, b, x2, x1, x0) \ - Two_Diff(a0, b , _i, x0); \ - Two_Sum( a1, _i, x2, x1) +#define Two_One_Diff( a1, a0, b, x2, x1, x0 ) \ + Two_Diff( a0, b, _i, x0 ); \ + Two_Sum( a1, _i, x2, x1 ) -#define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \ - Two_One_Sum(a1, a0, b0, _j, _0, x0); \ - Two_One_Sum(_j, _0, b1, x3, x2, x1) +#define Two_Two_Sum( a1, a0, b1, b0, x3, x2, x1, x0 ) \ + Two_One_Sum( a1, a0, b0, _j, _0, x0 ); \ + Two_One_Sum( _j, _0, b1, x3, x2, x1 ) -#define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \ - Two_One_Diff(a1, a0, b0, _j, _0, x0); \ - Two_One_Diff(_j, _0, b1, x3, x2, x1) +#define Two_Two_Diff( a1, a0, b1, b0, x3, x2, x1, x0 ) \ + Two_One_Diff( a1, a0, b0, _j, _0, x0 ); \ + Two_One_Diff( _j, _0, b1, x3, x2, x1 ) /*****************************************************************************/ /* */ @@ -4025,43 +4043,42 @@ struct edge *newedge; /* */ /*****************************************************************************/ -void exactinit() -{ - REAL half; - REAL check, lastcheck; - int every_other; - - every_other = 1; - half = 0.5; - epsilon = 1.0; - splitter = 1.0; - check = 1.0; - /* Repeatedly divide `epsilon' by two until it is too small to add to */ - /* one without causing roundoff. (Also check if the sum is equal to */ - /* the previous sum, for machines that round up instead of using exact */ - /* rounding. Not that these routines will work on such machines anyway. */ - do { - lastcheck = check; - epsilon *= half; - if (every_other) { - splitter *= 2.0; - } - every_other = !every_other; - check = (REAL)(1.0 + epsilon); - } while ((check != 1.0) && (check != lastcheck)); - splitter += 1.0; - if (verbose > 1) { - printf("Floating point roundoff is of magnitude %.17g\n", epsilon); - printf("Floating point splitter is %.17g\n", splitter); - } - /* Error bounds for orientation and incircle tests. */ - resulterrbound = (REAL)((3.0 + 8.0 * epsilon) * epsilon); - ccwerrboundA = (REAL)((3.0 + 16.0 * epsilon) * epsilon); - ccwerrboundB = (REAL)((2.0 + 12.0 * epsilon) * epsilon); - ccwerrboundC = (REAL)((9.0 + 64.0 * epsilon) * epsilon * epsilon); - iccerrboundA = (REAL)((10.0 + 96.0 * epsilon) * epsilon); - iccerrboundB = (REAL)((4.0 + 48.0 * epsilon) * epsilon); - iccerrboundC = (REAL)((44.0 + 576.0 * epsilon) * epsilon * epsilon); +void exactinit(){ + REAL half; + REAL check, lastcheck; + int every_other; + + every_other = 1; + half = 0.5; + epsilon = 1.0; + splitter = 1.0; + check = 1.0; + /* Repeatedly divide `epsilon' by two until it is too small to add to */ + /* one without causing roundoff. (Also check if the sum is equal to */ + /* the previous sum, for machines that round up instead of using exact */ + /* rounding. Not that these routines will work on such machines anyway. */ + do { + lastcheck = check; + epsilon *= half; + if ( every_other ) { + splitter *= 2.0; + } + every_other = !every_other; + check = (REAL)( 1.0 + epsilon ); + } while ( ( check != 1.0 ) && ( check != lastcheck ) ); + splitter += 1.0; + if ( verbose > 1 ) { + printf( "Floating point roundoff is of magnitude %.17g\n", epsilon ); + printf( "Floating point splitter is %.17g\n", splitter ); + } + /* Error bounds for orientation and incircle tests. */ + resulterrbound = (REAL)( ( 3.0 + 8.0 * epsilon ) * epsilon ); + ccwerrboundA = (REAL)( ( 3.0 + 16.0 * epsilon ) * epsilon ); + ccwerrboundB = (REAL)( ( 2.0 + 12.0 * epsilon ) * epsilon ); + ccwerrboundC = (REAL)( ( 9.0 + 64.0 * epsilon ) * epsilon * epsilon ); + iccerrboundA = (REAL)( ( 10.0 + 96.0 * epsilon ) * epsilon ); + iccerrboundB = (REAL)( ( 4.0 + 48.0 * epsilon ) * epsilon ); + iccerrboundC = (REAL)( ( 44.0 + 576.0 * epsilon ) * epsilon * epsilon ); } /*****************************************************************************/ @@ -4078,78 +4095,81 @@ void exactinit() /* */ /*****************************************************************************/ -int fast_expansion_sum_zeroelim(elen, e, flen, f, h) /* h cannot be e or f. */ +int fast_expansion_sum_zeroelim( elen, e, flen, f, h ) /* h cannot be e or f. */ int elen; REAL *e; int flen; REAL *f; REAL *h; { - REAL Q; - INEXACT REAL Qnew; - INEXACT REAL hh; - INEXACT REAL bvirt; - REAL avirt, bround, around; - int eindex, findex, hindex; - REAL enow, fnow; - - enow = e[0]; - fnow = f[0]; - eindex = findex = 0; - if ((fnow > enow) == (fnow > -enow)) { - Q = enow; - enow = e[++eindex]; - } else { - Q = fnow; - fnow = f[++findex]; - } - hindex = 0; - if ((eindex < elen) && (findex < flen)) { - if ((fnow > enow) == (fnow > -enow)) { - Fast_Two_Sum(enow, Q, Qnew, hh); - enow = e[++eindex]; - } else { - Fast_Two_Sum(fnow, Q, Qnew, hh); - fnow = f[++findex]; - } - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - while ((eindex < elen) && (findex < flen)) { - if ((fnow > enow) == (fnow > -enow)) { - Two_Sum(Q, enow, Qnew, hh); - enow = e[++eindex]; - } else { - Two_Sum(Q, fnow, Qnew, hh); - fnow = f[++findex]; - } - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - } - while (eindex < elen) { - Two_Sum(Q, enow, Qnew, hh); - enow = e[++eindex]; - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - while (findex < flen) { - Two_Sum(Q, fnow, Qnew, hh); - fnow = f[++findex]; - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - if ((Q != 0.0) || (hindex == 0)) { - h[hindex++] = Q; - } - return hindex; + REAL Q; + INEXACT REAL Qnew; + INEXACT REAL hh; + INEXACT REAL bvirt; + REAL avirt, bround, around; + int eindex, findex, hindex; + REAL enow, fnow; + + enow = e[0]; + fnow = f[0]; + eindex = findex = 0; + if ( ( fnow > enow ) == ( fnow > -enow ) ) { + Q = enow; + enow = e[++eindex]; + } + else { + Q = fnow; + fnow = f[++findex]; + } + hindex = 0; + if ( ( eindex < elen ) && ( findex < flen ) ) { + if ( ( fnow > enow ) == ( fnow > -enow ) ) { + Fast_Two_Sum( enow, Q, Qnew, hh ); + enow = e[++eindex]; + } + else { + Fast_Two_Sum( fnow, Q, Qnew, hh ); + fnow = f[++findex]; + } + Q = Qnew; + if ( hh != 0.0 ) { + h[hindex++] = hh; + } + while ( ( eindex < elen ) && ( findex < flen ) ) { + if ( ( fnow > enow ) == ( fnow > -enow ) ) { + Two_Sum( Q, enow, Qnew, hh ); + enow = e[++eindex]; + } + else { + Two_Sum( Q, fnow, Qnew, hh ); + fnow = f[++findex]; + } + Q = Qnew; + if ( hh != 0.0 ) { + h[hindex++] = hh; + } + } + } + while ( eindex < elen ) { + Two_Sum( Q, enow, Qnew, hh ); + enow = e[++eindex]; + Q = Qnew; + if ( hh != 0.0 ) { + h[hindex++] = hh; + } + } + while ( findex < flen ) { + Two_Sum( Q, fnow, Qnew, hh ); + fnow = f[++findex]; + Q = Qnew; + if ( hh != 0.0 ) { + h[hindex++] = hh; + } + } + if ( ( Q != 0.0 ) || ( hindex == 0 ) ) { + h[hindex++] = Q; + } + return hindex; } /*****************************************************************************/ @@ -4167,47 +4187,47 @@ REAL *h; /* */ /*****************************************************************************/ -int scale_expansion_zeroelim(elen, e, b, h) /* e and h cannot be the same. */ +int scale_expansion_zeroelim( elen, e, b, h ) /* e and h cannot be the same. */ int elen; REAL *e; REAL b; REAL *h; { - INEXACT REAL Q, sum; - REAL hh; - INEXACT REAL product1; - REAL product0; - int eindex, hindex; - REAL enow; - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - - Split(b, bhi, blo); - Two_Product_Presplit(e[0], b, bhi, blo, Q, hh); - hindex = 0; - if (hh != 0) { - h[hindex++] = hh; - } - for (eindex = 1; eindex < elen; eindex++) { - enow = e[eindex]; - Two_Product_Presplit(enow, b, bhi, blo, product1, product0); - Two_Sum(Q, product0, sum, hh); - if (hh != 0) { - h[hindex++] = hh; - } - Fast_Two_Sum(product1, sum, Q, hh); - if (hh != 0) { - h[hindex++] = hh; - } - } - if ((Q != 0.0) || (hindex == 0)) { - h[hindex++] = Q; - } - return hindex; + INEXACT REAL Q, sum; + REAL hh; + INEXACT REAL product1; + REAL product0; + int eindex, hindex; + REAL enow; + INEXACT REAL bvirt; + REAL avirt, bround, around; + INEXACT REAL c; + INEXACT REAL abig; + REAL ahi, alo, bhi, blo; + REAL err1, err2, err3; + + Split( b, bhi, blo ); + Two_Product_Presplit( e[0], b, bhi, blo, Q, hh ); + hindex = 0; + if ( hh != 0 ) { + h[hindex++] = hh; + } + for ( eindex = 1; eindex < elen; eindex++ ) { + enow = e[eindex]; + Two_Product_Presplit( enow, b, bhi, blo, product1, product0 ); + Two_Sum( Q, product0, sum, hh ); + if ( hh != 0 ) { + h[hindex++] = hh; + } + Fast_Two_Sum( product1, sum, Q, hh ); + if ( hh != 0 ) { + h[hindex++] = hh; + } + } + if ( ( Q != 0.0 ) || ( hindex == 0 ) ) { + h[hindex++] = Q; + } + return hindex; } /*****************************************************************************/ @@ -4218,18 +4238,18 @@ REAL *h; /* */ /*****************************************************************************/ -REAL estimate(elen, e) +REAL estimate( elen, e ) int elen; REAL *e; { - REAL Q; - int eindex; - - Q = e[0]; - for (eindex = 1; eindex < elen; eindex++) { - Q += e[eindex]; - } - return Q; + REAL Q; + int eindex; + + Q = e[0]; + for ( eindex = 1; eindex < elen; eindex++ ) { + Q += e[eindex]; + } + return Q; } /*****************************************************************************/ @@ -4252,130 +4272,134 @@ REAL *e; /* */ /*****************************************************************************/ -REAL counterclockwiseadapt(pa, pb, pc, detsum) +REAL counterclockwiseadapt( pa, pb, pc, detsum ) point pa; point pb; point pc; REAL detsum; { - INEXACT REAL acx, acy, bcx, bcy; - REAL acxtail, acytail, bcxtail, bcytail; - INEXACT REAL detleft, detright; - REAL detlefttail, detrighttail; - REAL det, errbound; - REAL B[4], C1[8], C2[12], D[16]; - INEXACT REAL B3; - int C1length, C2length, Dlength; - REAL u[4]; - INEXACT REAL u3; - INEXACT REAL s1, t1; - REAL s0, t0; - - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - INEXACT REAL _i, _j; - REAL _0; - - acx = (REAL) (pa[0] - pc[0]); - bcx = (REAL) (pb[0] - pc[0]); - acy = (REAL) (pa[1] - pc[1]); - bcy = (REAL) (pb[1] - pc[1]); - - Two_Product(acx, bcy, detleft, detlefttail); - Two_Product(acy, bcx, detright, detrighttail); - - Two_Two_Diff(detleft, detlefttail, detright, detrighttail, - B3, B[2], B[1], B[0]); - B[3] = B3; - - det = estimate(4, B); - errbound = (REAL)(ccwerrboundB * detsum); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Diff_Tail(pa[0], pc[0], acx, acxtail); - Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail); - Two_Diff_Tail(pa[1], pc[1], acy, acytail); - Two_Diff_Tail(pb[1], pc[1], bcy, bcytail); - - if ((acxtail == 0.0) && (acytail == 0.0) - && (bcxtail == 0.0) && (bcytail == 0.0)) { - return det; - } - - errbound = (REAL)(ccwerrboundC * detsum + resulterrbound * Absolute(det)); - det += (acx * bcytail + bcy * acxtail) - - (acy * bcxtail + bcx * acytail); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Product(acxtail, bcy, s1, s0); - Two_Product(acytail, bcx, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1); - - Two_Product(acx, bcytail, s1, s0); - Two_Product(acy, bcxtail, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2); - - Two_Product(acxtail, bcytail, s1, s0); - Two_Product(acytail, bcxtail, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D); - - return(D[Dlength - 1]); + INEXACT REAL acx, acy, bcx, bcy; + REAL acxtail, acytail, bcxtail, bcytail; + INEXACT REAL detleft, detright; + REAL detlefttail, detrighttail; + REAL det, errbound; + REAL B[4], C1[8], C2[12], D[16]; + INEXACT REAL B3; + int C1length, C2length, Dlength; + REAL u[4]; + INEXACT REAL u3; + INEXACT REAL s1, t1; + REAL s0, t0; + + INEXACT REAL bvirt; + REAL avirt, bround, around; + INEXACT REAL c; + INEXACT REAL abig; + REAL ahi, alo, bhi, blo; + REAL err1, err2, err3; + INEXACT REAL _i, _j; + REAL _0; + + acx = (REAL) ( pa[0] - pc[0] ); + bcx = (REAL) ( pb[0] - pc[0] ); + acy = (REAL) ( pa[1] - pc[1] ); + bcy = (REAL) ( pb[1] - pc[1] ); + + Two_Product( acx, bcy, detleft, detlefttail ); + Two_Product( acy, bcx, detright, detrighttail ); + + Two_Two_Diff( detleft, detlefttail, detright, detrighttail, + B3, B[2], B[1], B[0] ); + B[3] = B3; + + det = estimate( 4, B ); + errbound = (REAL)( ccwerrboundB * detsum ); + if ( ( det >= errbound ) || ( -det >= errbound ) ) { + return det; + } + + Two_Diff_Tail( pa[0], pc[0], acx, acxtail ); + Two_Diff_Tail( pb[0], pc[0], bcx, bcxtail ); + Two_Diff_Tail( pa[1], pc[1], acy, acytail ); + Two_Diff_Tail( pb[1], pc[1], bcy, bcytail ); + + if ( ( acxtail == 0.0 ) && ( acytail == 0.0 ) + && ( bcxtail == 0.0 ) && ( bcytail == 0.0 ) ) { + return det; + } + + errbound = (REAL)( ccwerrboundC * detsum + resulterrbound * Absolute( det ) ); + det += ( acx * bcytail + bcy * acxtail ) + - ( acy * bcxtail + bcx * acytail ); + if ( ( det >= errbound ) || ( -det >= errbound ) ) { + return det; + } + + Two_Product( acxtail, bcy, s1, s0 ); + Two_Product( acytail, bcx, t1, t0 ); + Two_Two_Diff( s1, s0, t1, t0, u3, u[2], u[1], u[0] ); + u[3] = u3; + C1length = fast_expansion_sum_zeroelim( 4, B, 4, u, C1 ); + + Two_Product( acx, bcytail, s1, s0 ); + Two_Product( acy, bcxtail, t1, t0 ); + Two_Two_Diff( s1, s0, t1, t0, u3, u[2], u[1], u[0] ); + u[3] = u3; + C2length = fast_expansion_sum_zeroelim( C1length, C1, 4, u, C2 ); + + Two_Product( acxtail, bcytail, s1, s0 ); + Two_Product( acytail, bcxtail, t1, t0 ); + Two_Two_Diff( s1, s0, t1, t0, u3, u[2], u[1], u[0] ); + u[3] = u3; + Dlength = fast_expansion_sum_zeroelim( C2length, C2, 4, u, D ); + + return( D[Dlength - 1] ); } -REAL counterclockwise(pa, pb, pc) +REAL counterclockwise( pa, pb, pc ) point pa; point pb; point pc; { - REAL detleft, detright, det; - REAL detsum, errbound; - - counterclockcount++; - - detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]); - detright = (pa[1] - pc[1]) * (pb[0] - pc[0]); - det = detleft - detright; - - if (noexact) { - return det; - } - - if (detleft > 0.0) { - if (detright <= 0.0) { - return det; - } else { - detsum = detleft + detright; - } - } else if (detleft < 0.0) { - if (detright >= 0.0) { - return det; - } else { - detsum = -detleft - detright; - } - } else { - return det; - } - - errbound = ccwerrboundA * detsum; - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - return counterclockwiseadapt(pa, pb, pc, detsum); + REAL detleft, detright, det; + REAL detsum, errbound; + + counterclockcount++; + + detleft = ( pa[0] - pc[0] ) * ( pb[1] - pc[1] ); + detright = ( pa[1] - pc[1] ) * ( pb[0] - pc[0] ); + det = detleft - detright; + + if ( noexact ) { + return det; + } + + if ( detleft > 0.0 ) { + if ( detright <= 0.0 ) { + return det; + } + else { + detsum = detleft + detright; + } + } + else if ( detleft < 0.0 ) { + if ( detright >= 0.0 ) { + return det; + } + else { + detsum = -detleft - detright; + } + } + else { + return det; + } + + errbound = ccwerrboundA * detsum; + if ( ( det >= errbound ) || ( -det >= errbound ) ) { + return det; + } + + return counterclockwiseadapt( pa, pb, pc, detsum ); } /*****************************************************************************/ @@ -4397,630 +4421,633 @@ point pc; /* */ /*****************************************************************************/ -REAL incircleadapt(pa, pb, pc, pd, permanent) +REAL incircleadapt( pa, pb, pc, pd, permanent ) point pa; point pb; point pc; point pd; REAL permanent; { - INEXACT REAL adx, bdx, cdx, ady, bdy, cdy; - REAL det, errbound; - - INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1; - REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0; - REAL bc[4], ca[4], ab[4]; - INEXACT REAL bc3, ca3, ab3; - REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32]; - int axbclen, axxbclen, aybclen, ayybclen, alen; - REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32]; - int bxcalen, bxxcalen, bycalen, byycalen, blen; - REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32]; - int cxablen, cxxablen, cyablen, cyyablen, clen; - REAL abdet[64]; - int ablen; - REAL fin1[1152], fin2[1152]; - REAL *finnow, *finother, *finswap; - int finlength; - - REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; - INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1; - REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0; - REAL aa[4], bb[4], cc[4]; - INEXACT REAL aa3, bb3, cc3; - INEXACT REAL ti1, tj1; - REAL ti0, tj0; - REAL u[4], v[4]; - INEXACT REAL u3, v3; - REAL temp8[8], temp16a[16], temp16b[16], temp16c[16]; - REAL temp32a[32], temp32b[32], temp48[48], temp64[64]; - int temp8len, temp16alen, temp16blen, temp16clen; - int temp32alen, temp32blen, temp48len, temp64len; - REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8]; - int axtbblen, axtcclen, aytbblen, aytcclen; - REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8]; - int bxtaalen, bxtcclen, bytaalen, bytcclen; - REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8]; - int cxtaalen, cxtbblen, cytaalen, cytbblen; - REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8]; - int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; - REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16]; - int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen; - REAL axtbctt[8], aytbctt[8], bxtcatt[8]; - REAL bytcatt[8], cxtabtt[8], cytabtt[8]; - int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen; - REAL abt[8], bct[8], cat[8]; - int abtlen, bctlen, catlen; - REAL abtt[4], bctt[4], catt[4]; - int abttlen, bcttlen, cattlen; - INEXACT REAL abtt3, bctt3, catt3; - REAL negate; - - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - INEXACT REAL _i, _j; - REAL _0; - - adx = (REAL) (pa[0] - pd[0]); - bdx = (REAL) (pb[0] - pd[0]); - cdx = (REAL) (pc[0] - pd[0]); - ady = (REAL) (pa[1] - pd[1]); - bdy = (REAL) (pb[1] - pd[1]); - cdy = (REAL) (pc[1] - pd[1]); - - Two_Product(bdx, cdy, bdxcdy1, bdxcdy0); - Two_Product(cdx, bdy, cdxbdy1, cdxbdy0); - Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]); - bc[3] = bc3; - axbclen = scale_expansion_zeroelim(4, bc, adx, axbc); - axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc); - aybclen = scale_expansion_zeroelim(4, bc, ady, aybc); - ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc); - alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet); - - Two_Product(cdx, ady, cdxady1, cdxady0); - Two_Product(adx, cdy, adxcdy1, adxcdy0); - Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]); - ca[3] = ca3; - bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca); - bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca); - bycalen = scale_expansion_zeroelim(4, ca, bdy, byca); - byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca); - blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet); - - Two_Product(adx, bdy, adxbdy1, adxbdy0); - Two_Product(bdx, ady, bdxady1, bdxady0); - Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]); - ab[3] = ab3; - cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab); - cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab); - cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab); - cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab); - clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet); - - ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet); - finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1); - - det = estimate(finlength, fin1); - errbound = (REAL)(iccerrboundB * permanent); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Diff_Tail(pa[0], pd[0], adx, adxtail); - Two_Diff_Tail(pa[1], pd[1], ady, adytail); - Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail); - Two_Diff_Tail(pb[1], pd[1], bdy, bdytail); - Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail); - Two_Diff_Tail(pc[1], pd[1], cdy, cdytail); - if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) - && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) { - return det; - } - - errbound = (REAL)(iccerrboundC * permanent + resulterrbound * Absolute(det)); - det += (REAL)(((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - - (bdy * cdxtail + cdx * bdytail)) - + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) - + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - - (cdy * adxtail + adx * cdytail)) - + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) - + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - - (ady * bdxtail + bdx * adytail)) - + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx))); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - finnow = fin1; - finother = fin2; - - if ((bdxtail != 0.0) || (bdytail != 0.0) - || (cdxtail != 0.0) || (cdytail != 0.0)) { - Square(adx, adxadx1, adxadx0); - Square(ady, adyady1, adyady0); - Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]); - aa[3] = aa3; - } - if ((cdxtail != 0.0) || (cdytail != 0.0) - || (adxtail != 0.0) || (adytail != 0.0)) { - Square(bdx, bdxbdx1, bdxbdx0); - Square(bdy, bdybdy1, bdybdy0); - Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]); - bb[3] = bb3; - } - if ((adxtail != 0.0) || (adytail != 0.0) - || (bdxtail != 0.0) || (bdytail != 0.0)) { - Square(cdx, cdxcdx1, cdxcdx0); - Square(cdy, cdycdy1, cdycdy0); - Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]); - cc[3] = cc3; - } - - if (adxtail != 0.0) { - axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc); - temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx, - temp16a); - - axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc); - temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b); - - axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb); - temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc); - temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady, - temp16a); - - aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb); - temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b); - - aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc); - temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdxtail != 0.0) { - bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca); - temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx, - temp16a); - - bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa); - temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b); - - bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc); - temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca); - temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy, - temp16a); - - bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc); - temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b); - - bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa); - temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdxtail != 0.0) { - cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab); - temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx, - temp16a); - - cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb); - temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b); - - cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa); - temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab); - temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy, - temp16a); - - cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa); - temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b); - - cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb); - temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - if ((adxtail != 0.0) || (adytail != 0.0)) { - if ((bdxtail != 0.0) || (bdytail != 0.0) - || (cdxtail != 0.0) || (cdytail != 0.0)) { - Two_Product(bdxtail, cdy, ti1, ti0); - Two_Product(bdx, cdytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -bdy; - Two_Product(cdxtail, negate, ti1, ti0); - negate = -bdytail; - Two_Product(cdx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct); - - Two_Product(bdxtail, cdytail, ti1, ti0); - Two_Product(cdxtail, bdytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]); - bctt[3] = bctt3; - bcttlen = 4; - } else { - bct[0] = 0.0; - bctlen = 1; - bctt[0] = 0.0; - bcttlen = 1; - } - - if (adxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a); - axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct); - temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (bdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail, - temp32a); - axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt); - temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx, - temp16a); - temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a); - aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct); - temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail, - temp32a); - aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt); - temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady, - temp16a); - temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - if ((bdxtail != 0.0) || (bdytail != 0.0)) { - if ((cdxtail != 0.0) || (cdytail != 0.0) - || (adxtail != 0.0) || (adytail != 0.0)) { - Two_Product(cdxtail, ady, ti1, ti0); - Two_Product(cdx, adytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -cdy; - Two_Product(adxtail, negate, ti1, ti0); - negate = -cdytail; - Two_Product(adx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat); - - Two_Product(cdxtail, adytail, ti1, ti0); - Two_Product(adxtail, cdytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]); - catt[3] = catt3; - cattlen = 4; - } else { - cat[0] = 0.0; - catlen = 1; - catt[0] = 0.0; - cattlen = 1; - } - - if (bdxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a); - bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat); - temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (cdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail, - temp32a); - bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt); - temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx, - temp16a); - temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a); - bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat); - temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail, - temp32a); - bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt); - temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy, - temp16a); - temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - if ((cdxtail != 0.0) || (cdytail != 0.0)) { - if ((adxtail != 0.0) || (adytail != 0.0) - || (bdxtail != 0.0) || (bdytail != 0.0)) { - Two_Product(adxtail, bdy, ti1, ti0); - Two_Product(adx, bdytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -ady; - Two_Product(bdxtail, negate, ti1, ti0); - negate = -adytail; - Two_Product(bdx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt); - - Two_Product(adxtail, bdytail, ti1, ti0); - Two_Product(bdxtail, adytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]); - abtt[3] = abtt3; - abttlen = 4; - } else { - abt[0] = 0.0; - abtlen = 1; - abtt[0] = 0.0; - abttlen = 1; - } - - if (cdxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a); - cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt); - temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (adytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail, - temp32a); - cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt); - temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx, - temp16a); - temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a); - cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt); - temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail, - temp32a); - cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt); - temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy, - temp16a); - temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - - return finnow[finlength - 1]; + INEXACT REAL adx, bdx, cdx, ady, bdy, cdy; + REAL det, errbound; + + INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1; + REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0; + REAL bc[4], ca[4], ab[4]; + INEXACT REAL bc3, ca3, ab3; + REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32]; + int axbclen, axxbclen, aybclen, ayybclen, alen; + REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32]; + int bxcalen, bxxcalen, bycalen, byycalen, blen; + REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32]; + int cxablen, cxxablen, cyablen, cyyablen, clen; + REAL abdet[64]; + int ablen; + REAL fin1[1152], fin2[1152]; + REAL *finnow, *finother, *finswap; + int finlength; + + REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; + INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1; + REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0; + REAL aa[4], bb[4], cc[4]; + INEXACT REAL aa3, bb3, cc3; + INEXACT REAL ti1, tj1; + REAL ti0, tj0; + REAL u[4], v[4]; + INEXACT REAL u3, v3; + REAL temp8[8], temp16a[16], temp16b[16], temp16c[16]; + REAL temp32a[32], temp32b[32], temp48[48], temp64[64]; + int temp8len, temp16alen, temp16blen, temp16clen; + int temp32alen, temp32blen, temp48len, temp64len; + REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8]; + int axtbblen, axtcclen, aytbblen, aytcclen; + REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8]; + int bxtaalen, bxtcclen, bytaalen, bytcclen; + REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8]; + int cxtaalen, cxtbblen, cytaalen, cytbblen; + REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8]; + int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; + REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16]; + int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen; + REAL axtbctt[8], aytbctt[8], bxtcatt[8]; + REAL bytcatt[8], cxtabtt[8], cytabtt[8]; + int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen; + REAL abt[8], bct[8], cat[8]; + int abtlen, bctlen, catlen; + REAL abtt[4], bctt[4], catt[4]; + int abttlen, bcttlen, cattlen; + INEXACT REAL abtt3, bctt3, catt3; + REAL negate; + + INEXACT REAL bvirt; + REAL avirt, bround, around; + INEXACT REAL c; + INEXACT REAL abig; + REAL ahi, alo, bhi, blo; + REAL err1, err2, err3; + INEXACT REAL _i, _j; + REAL _0; + + adx = (REAL) ( pa[0] - pd[0] ); + bdx = (REAL) ( pb[0] - pd[0] ); + cdx = (REAL) ( pc[0] - pd[0] ); + ady = (REAL) ( pa[1] - pd[1] ); + bdy = (REAL) ( pb[1] - pd[1] ); + cdy = (REAL) ( pc[1] - pd[1] ); + + Two_Product( bdx, cdy, bdxcdy1, bdxcdy0 ); + Two_Product( cdx, bdy, cdxbdy1, cdxbdy0 ); + Two_Two_Diff( bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0] ); + bc[3] = bc3; + axbclen = scale_expansion_zeroelim( 4, bc, adx, axbc ); + axxbclen = scale_expansion_zeroelim( axbclen, axbc, adx, axxbc ); + aybclen = scale_expansion_zeroelim( 4, bc, ady, aybc ); + ayybclen = scale_expansion_zeroelim( aybclen, aybc, ady, ayybc ); + alen = fast_expansion_sum_zeroelim( axxbclen, axxbc, ayybclen, ayybc, adet ); + + Two_Product( cdx, ady, cdxady1, cdxady0 ); + Two_Product( adx, cdy, adxcdy1, adxcdy0 ); + Two_Two_Diff( cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0] ); + ca[3] = ca3; + bxcalen = scale_expansion_zeroelim( 4, ca, bdx, bxca ); + bxxcalen = scale_expansion_zeroelim( bxcalen, bxca, bdx, bxxca ); + bycalen = scale_expansion_zeroelim( 4, ca, bdy, byca ); + byycalen = scale_expansion_zeroelim( bycalen, byca, bdy, byyca ); + blen = fast_expansion_sum_zeroelim( bxxcalen, bxxca, byycalen, byyca, bdet ); + + Two_Product( adx, bdy, adxbdy1, adxbdy0 ); + Two_Product( bdx, ady, bdxady1, bdxady0 ); + Two_Two_Diff( adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0] ); + ab[3] = ab3; + cxablen = scale_expansion_zeroelim( 4, ab, cdx, cxab ); + cxxablen = scale_expansion_zeroelim( cxablen, cxab, cdx, cxxab ); + cyablen = scale_expansion_zeroelim( 4, ab, cdy, cyab ); + cyyablen = scale_expansion_zeroelim( cyablen, cyab, cdy, cyyab ); + clen = fast_expansion_sum_zeroelim( cxxablen, cxxab, cyyablen, cyyab, cdet ); + + ablen = fast_expansion_sum_zeroelim( alen, adet, blen, bdet, abdet ); + finlength = fast_expansion_sum_zeroelim( ablen, abdet, clen, cdet, fin1 ); + + det = estimate( finlength, fin1 ); + errbound = (REAL)( iccerrboundB * permanent ); + if ( ( det >= errbound ) || ( -det >= errbound ) ) { + return det; + } + + Two_Diff_Tail( pa[0], pd[0], adx, adxtail ); + Two_Diff_Tail( pa[1], pd[1], ady, adytail ); + Two_Diff_Tail( pb[0], pd[0], bdx, bdxtail ); + Two_Diff_Tail( pb[1], pd[1], bdy, bdytail ); + Two_Diff_Tail( pc[0], pd[0], cdx, cdxtail ); + Two_Diff_Tail( pc[1], pd[1], cdy, cdytail ); + if ( ( adxtail == 0.0 ) && ( bdxtail == 0.0 ) && ( cdxtail == 0.0 ) + && ( adytail == 0.0 ) && ( bdytail == 0.0 ) && ( cdytail == 0.0 ) ) { + return det; + } + + errbound = (REAL)( iccerrboundC * permanent + resulterrbound * Absolute( det ) ); + det += (REAL)( ( ( adx * adx + ady * ady ) * ( ( bdx * cdytail + cdy * bdxtail ) + - ( bdy * cdxtail + cdx * bdytail ) ) + + 2.0 * ( adx * adxtail + ady * adytail ) * ( bdx * cdy - bdy * cdx ) ) + + ( ( bdx * bdx + bdy * bdy ) * ( ( cdx * adytail + ady * cdxtail ) + - ( cdy * adxtail + adx * cdytail ) ) + + 2.0 * ( bdx * bdxtail + bdy * bdytail ) * ( cdx * ady - cdy * adx ) ) + + ( ( cdx * cdx + cdy * cdy ) * ( ( adx * bdytail + bdy * adxtail ) + - ( ady * bdxtail + bdx * adytail ) ) + + 2.0 * ( cdx * cdxtail + cdy * cdytail ) * ( adx * bdy - ady * bdx ) ) ); + if ( ( det >= errbound ) || ( -det >= errbound ) ) { + return det; + } + + finnow = fin1; + finother = fin2; + + if ( ( bdxtail != 0.0 ) || ( bdytail != 0.0 ) + || ( cdxtail != 0.0 ) || ( cdytail != 0.0 ) ) { + Square( adx, adxadx1, adxadx0 ); + Square( ady, adyady1, adyady0 ); + Two_Two_Sum( adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0] ); + aa[3] = aa3; + } + if ( ( cdxtail != 0.0 ) || ( cdytail != 0.0 ) + || ( adxtail != 0.0 ) || ( adytail != 0.0 ) ) { + Square( bdx, bdxbdx1, bdxbdx0 ); + Square( bdy, bdybdy1, bdybdy0 ); + Two_Two_Sum( bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0] ); + bb[3] = bb3; + } + if ( ( adxtail != 0.0 ) || ( adytail != 0.0 ) + || ( bdxtail != 0.0 ) || ( bdytail != 0.0 ) ) { + Square( cdx, cdxcdx1, cdxcdx0 ); + Square( cdy, cdycdy1, cdycdy0 ); + Two_Two_Sum( cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0] ); + cc[3] = cc3; + } + + if ( adxtail != 0.0 ) { + axtbclen = scale_expansion_zeroelim( 4, bc, adxtail, axtbc ); + temp16alen = scale_expansion_zeroelim( axtbclen, axtbc, 2.0 * adx, + temp16a ); + + axtcclen = scale_expansion_zeroelim( 4, cc, adxtail, axtcc ); + temp16blen = scale_expansion_zeroelim( axtcclen, axtcc, bdy, temp16b ); + + axtbblen = scale_expansion_zeroelim( 4, bb, adxtail, axtbb ); + temp16clen = scale_expansion_zeroelim( axtbblen, axtbb, -cdy, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( adytail != 0.0 ) { + aytbclen = scale_expansion_zeroelim( 4, bc, adytail, aytbc ); + temp16alen = scale_expansion_zeroelim( aytbclen, aytbc, 2.0 * ady, + temp16a ); + + aytbblen = scale_expansion_zeroelim( 4, bb, adytail, aytbb ); + temp16blen = scale_expansion_zeroelim( aytbblen, aytbb, cdx, temp16b ); + + aytcclen = scale_expansion_zeroelim( 4, cc, adytail, aytcc ); + temp16clen = scale_expansion_zeroelim( aytcclen, aytcc, -bdx, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( bdxtail != 0.0 ) { + bxtcalen = scale_expansion_zeroelim( 4, ca, bdxtail, bxtca ); + temp16alen = scale_expansion_zeroelim( bxtcalen, bxtca, 2.0 * bdx, + temp16a ); + + bxtaalen = scale_expansion_zeroelim( 4, aa, bdxtail, bxtaa ); + temp16blen = scale_expansion_zeroelim( bxtaalen, bxtaa, cdy, temp16b ); + + bxtcclen = scale_expansion_zeroelim( 4, cc, bdxtail, bxtcc ); + temp16clen = scale_expansion_zeroelim( bxtcclen, bxtcc, -ady, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( bdytail != 0.0 ) { + bytcalen = scale_expansion_zeroelim( 4, ca, bdytail, bytca ); + temp16alen = scale_expansion_zeroelim( bytcalen, bytca, 2.0 * bdy, + temp16a ); + + bytcclen = scale_expansion_zeroelim( 4, cc, bdytail, bytcc ); + temp16blen = scale_expansion_zeroelim( bytcclen, bytcc, adx, temp16b ); + + bytaalen = scale_expansion_zeroelim( 4, aa, bdytail, bytaa ); + temp16clen = scale_expansion_zeroelim( bytaalen, bytaa, -cdx, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( cdxtail != 0.0 ) { + cxtablen = scale_expansion_zeroelim( 4, ab, cdxtail, cxtab ); + temp16alen = scale_expansion_zeroelim( cxtablen, cxtab, 2.0 * cdx, + temp16a ); + + cxtbblen = scale_expansion_zeroelim( 4, bb, cdxtail, cxtbb ); + temp16blen = scale_expansion_zeroelim( cxtbblen, cxtbb, ady, temp16b ); + + cxtaalen = scale_expansion_zeroelim( 4, aa, cdxtail, cxtaa ); + temp16clen = scale_expansion_zeroelim( cxtaalen, cxtaa, -bdy, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( cdytail != 0.0 ) { + cytablen = scale_expansion_zeroelim( 4, ab, cdytail, cytab ); + temp16alen = scale_expansion_zeroelim( cytablen, cytab, 2.0 * cdy, + temp16a ); + + cytaalen = scale_expansion_zeroelim( 4, aa, cdytail, cytaa ); + temp16blen = scale_expansion_zeroelim( cytaalen, cytaa, bdx, temp16b ); + + cytbblen = scale_expansion_zeroelim( 4, bb, cdytail, cytbb ); + temp16clen = scale_expansion_zeroelim( cytbblen, cytbb, -adx, temp16c ); + + temp32alen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16clen, temp16c, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + + if ( ( adxtail != 0.0 ) || ( adytail != 0.0 ) ) { + if ( ( bdxtail != 0.0 ) || ( bdytail != 0.0 ) + || ( cdxtail != 0.0 ) || ( cdytail != 0.0 ) ) { + Two_Product( bdxtail, cdy, ti1, ti0 ); + Two_Product( bdx, cdytail, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0] ); + u[3] = u3; + negate = -bdy; + Two_Product( cdxtail, negate, ti1, ti0 ); + negate = -bdytail; + Two_Product( cdx, negate, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0] ); + v[3] = v3; + bctlen = fast_expansion_sum_zeroelim( 4, u, 4, v, bct ); + + Two_Product( bdxtail, cdytail, ti1, ti0 ); + Two_Product( cdxtail, bdytail, tj1, tj0 ); + Two_Two_Diff( ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0] ); + bctt[3] = bctt3; + bcttlen = 4; + } + else { + bct[0] = 0.0; + bctlen = 1; + bctt[0] = 0.0; + bcttlen = 1; + } + + if ( adxtail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( axtbclen, axtbc, adxtail, temp16a ); + axtbctlen = scale_expansion_zeroelim( bctlen, bct, adxtail, axtbct ); + temp32alen = scale_expansion_zeroelim( axtbctlen, axtbct, 2.0 * adx, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + if ( bdytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, cc, adxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, bdytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( cdytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, bb, -adxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, cdytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = scale_expansion_zeroelim( axtbctlen, axtbct, adxtail, + temp32a ); + axtbcttlen = scale_expansion_zeroelim( bcttlen, bctt, adxtail, axtbctt ); + temp16alen = scale_expansion_zeroelim( axtbcttlen, axtbctt, 2.0 * adx, + temp16a ); + temp16blen = scale_expansion_zeroelim( axtbcttlen, axtbctt, adxtail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( adytail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( aytbclen, aytbc, adytail, temp16a ); + aytbctlen = scale_expansion_zeroelim( bctlen, bct, adytail, aytbct ); + temp32alen = scale_expansion_zeroelim( aytbctlen, aytbct, 2.0 * ady, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + + + temp32alen = scale_expansion_zeroelim( aytbctlen, aytbct, adytail, + temp32a ); + aytbcttlen = scale_expansion_zeroelim( bcttlen, bctt, adytail, aytbctt ); + temp16alen = scale_expansion_zeroelim( aytbcttlen, aytbctt, 2.0 * ady, + temp16a ); + temp16blen = scale_expansion_zeroelim( aytbcttlen, aytbctt, adytail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + } + if ( ( bdxtail != 0.0 ) || ( bdytail != 0.0 ) ) { + if ( ( cdxtail != 0.0 ) || ( cdytail != 0.0 ) + || ( adxtail != 0.0 ) || ( adytail != 0.0 ) ) { + Two_Product( cdxtail, ady, ti1, ti0 ); + Two_Product( cdx, adytail, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0] ); + u[3] = u3; + negate = -cdy; + Two_Product( adxtail, negate, ti1, ti0 ); + negate = -cdytail; + Two_Product( adx, negate, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0] ); + v[3] = v3; + catlen = fast_expansion_sum_zeroelim( 4, u, 4, v, cat ); + + Two_Product( cdxtail, adytail, ti1, ti0 ); + Two_Product( adxtail, cdytail, tj1, tj0 ); + Two_Two_Diff( ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0] ); + catt[3] = catt3; + cattlen = 4; + } + else { + cat[0] = 0.0; + catlen = 1; + catt[0] = 0.0; + cattlen = 1; + } + + if ( bdxtail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( bxtcalen, bxtca, bdxtail, temp16a ); + bxtcatlen = scale_expansion_zeroelim( catlen, cat, bdxtail, bxtcat ); + temp32alen = scale_expansion_zeroelim( bxtcatlen, bxtcat, 2.0 * bdx, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + if ( cdytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, aa, bdxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, cdytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( adytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, cc, -bdxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, adytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = scale_expansion_zeroelim( bxtcatlen, bxtcat, bdxtail, + temp32a ); + bxtcattlen = scale_expansion_zeroelim( cattlen, catt, bdxtail, bxtcatt ); + temp16alen = scale_expansion_zeroelim( bxtcattlen, bxtcatt, 2.0 * bdx, + temp16a ); + temp16blen = scale_expansion_zeroelim( bxtcattlen, bxtcatt, bdxtail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( bdytail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( bytcalen, bytca, bdytail, temp16a ); + bytcatlen = scale_expansion_zeroelim( catlen, cat, bdytail, bytcat ); + temp32alen = scale_expansion_zeroelim( bytcatlen, bytcat, 2.0 * bdy, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + + + temp32alen = scale_expansion_zeroelim( bytcatlen, bytcat, bdytail, + temp32a ); + bytcattlen = scale_expansion_zeroelim( cattlen, catt, bdytail, bytcatt ); + temp16alen = scale_expansion_zeroelim( bytcattlen, bytcatt, 2.0 * bdy, + temp16a ); + temp16blen = scale_expansion_zeroelim( bytcattlen, bytcatt, bdytail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + } + if ( ( cdxtail != 0.0 ) || ( cdytail != 0.0 ) ) { + if ( ( adxtail != 0.0 ) || ( adytail != 0.0 ) + || ( bdxtail != 0.0 ) || ( bdytail != 0.0 ) ) { + Two_Product( adxtail, bdy, ti1, ti0 ); + Two_Product( adx, bdytail, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0] ); + u[3] = u3; + negate = -ady; + Two_Product( bdxtail, negate, ti1, ti0 ); + negate = -adytail; + Two_Product( bdx, negate, tj1, tj0 ); + Two_Two_Sum( ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0] ); + v[3] = v3; + abtlen = fast_expansion_sum_zeroelim( 4, u, 4, v, abt ); + + Two_Product( adxtail, bdytail, ti1, ti0 ); + Two_Product( bdxtail, adytail, tj1, tj0 ); + Two_Two_Diff( ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0] ); + abtt[3] = abtt3; + abttlen = 4; + } + else { + abt[0] = 0.0; + abtlen = 1; + abtt[0] = 0.0; + abttlen = 1; + } + + if ( cdxtail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( cxtablen, cxtab, cdxtail, temp16a ); + cxtabtlen = scale_expansion_zeroelim( abtlen, abt, cdxtail, cxtabt ); + temp32alen = scale_expansion_zeroelim( cxtabtlen, cxtabt, 2.0 * cdx, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + if ( adytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, bb, cdxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, adytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( bdytail != 0.0 ) { + temp8len = scale_expansion_zeroelim( 4, aa, -cdxtail, temp8 ); + temp16alen = scale_expansion_zeroelim( temp8len, temp8, bdytail, + temp16a ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp16alen, + temp16a, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = scale_expansion_zeroelim( cxtabtlen, cxtabt, cdxtail, + temp32a ); + cxtabttlen = scale_expansion_zeroelim( abttlen, abtt, cdxtail, cxtabtt ); + temp16alen = scale_expansion_zeroelim( cxtabttlen, cxtabtt, 2.0 * cdx, + temp16a ); + temp16blen = scale_expansion_zeroelim( cxtabttlen, cxtabtt, cdxtail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + if ( cdytail != 0.0 ) { + temp16alen = scale_expansion_zeroelim( cytablen, cytab, cdytail, temp16a ); + cytabtlen = scale_expansion_zeroelim( abtlen, abt, cdytail, cytabt ); + temp32alen = scale_expansion_zeroelim( cytabtlen, cytabt, 2.0 * cdy, + temp32a ); + temp48len = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp32alen, temp32a, temp48 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp48len, + temp48, finother ); + finswap = finnow; finnow = finother; finother = finswap; + + + temp32alen = scale_expansion_zeroelim( cytabtlen, cytabt, cdytail, + temp32a ); + cytabttlen = scale_expansion_zeroelim( abttlen, abtt, cdytail, cytabtt ); + temp16alen = scale_expansion_zeroelim( cytabttlen, cytabtt, 2.0 * cdy, + temp16a ); + temp16blen = scale_expansion_zeroelim( cytabttlen, cytabtt, cdytail, + temp16b ); + temp32blen = fast_expansion_sum_zeroelim( temp16alen, temp16a, + temp16blen, temp16b, temp32b ); + temp64len = fast_expansion_sum_zeroelim( temp32alen, temp32a, + temp32blen, temp32b, temp64 ); + finlength = fast_expansion_sum_zeroelim( finlength, finnow, temp64len, + temp64, finother ); + finswap = finnow; finnow = finother; finother = finswap; + } + } + + return finnow[finlength - 1]; } -REAL incircle(pa, pb, pc, pd) +REAL incircle( pa, pb, pc, pd ) point pa; point pb; point pc; point pd; { - REAL adx, bdx, cdx, ady, bdy, cdy; - REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; - REAL alift, blift, clift; - REAL det; - REAL permanent, errbound; - - incirclecount++; - - adx = pa[0] - pd[0]; - bdx = pb[0] - pd[0]; - cdx = pc[0] - pd[0]; - ady = pa[1] - pd[1]; - bdy = pb[1] - pd[1]; - cdy = pc[1] - pd[1]; - - bdxcdy = bdx * cdy; - cdxbdy = cdx * bdy; - alift = adx * adx + ady * ady; - - cdxady = cdx * ady; - adxcdy = adx * cdy; - blift = bdx * bdx + bdy * bdy; - - adxbdy = adx * bdy; - bdxady = bdx * ady; - clift = cdx * cdx + cdy * cdy; - - det = alift * (bdxcdy - cdxbdy) - + blift * (cdxady - adxcdy) - + clift * (adxbdy - bdxady); - - if (noexact) { - return det; - } - - permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift - + (Absolute(cdxady) + Absolute(adxcdy)) * blift - + (Absolute(adxbdy) + Absolute(bdxady)) * clift; - errbound = iccerrboundA * permanent; - if ((det > errbound) || (-det > errbound)) { - return det; - } - - return incircleadapt(pa, pb, pc, pd, permanent); + REAL adx, bdx, cdx, ady, bdy, cdy; + REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; + REAL alift, blift, clift; + REAL det; + REAL permanent, errbound; + + incirclecount++; + + adx = pa[0] - pd[0]; + bdx = pb[0] - pd[0]; + cdx = pc[0] - pd[0]; + ady = pa[1] - pd[1]; + bdy = pb[1] - pd[1]; + cdy = pc[1] - pd[1]; + + bdxcdy = bdx * cdy; + cdxbdy = cdx * bdy; + alift = adx * adx + ady * ady; + + cdxady = cdx * ady; + adxcdy = adx * cdy; + blift = bdx * bdx + bdy * bdy; + + adxbdy = adx * bdy; + bdxady = bdx * ady; + clift = cdx * cdx + cdy * cdy; + + det = alift * ( bdxcdy - cdxbdy ) + + blift * ( cdxady - adxcdy ) + + clift * ( adxbdy - bdxady ); + + if ( noexact ) { + return det; + } + + permanent = ( Absolute( bdxcdy ) + Absolute( cdxbdy ) ) * alift + + ( Absolute( cdxady ) + Absolute( adxcdy ) ) * blift + + ( Absolute( adxbdy ) + Absolute( bdxady ) ) * clift; + errbound = iccerrboundA * permanent; + if ( ( det > errbound ) || ( -det > errbound ) ) { + return det; + } + + return incircleadapt( pa, pb, pc, pd, permanent ); } /** **/ @@ -5033,20 +5060,19 @@ point pd; /* */ /*****************************************************************************/ -void triangleinit() -{ - points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems = - badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l; - points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes = - badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0; - recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */ - samples = 1; /* Point location should take at least one sample. */ - checksegments = 0; /* There are no segments in the triangulation yet. */ - incirclecount = counterclockcount = hyperbolacount = 0; - circumcentercount = circletopcount = 0; - randomseed = 1; - - exactinit(); /* Initialize exact arithmetic constants. */ +void triangleinit(){ + points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems = + badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l; + points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes = + badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0; + recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */ + samples = 1; /* Point location should take at least one sample. */ + checksegments = 0; /* There are no segments in the triangulation yet. */ + incirclecount = counterclockcount = hyperbolacount = 0; + circumcentercount = circletopcount = 0; + randomseed = 1; + + exactinit(); /* Initialize exact arithmetic constants. */ } /*****************************************************************************/ @@ -5059,11 +5085,11 @@ void triangleinit() /* */ /*****************************************************************************/ -unsigned long randomnation(choices) +unsigned long randomnation( choices ) unsigned int choices; { - randomseed = (randomseed * 1366l + 150889l) % 714025l; - return randomseed / (714025l / choices + 1); + randomseed = ( randomseed * 1366l + 150889l ) % 714025l; + return randomseed / ( 714025l / choices + 1 ); } /********* Mesh quality testing routines begin here *********/ @@ -5078,86 +5104,87 @@ unsigned int choices; #ifndef REDUCED -void checkmesh() -{ - struct triedge triangleloop; - struct triedge oppotri, oppooppotri; - point triorg, tridest, triapex; - point oppoorg, oppodest; - int horrors; - int saveexact; - triangle ptr; /* Temporary variable used by sym(). */ - - /* Temporarily turn on exact arithmetic if it's off. */ - saveexact = noexact; - noexact = 0; - if (!quiet) { - printf(" Checking consistency of mesh...\n"); - } - horrors = 0; - /* Run through the list of triangles, checking each one. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three edges of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - dest(triangleloop, tridest); - if (triangleloop.orient == 0) { /* Only test for inversion once. */ - /* Test if the triangle is flat or inverted. */ - apex(triangleloop, triapex); - if (counterclockwise(triorg, tridest, triapex) <= 0.0) { - printf(" !! !! Inverted "); - printtriangle(&triangleloop); - horrors++; - } - } - /* Find the neighboring triangle on this edge. */ - sym(triangleloop, oppotri); - if (oppotri.tri != dummytri) { - /* Check that the triangle's neighbor knows it's a neighbor. */ - sym(oppotri, oppooppotri); - if ((triangleloop.tri != oppooppotri.tri) - || (triangleloop.orient != oppooppotri.orient)) { - printf(" !! !! Asymmetric triangle-triangle bond:\n"); - if (triangleloop.tri == oppooppotri.tri) { - printf(" (Right triangle, wrong orientation)\n"); - } - printf(" First "); - printtriangle(&triangleloop); - printf(" Second (nonreciprocating) "); - printtriangle(&oppotri); - horrors++; - } - /* Check that both triangles agree on the identities */ - /* of their shared vertices. */ - org(oppotri, oppoorg); - dest(oppotri, oppodest); - if ((triorg != oppodest) || (tridest != oppoorg)) { - printf(" !! !! Mismatched edge coordinates between two triangles:\n" - ); - printf(" First mismatched "); - printtriangle(&triangleloop); - printf(" Second mismatched "); - printtriangle(&oppotri); - horrors++; - } - } - } - triangleloop.tri = triangletraverse(); - } - if (horrors == 0) { - if (!quiet) { - printf(" In my studied opinion, the mesh appears to be consistent.\n"); - } - } else if (horrors == 1) { - printf(" !! !! !! !! Precisely one festering wound discovered.\n"); - } else { - printf(" !! !! !! !! %d abominations witnessed.\n", horrors); - } - /* Restore the status of exact arithmetic. */ - noexact = saveexact; +void checkmesh(){ + struct triedge triangleloop; + struct triedge oppotri, oppooppotri; + point triorg, tridest, triapex; + point oppoorg, oppodest; + int horrors; + int saveexact; + triangle ptr; /* Temporary variable used by sym(). */ + + /* Temporarily turn on exact arithmetic if it's off. */ + saveexact = noexact; + noexact = 0; + if ( !quiet ) { + printf( " Checking consistency of mesh...\n" ); + } + horrors = 0; + /* Run through the list of triangles, checking each one. */ + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + while ( triangleloop.tri != (triangle *) NULL ) { + /* Check all three edges of the triangle. */ + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + org( triangleloop, triorg ); + dest( triangleloop, tridest ); + if ( triangleloop.orient == 0 ) { /* Only test for inversion once. */ + /* Test if the triangle is flat or inverted. */ + apex( triangleloop, triapex ); + if ( counterclockwise( triorg, tridest, triapex ) <= 0.0 ) { + printf( " !! !! Inverted " ); + printtriangle( &triangleloop ); + horrors++; + } + } + /* Find the neighboring triangle on this edge. */ + sym( triangleloop, oppotri ); + if ( oppotri.tri != dummytri ) { + /* Check that the triangle's neighbor knows it's a neighbor. */ + sym( oppotri, oppooppotri ); + if ( ( triangleloop.tri != oppooppotri.tri ) + || ( triangleloop.orient != oppooppotri.orient ) ) { + printf( " !! !! Asymmetric triangle-triangle bond:\n" ); + if ( triangleloop.tri == oppooppotri.tri ) { + printf( " (Right triangle, wrong orientation)\n" ); + } + printf( " First " ); + printtriangle( &triangleloop ); + printf( " Second (nonreciprocating) " ); + printtriangle( &oppotri ); + horrors++; + } + /* Check that both triangles agree on the identities */ + /* of their shared vertices. */ + org( oppotri, oppoorg ); + dest( oppotri, oppodest ); + if ( ( triorg != oppodest ) || ( tridest != oppoorg ) ) { + printf( " !! !! Mismatched edge coordinates between two triangles:\n" + ); + printf( " First mismatched " ); + printtriangle( &triangleloop ); + printf( " Second mismatched " ); + printtriangle( &oppotri ); + horrors++; + } + } + } + triangleloop.tri = triangletraverse(); + } + if ( horrors == 0 ) { + if ( !quiet ) { + printf( " In my studied opinion, the mesh appears to be consistent.\n" ); + } + } + else if ( horrors == 1 ) { + printf( " !! !! !! !! Precisely one festering wound discovered.\n" ); + } + else { + printf( " !! !! !! !! %d abominations witnessed.\n", horrors ); + } + /* Restore the status of exact arithmetic. */ + noexact = saveexact; } #endif /* not REDUCED */ @@ -5170,78 +5197,79 @@ void checkmesh() #ifndef REDUCED -void checkdelaunay() -{ - struct triedge triangleloop; - struct triedge oppotri; - struct edge opposhelle; - point triorg, tridest, triapex; - point oppoapex; - int shouldbedelaunay; - int horrors; - int saveexact; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Temporarily turn on exact arithmetic if it's off. */ - saveexact = noexact; - noexact = 0; - if (!quiet) { - printf(" Checking Delaunay property of mesh...\n"); - } - horrors = 0; - /* Run through the list of triangles, checking each one. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three edges of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - dest(triangleloop, tridest); - apex(triangleloop, triapex); - sym(triangleloop, oppotri); - apex(oppotri, oppoapex); - /* Only test that the edge is locally Delaunay if there is an */ - /* adjoining triangle whose pointer is larger (to ensure that */ - /* each pair isn't tested twice). */ - shouldbedelaunay = (oppotri.tri != dummytri) - && (triapex != (point) NULL) && (oppoapex != (point) NULL) - && (triangleloop.tri < oppotri.tri); - if (checksegments && shouldbedelaunay) { - /* If a shell edge separates the triangles, then the edge is */ - /* constrained, so no local Delaunay test should be done. */ - tspivot(triangleloop, opposhelle); - if (opposhelle.sh != dummysh){ - shouldbedelaunay = 0; - } - } - if (shouldbedelaunay) { - if (incircle(triorg, tridest, triapex, oppoapex) > 0.0) { - printf(" !! !! Non-Delaunay pair of triangles:\n"); - printf(" First non-Delaunay "); - printtriangle(&triangleloop); - printf(" Second non-Delaunay "); - printtriangle(&oppotri); - horrors++; - } - } - } - triangleloop.tri = triangletraverse(); - } - if (horrors == 0) { - if (!quiet) { - printf( - " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n"); - } - } else if (horrors == 1) { - printf( - " !! !! !! !! Precisely one terrifying transgression identified.\n"); - } else { - printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors); - } - /* Restore the status of exact arithmetic. */ - noexact = saveexact; +void checkdelaunay(){ + struct triedge triangleloop; + struct triedge oppotri; + struct edge opposhelle; + point triorg, tridest, triapex; + point oppoapex; + int shouldbedelaunay; + int horrors; + int saveexact; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + /* Temporarily turn on exact arithmetic if it's off. */ + saveexact = noexact; + noexact = 0; + if ( !quiet ) { + printf( " Checking Delaunay property of mesh...\n" ); + } + horrors = 0; + /* Run through the list of triangles, checking each one. */ + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + while ( triangleloop.tri != (triangle *) NULL ) { + /* Check all three edges of the triangle. */ + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + org( triangleloop, triorg ); + dest( triangleloop, tridest ); + apex( triangleloop, triapex ); + sym( triangleloop, oppotri ); + apex( oppotri, oppoapex ); + /* Only test that the edge is locally Delaunay if there is an */ + /* adjoining triangle whose pointer is larger (to ensure that */ + /* each pair isn't tested twice). */ + shouldbedelaunay = ( oppotri.tri != dummytri ) + && ( triapex != (point) NULL ) && ( oppoapex != (point) NULL ) + && ( triangleloop.tri < oppotri.tri ); + if ( checksegments && shouldbedelaunay ) { + /* If a shell edge separates the triangles, then the edge is */ + /* constrained, so no local Delaunay test should be done. */ + tspivot( triangleloop, opposhelle ); + if ( opposhelle.sh != dummysh ) { + shouldbedelaunay = 0; + } + } + if ( shouldbedelaunay ) { + if ( incircle( triorg, tridest, triapex, oppoapex ) > 0.0 ) { + printf( " !! !! Non-Delaunay pair of triangles:\n" ); + printf( " First non-Delaunay " ); + printtriangle( &triangleloop ); + printf( " Second non-Delaunay " ); + printtriangle( &oppotri ); + horrors++; + } + } + } + triangleloop.tri = triangletraverse(); + } + if ( horrors == 0 ) { + if ( !quiet ) { + printf( + " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n" ); + } + } + else if ( horrors == 1 ) { + printf( + " !! !! !! !! Precisely one terrifying transgression identified.\n" ); + } + else { + printf( " !! !! !! !! %d obscenities viewed with horror.\n", horrors ); + } + /* Restore the status of exact arithmetic. */ + noexact = saveexact; } #endif /* not REDUCED */ @@ -5258,43 +5286,44 @@ void checkdelaunay() #ifndef CDT_ONLY -void enqueuebadtri(instri, angle, insapex, insorg, insdest) +void enqueuebadtri( instri, angle, insapex, insorg, insdest ) struct triedge *instri; REAL angle; point insapex; point insorg; point insdest; { - struct badface *newface; - int queuenumber; - - if (verbose > 2) { - printf(" Queueing bad triangle:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0], - insorg[1], insdest[0], insdest[1], insapex[0], insapex[1]); - } - /* Allocate space for the bad triangle. */ - newface = (struct badface *) poolalloc(&badtriangles); - triedgecopy(*instri, newface->badfacetri); - newface->key = angle; - newface->faceapex = insapex; - newface->faceorg = insorg; - newface->facedest = insdest; - newface->nextface = (struct badface *) NULL; - /* Determine the appropriate queue to put the bad triangle into. */ - if (angle > 0.6) { - queuenumber = (int) (160.0 * (angle - 0.6)); - if (queuenumber > 63) { - queuenumber = 63; - } - } else { - /* It's not a bad angle; put the triangle in the lowest-priority queue. */ - queuenumber = 0; - } - /* Add the triangle to the end of a queue. */ - *queuetail[queuenumber] = newface; - /* Maintain a pointer to the NULL pointer at the end of the queue. */ - queuetail[queuenumber] = &newface->nextface; + struct badface *newface; + int queuenumber; + + if ( verbose > 2 ) { + printf( " Queueing bad triangle:\n" ); + printf( " (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0], + insorg[1], insdest[0], insdest[1], insapex[0], insapex[1] ); + } + /* Allocate space for the bad triangle. */ + newface = (struct badface *) poolalloc( &badtriangles ); + triedgecopy( *instri, newface->badfacetri ); + newface->key = angle; + newface->faceapex = insapex; + newface->faceorg = insorg; + newface->facedest = insdest; + newface->nextface = (struct badface *) NULL; + /* Determine the appropriate queue to put the bad triangle into. */ + if ( angle > 0.6 ) { + queuenumber = (int) ( 160.0 * ( angle - 0.6 ) ); + if ( queuenumber > 63 ) { + queuenumber = 63; + } + } + else { + /* It's not a bad angle; put the triangle in the lowest-priority queue. */ + queuenumber = 0; + } + /* Add the triangle to the end of a queue. */ + *queuetail[queuenumber] = newface; + /* Maintain a pointer to the NULL pointer at the end of the queue. */ + queuetail[queuenumber] = &newface->nextface; } #endif /* not CDT_ONLY */ @@ -5307,25 +5336,24 @@ point insdest; #ifndef CDT_ONLY -struct badface *dequeuebadtri() -{ - struct badface *result; - int queuenumber; - - /* Look for a nonempty queue. */ - for (queuenumber = 63; queuenumber >= 0; queuenumber--) { - result = queuefront[queuenumber]; - if (result != (struct badface *) NULL) { - /* Remove the triangle from the queue. */ - queuefront[queuenumber] = result->nextface; - /* Maintain a pointer to the NULL pointer at the end of the queue. */ - if (queuefront[queuenumber] == (struct badface *) NULL) { - queuetail[queuenumber] = &queuefront[queuenumber]; - } - return result; - } - } - return (struct badface *) NULL; +struct badface *dequeuebadtri(){ + struct badface *result; + int queuenumber; + + /* Look for a nonempty queue. */ + for ( queuenumber = 63; queuenumber >= 0; queuenumber-- ) { + result = queuefront[queuenumber]; + if ( result != (struct badface *) NULL ) { + /* Remove the triangle from the queue. */ + queuefront[queuenumber] = result->nextface; + /* Maintain a pointer to the NULL pointer at the end of the queue. */ + if ( queuefront[queuenumber] == (struct badface *) NULL ) { + queuetail[queuenumber] = &queuefront[queuenumber]; + } + return result; + } + } + return (struct badface *) NULL; } #endif /* not CDT_ONLY */ @@ -5345,72 +5373,73 @@ struct badface *dequeuebadtri() #ifndef CDT_ONLY -int checkedge4encroach(testedge) +int checkedge4encroach( testedge ) struct edge *testedge; { - struct triedge neighbortri; - struct edge testsym; - struct edge *badedge; - int addtolist; - int sides; - point eorg, edest, eapex; - triangle ptr; /* Temporary variable used by stpivot(). */ - - addtolist = 0; - sides = 0; - - sorg(*testedge, eorg); - sdest(*testedge, edest); - /* Check one neighbor of the shell edge. */ - stpivot(*testedge, neighbortri); - /* Does the neighbor exist, or is this a boundary edge? */ - if (neighbortri.tri != dummytri) { - sides++; - /* Find a vertex opposite this edge. */ - apex(neighbortri, eapex); - /* Check whether the vertex is inside the diametral circle of the */ - /* shell edge. Pythagoras' Theorem is used to check whether the */ - /* angle at the vertex is greater than 90 degrees. */ - if (eapex[0] * (eorg[0] + edest[0]) + eapex[1] * (eorg[1] + edest[1]) > - eapex[0] * eapex[0] + eorg[0] * edest[0] + - eapex[1] * eapex[1] + eorg[1] * edest[1]) { - addtolist = 1; - } - } - /* Check the other neighbor of the shell edge. */ - ssym(*testedge, testsym); - stpivot(testsym, neighbortri); - /* Does the neighbor exist, or is this a boundary edge? */ - if (neighbortri.tri != dummytri) { - sides++; - /* Find the other vertex opposite this edge. */ - apex(neighbortri, eapex); - /* Check whether the vertex is inside the diametral circle of the */ - /* shell edge. Pythagoras' Theorem is used to check whether the */ - /* angle at the vertex is greater than 90 degrees. */ - if (eapex[0] * (eorg[0] + edest[0]) + - eapex[1] * (eorg[1] + edest[1]) > - eapex[0] * eapex[0] + eorg[0] * edest[0] + - eapex[1] * eapex[1] + eorg[1] * edest[1]) { - addtolist += 2; - } - } - - if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) { - if (verbose > 2) { - printf(" Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n", - eorg[0], eorg[1], edest[0], edest[1]); - } - /* Add the shell edge to the list of encroached segments. */ - /* Be sure to get the orientation right. */ - badedge = (struct edge *) poolalloc(&badsegments); - if (addtolist == 1) { - shellecopy(*testedge, *badedge); - } else { - shellecopy(testsym, *badedge); - } - } - return addtolist; + struct triedge neighbortri; + struct edge testsym; + struct edge *badedge; + int addtolist; + int sides; + point eorg, edest, eapex; + triangle ptr; /* Temporary variable used by stpivot(). */ + + addtolist = 0; + sides = 0; + + sorg( *testedge, eorg ); + sdest( *testedge, edest ); + /* Check one neighbor of the shell edge. */ + stpivot( *testedge, neighbortri ); + /* Does the neighbor exist, or is this a boundary edge? */ + if ( neighbortri.tri != dummytri ) { + sides++; + /* Find a vertex opposite this edge. */ + apex( neighbortri, eapex ); + /* Check whether the vertex is inside the diametral circle of the */ + /* shell edge. Pythagoras' Theorem is used to check whether the */ + /* angle at the vertex is greater than 90 degrees. */ + if ( eapex[0] * ( eorg[0] + edest[0] ) + eapex[1] * ( eorg[1] + edest[1] ) > + eapex[0] * eapex[0] + eorg[0] * edest[0] + + eapex[1] * eapex[1] + eorg[1] * edest[1] ) { + addtolist = 1; + } + } + /* Check the other neighbor of the shell edge. */ + ssym( *testedge, testsym ); + stpivot( testsym, neighbortri ); + /* Does the neighbor exist, or is this a boundary edge? */ + if ( neighbortri.tri != dummytri ) { + sides++; + /* Find the other vertex opposite this edge. */ + apex( neighbortri, eapex ); + /* Check whether the vertex is inside the diametral circle of the */ + /* shell edge. Pythagoras' Theorem is used to check whether the */ + /* angle at the vertex is greater than 90 degrees. */ + if ( eapex[0] * ( eorg[0] + edest[0] ) + + eapex[1] * ( eorg[1] + edest[1] ) > + eapex[0] * eapex[0] + eorg[0] * edest[0] + + eapex[1] * eapex[1] + eorg[1] * edest[1] ) { + addtolist += 2; + } + } + + if ( addtolist && ( !nobisect || ( ( nobisect == 1 ) && ( sides == 2 ) ) ) ) { + if ( verbose > 2 ) { + printf( " Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n", + eorg[0], eorg[1], edest[0], edest[1] ); + } + /* Add the shell edge to the list of encroached segments. */ + /* Be sure to get the orientation right. */ + badedge = (struct edge *) poolalloc( &badsegments ); + if ( addtolist == 1 ) { + shellecopy( *testedge, *badedge ); + } + else { + shellecopy( testsym, *badedge ); + } + } + return addtolist; } #endif /* not CDT_ONLY */ @@ -5427,107 +5456,110 @@ struct edge *testedge; #ifndef CDT_ONLY -void testtriangle(testtri) +void testtriangle( testtri ) struct triedge *testtri; { - struct triedge sametesttri; - struct edge edge1, edge2; - point torg, tdest, tapex; - point anglevertex; - REAL dxod, dyod, dxda, dyda, dxao, dyao; - REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2; - REAL apexlen, orglen, destlen; - REAL angle; - REAL area; - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*testtri, torg); - dest(*testtri, tdest); - apex(*testtri, tapex); - dxod = torg[0] - tdest[0]; - dyod = torg[1] - tdest[1]; - dxda = tdest[0] - tapex[0]; - dyda = tdest[1] - tapex[1]; - dxao = tapex[0] - torg[0]; - dyao = tapex[1] - torg[1]; - dxod2 = dxod * dxod; - dyod2 = dyod * dyod; - dxda2 = dxda * dxda; - dyda2 = dyda * dyda; - dxao2 = dxao * dxao; - dyao2 = dyao * dyao; - /* Find the lengths of the triangle's three edges. */ - apexlen = dxod2 + dyod2; - orglen = dxda2 + dyda2; - destlen = dxao2 + dyao2; - if ((apexlen < orglen) && (apexlen < destlen)) { - /* The edge opposite the apex is shortest. */ - /* Find the square of the cosine of the angle at the apex. */ - angle = dxda * dxao + dyda * dyao; - angle = angle * angle / (orglen * destlen); - anglevertex = tapex; - lnext(*testtri, sametesttri); - tspivot(sametesttri, edge1); - lnextself(sametesttri); - tspivot(sametesttri, edge2); - } else if (orglen < destlen) { - /* The edge opposite the origin is shortest. */ - /* Find the square of the cosine of the angle at the origin. */ - angle = dxod * dxao + dyod * dyao; - angle = angle * angle / (apexlen * destlen); - anglevertex = torg; - tspivot(*testtri, edge1); - lprev(*testtri, sametesttri); - tspivot(sametesttri, edge2); - } else { - /* The edge opposite the destination is shortest. */ - /* Find the square of the cosine of the angle at the destination. */ - angle = dxod * dxda + dyod * dyda; - angle = angle * angle / (apexlen * orglen); - anglevertex = tdest; - tspivot(*testtri, edge1); - lnext(*testtri, sametesttri); - tspivot(sametesttri, edge2); - } - /* Check if both edges that form the angle are segments. */ - if ((edge1.sh != dummysh) && (edge2.sh != dummysh)) { - /* The angle is a segment intersection. */ - if ((angle > 0.9924) && !quiet) { /* Roughly 5 degrees. */ - if (angle > 1.0) { - /* Beware of a floating exception in acos(). */ - angle = 1.0; - } - /* Find the actual angle in degrees, for printing. */ - angle = acos(sqrt(angle)) * (180.0 / PI); - printf( - "Warning: Small angle (%.4g degrees) between segments at point\n", - angle); - printf(" (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]); - } - /* Don't add this bad triangle to the list; there's nothing that */ - /* can be done about a small angle between two segments. */ - angle = 0.0; - } - /* Check whether the angle is smaller than permitted. */ - if (angle > goodangle) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - return; - } - if (vararea || fixedarea) { - /* Check whether the area is larger than permitted. */ - area = 0.5 * (dxod * dyda - dyod * dxda); - if (fixedarea && (area > maxarea)) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - } else if (vararea) { - /* Nonpositive area constraints are treated as unconstrained. */ - if ((area > areabound(*testtri)) && (areabound(*testtri) > 0.0)) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - } - } - } + struct triedge sametesttri; + struct edge edge1, edge2; + point torg, tdest, tapex; + point anglevertex; + REAL dxod, dyod, dxda, dyda, dxao, dyao; + REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2; + REAL apexlen, orglen, destlen; + REAL angle; + REAL area; + shelle sptr; /* Temporary variable used by tspivot(). */ + + org( *testtri, torg ); + dest( *testtri, tdest ); + apex( *testtri, tapex ); + dxod = torg[0] - tdest[0]; + dyod = torg[1] - tdest[1]; + dxda = tdest[0] - tapex[0]; + dyda = tdest[1] - tapex[1]; + dxao = tapex[0] - torg[0]; + dyao = tapex[1] - torg[1]; + dxod2 = dxod * dxod; + dyod2 = dyod * dyod; + dxda2 = dxda * dxda; + dyda2 = dyda * dyda; + dxao2 = dxao * dxao; + dyao2 = dyao * dyao; + /* Find the lengths of the triangle's three edges. */ + apexlen = dxod2 + dyod2; + orglen = dxda2 + dyda2; + destlen = dxao2 + dyao2; + if ( ( apexlen < orglen ) && ( apexlen < destlen ) ) { + /* The edge opposite the apex is shortest. */ + /* Find the square of the cosine of the angle at the apex. */ + angle = dxda * dxao + dyda * dyao; + angle = angle * angle / ( orglen * destlen ); + anglevertex = tapex; + lnext( *testtri, sametesttri ); + tspivot( sametesttri, edge1 ); + lnextself( sametesttri ); + tspivot( sametesttri, edge2 ); + } + else if ( orglen < destlen ) { + /* The edge opposite the origin is shortest. */ + /* Find the square of the cosine of the angle at the origin. */ + angle = dxod * dxao + dyod * dyao; + angle = angle * angle / ( apexlen * destlen ); + anglevertex = torg; + tspivot( *testtri, edge1 ); + lprev( *testtri, sametesttri ); + tspivot( sametesttri, edge2 ); + } + else { + /* The edge opposite the destination is shortest. */ + /* Find the square of the cosine of the angle at the destination. */ + angle = dxod * dxda + dyod * dyda; + angle = angle * angle / ( apexlen * orglen ); + anglevertex = tdest; + tspivot( *testtri, edge1 ); + lnext( *testtri, sametesttri ); + tspivot( sametesttri, edge2 ); + } + /* Check if both edges that form the angle are segments. */ + if ( ( edge1.sh != dummysh ) && ( edge2.sh != dummysh ) ) { + /* The angle is a segment intersection. */ + if ( ( angle > 0.9924 ) && !quiet ) { /* Roughly 5 degrees. */ + if ( angle > 1.0 ) { + /* Beware of a floating exception in acos(). */ + angle = 1.0; + } + /* Find the actual angle in degrees, for printing. */ + angle = acos( sqrt( angle ) ) * ( 180.0 / PI ); + printf( + "Warning: Small angle (%.4g degrees) between segments at point\n", + angle ); + printf( " (%.12g, %.12g)\n", anglevertex[0], anglevertex[1] ); + } + /* Don't add this bad triangle to the list; there's nothing that */ + /* can be done about a small angle between two segments. */ + angle = 0.0; + } + /* Check whether the angle is smaller than permitted. */ + if ( angle > goodangle ) { + /* Add this triangle to the list of bad triangles. */ + enqueuebadtri( testtri, angle, tapex, torg, tdest ); + return; + } + if ( vararea || fixedarea ) { + /* Check whether the area is larger than permitted. */ + area = 0.5 * ( dxod * dyda - dyod * dxda ); + if ( fixedarea && ( area > maxarea ) ) { + /* Add this triangle to the list of bad triangles. */ + enqueuebadtri( testtri, angle, tapex, torg, tdest ); + } + else if ( vararea ) { + /* Nonpositive area constraints are treated as unconstrained. */ + if ( ( area > areabound( *testtri ) ) && ( areabound( *testtri ) > 0.0 ) ) { + /* Add this triangle to the list of bad triangles. */ + enqueuebadtri( testtri, angle, tapex, torg, tdest ); + } + } + } } #endif /* not CDT_ONLY */ @@ -5553,25 +5585,24 @@ struct triedge *testtri; /* */ /*****************************************************************************/ -void makepointmap() -{ - struct triedge triangleloop; - point triorg; - - if (verbose) { - printf(" Constructing mapping from points to triangles.\n"); - } - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three points of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - setpoint2tri(triorg, encode(triangleloop)); - } - triangleloop.tri = triangletraverse(); - } +void makepointmap(){ + struct triedge triangleloop; + point triorg; + + if ( verbose ) { + printf( " Constructing mapping from points to triangles.\n" ); + } + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + while ( triangleloop.tri != (triangle *) NULL ) { + /* Check all three points of the triangle. */ + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + org( triangleloop, triorg ); + setpoint2tri( triorg, encode( triangleloop ) ); + } + triangleloop.tri = triangletraverse(); + } } /*****************************************************************************/ @@ -5638,102 +5669,107 @@ void makepointmap() /* */ /*****************************************************************************/ -enum locateresult preciselocate(searchpoint, searchtri) +enum locateresult preciselocate( searchpoint, searchtri ) point searchpoint; struct triedge *searchtri; { - struct triedge backtracktri; - point forg, fdest, fapex; - point swappoint; - REAL orgorient, destorient; - int moveleft; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 2) { - printf(" Searching for point (%.12g, %.12g).\n", - searchpoint[0], searchpoint[1]); - } - /* Where are we? */ - org(*searchtri, forg); - dest(*searchtri, fdest); - apex(*searchtri, fapex); - while (1) { - if (verbose > 2) { - printf(" At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]); - } - /* Check whether the apex is the point we seek. */ - if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) { - lprevself(*searchtri); - return ONVERTEX; - } - /* Does the point lie on the other side of the line defined by the */ - /* triangle edge opposite the triangle's destination? */ - destorient = counterclockwise(forg, fapex, searchpoint); - /* Does the point lie on the other side of the line defined by the */ - /* triangle edge opposite the triangle's origin? */ - orgorient = counterclockwise(fapex, fdest, searchpoint); - if (destorient > 0.0) { - if (orgorient > 0.0) { - /* Move left if the inner product of (fapex - searchpoint) and */ - /* (fdest - forg) is positive. This is equivalent to drawing */ - /* a line perpendicular to the line (forg, fdest) passing */ - /* through `fapex', and determining which side of this line */ - /* `searchpoint' falls on. */ - moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) + - (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0; - } else { - moveleft = 1; - } - } else { - if (orgorient > 0.0) { - moveleft = 0; - } else { - /* The point we seek must be on the boundary of or inside this */ - /* triangle. */ - if (destorient == 0.0) { - lprevself(*searchtri); - return ONEDGE; - } - if (orgorient == 0.0) { - lnextself(*searchtri); - return ONEDGE; - } - return INTRIANGLE; - } - } - - /* Move to another triangle. Leave a trace `backtracktri' in case */ - /* floating-point roundoff or some such bogey causes us to walk */ - /* off a boundary of the triangulation. We can just bounce off */ - /* the boundary as if it were an elastic band. */ - if (moveleft) { - lprev(*searchtri, backtracktri); - fdest = fapex; - } else { - lnext(*searchtri, backtracktri); - forg = fapex; - } - sym(backtracktri, *searchtri); - - /* Check for walking off the edge. */ - if (searchtri->tri == dummytri) { - /* Turn around. */ - triedgecopy(backtracktri, *searchtri); - swappoint = forg; - forg = fdest; - fdest = swappoint; - apex(*searchtri, fapex); - /* Check if the point really is beyond the triangulation boundary. */ - destorient = counterclockwise(forg, fapex, searchpoint); - orgorient = counterclockwise(fapex, fdest, searchpoint); - if ((orgorient < 0.0) && (destorient < 0.0)) { - return OUTSIDE; - } - } else { - apex(*searchtri, fapex); - } - } + struct triedge backtracktri; + point forg, fdest, fapex; + point swappoint; + REAL orgorient, destorient; + int moveleft; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( verbose > 2 ) { + printf( " Searching for point (%.12g, %.12g).\n", + searchpoint[0], searchpoint[1] ); + } + /* Where are we? */ + org( *searchtri, forg ); + dest( *searchtri, fdest ); + apex( *searchtri, fapex ); + while ( 1 ) { + if ( verbose > 2 ) { + printf( " At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1] ); + } + /* Check whether the apex is the point we seek. */ + if ( ( fapex[0] == searchpoint[0] ) && ( fapex[1] == searchpoint[1] ) ) { + lprevself( *searchtri ); + return ONVERTEX; + } + /* Does the point lie on the other side of the line defined by the */ + /* triangle edge opposite the triangle's destination? */ + destorient = counterclockwise( forg, fapex, searchpoint ); + /* Does the point lie on the other side of the line defined by the */ + /* triangle edge opposite the triangle's origin? */ + orgorient = counterclockwise( fapex, fdest, searchpoint ); + if ( destorient > 0.0 ) { + if ( orgorient > 0.0 ) { + /* Move left if the inner product of (fapex - searchpoint) and */ + /* (fdest - forg) is positive. This is equivalent to drawing */ + /* a line perpendicular to the line (forg, fdest) passing */ + /* through `fapex', and determining which side of this line */ + /* `searchpoint' falls on. */ + moveleft = ( fapex[0] - searchpoint[0] ) * ( fdest[0] - forg[0] ) + + ( fapex[1] - searchpoint[1] ) * ( fdest[1] - forg[1] ) > 0.0; + } + else { + moveleft = 1; + } + } + else { + if ( orgorient > 0.0 ) { + moveleft = 0; + } + else { + /* The point we seek must be on the boundary of or inside this */ + /* triangle. */ + if ( destorient == 0.0 ) { + lprevself( *searchtri ); + return ONEDGE; + } + if ( orgorient == 0.0 ) { + lnextself( *searchtri ); + return ONEDGE; + } + return INTRIANGLE; + } + } + + /* Move to another triangle. Leave a trace `backtracktri' in case */ + /* floating-point roundoff or some such bogey causes us to walk */ + /* off a boundary of the triangulation. We can just bounce off */ + /* the boundary as if it were an elastic band. */ + if ( moveleft ) { + lprev( *searchtri, backtracktri ); + fdest = fapex; + } + else { + lnext( *searchtri, backtracktri ); + forg = fapex; + } + sym( backtracktri, *searchtri ); + + /* Check for walking off the edge. */ + if ( searchtri->tri == dummytri ) { + /* Turn around. */ + triedgecopy( backtracktri, *searchtri ); + swappoint = forg; + forg = fdest; + fdest = swappoint; + apex( *searchtri, fapex ); + /* Check if the point really is beyond the triangulation boundary. */ + destorient = counterclockwise( forg, fapex, searchpoint ); + orgorient = counterclockwise( fapex, fdest, searchpoint ); + if ( ( orgorient < 0.0 ) && ( destorient < 0.0 ) ) { + return OUTSIDE; + } + } + else { + apex( *searchtri, fapex ); + } + } } /*****************************************************************************/ @@ -5772,123 +5808,125 @@ struct triedge *searchtri; /* */ /*****************************************************************************/ -enum locateresult locate(searchpoint, searchtri) +enum locateresult locate( searchpoint, searchtri ) point searchpoint; struct triedge *searchtri; { - VOID **sampleblock; - triangle *firsttri; - struct triedge sampletri; - point torg, tdest; - unsigned long alignptr; - REAL searchdist, dist; - REAL ahead; - long sampleblocks, samplesperblock, samplenum; - long triblocks; - long i, j; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 2) { - printf(" Randomly sampling for a triangle near point (%.12g, %.12g).\n", - searchpoint[0], searchpoint[1]); - } - /* Record the distance from the suggested starting triangle to the */ - /* point we seek. */ - org(*searchtri, torg); - searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (verbose > 2) { - printf(" Boundary triangle has origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - - /* If a recently encountered triangle has been recorded and has not been */ - /* deallocated, test it as a good starting point. */ - if (recenttri.tri != (triangle *) NULL) { - if (recenttri.tri[3] != (triangle) NULL) { - org(recenttri, torg); - if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) { - triedgecopy(recenttri, *searchtri); - return ONVERTEX; - } - dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (dist < searchdist) { - triedgecopy(recenttri, *searchtri); - searchdist = dist; - if (verbose > 2) { - printf(" Choosing recent triangle with origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - } - } - } - - /* The number of random samples taken is proportional to the cube root of */ - /* the number of triangles in the mesh. The next bit of code assumes */ - /* that the number of triangles increases monotonically. */ - while (SAMPLEFACTOR * samples * samples * samples < triangles.items) { - samples++; - } - triblocks = (triangles.maxitems + TRIPERBLOCK - 1) / TRIPERBLOCK; - samplesperblock = 1 + (samples / triblocks); - sampleblocks = samples / samplesperblock; - sampleblock = triangles.firstblock; - sampletri.orient = 0; - for (i = 0; i < sampleblocks; i++) { - alignptr = (unsigned long) (sampleblock + 1); - firsttri = (triangle *) (alignptr + (unsigned long) triangles.alignbytes - - (alignptr % (unsigned long) triangles.alignbytes)); - for (j = 0; j < samplesperblock; j++) { - if (i == triblocks - 1) { - samplenum = randomnation((int) - (triangles.maxitems - (i * TRIPERBLOCK))); - } else { - samplenum = randomnation(TRIPERBLOCK); - } - sampletri.tri = (triangle *) - (firsttri + (samplenum * triangles.itemwords)); - if (sampletri.tri[3] != (triangle) NULL) { - org(sampletri, torg); - dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (dist < searchdist) { - triedgecopy(sampletri, *searchtri); - searchdist = dist; - if (verbose > 2) { - printf(" Choosing triangle with origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - } - } - } - sampleblock = (VOID **) *sampleblock; - } - /* Where are we? */ - org(*searchtri, torg); - dest(*searchtri, tdest); - /* Check the starting triangle's vertices. */ - if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) { - return ONVERTEX; - } - if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) { - lnextself(*searchtri); - return ONVERTEX; - } - /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */ - ahead = counterclockwise(torg, tdest, searchpoint); - if (ahead < 0.0) { - /* Turn around so that `searchpoint' is to the left of the */ - /* edge specified by `searchtri'. */ - symself(*searchtri); - } else if (ahead == 0.0) { - /* Check if `searchpoint' is between `torg' and `tdest'. */ - if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) - && ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) { - return ONEDGE; - } - } - return preciselocate(searchpoint, searchtri); + VOID **sampleblock; + triangle *firsttri; + struct triedge sampletri; + point torg, tdest; + unsigned long alignptr; + REAL searchdist, dist; + REAL ahead; + long sampleblocks, samplesperblock, samplenum; + long triblocks; + long i, j; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( verbose > 2 ) { + printf( " Randomly sampling for a triangle near point (%.12g, %.12g).\n", + searchpoint[0], searchpoint[1] ); + } + /* Record the distance from the suggested starting triangle to the */ + /* point we seek. */ + org( *searchtri, torg ); + searchdist = ( searchpoint[0] - torg[0] ) * ( searchpoint[0] - torg[0] ) + + ( searchpoint[1] - torg[1] ) * ( searchpoint[1] - torg[1] ); + if ( verbose > 2 ) { + printf( " Boundary triangle has origin (%.12g, %.12g).\n", + torg[0], torg[1] ); + } + + /* If a recently encountered triangle has been recorded and has not been */ + /* deallocated, test it as a good starting point. */ + if ( recenttri.tri != (triangle *) NULL ) { + if ( recenttri.tri[3] != (triangle) NULL ) { + org( recenttri, torg ); + if ( ( torg[0] == searchpoint[0] ) && ( torg[1] == searchpoint[1] ) ) { + triedgecopy( recenttri, *searchtri ); + return ONVERTEX; + } + dist = ( searchpoint[0] - torg[0] ) * ( searchpoint[0] - torg[0] ) + + ( searchpoint[1] - torg[1] ) * ( searchpoint[1] - torg[1] ); + if ( dist < searchdist ) { + triedgecopy( recenttri, *searchtri ); + searchdist = dist; + if ( verbose > 2 ) { + printf( " Choosing recent triangle with origin (%.12g, %.12g).\n", + torg[0], torg[1] ); + } + } + } + } + + /* The number of random samples taken is proportional to the cube root of */ + /* the number of triangles in the mesh. The next bit of code assumes */ + /* that the number of triangles increases monotonically. */ + while ( SAMPLEFACTOR * samples * samples * samples < triangles.items ) { + samples++; + } + triblocks = ( triangles.maxitems + TRIPERBLOCK - 1 ) / TRIPERBLOCK; + samplesperblock = 1 + ( samples / triblocks ); + sampleblocks = samples / samplesperblock; + sampleblock = triangles.firstblock; + sampletri.orient = 0; + for ( i = 0; i < sampleblocks; i++ ) { + alignptr = (unsigned long) ( sampleblock + 1 ); + firsttri = (triangle *) ( alignptr + (unsigned long) triangles.alignbytes + - ( alignptr % (unsigned long) triangles.alignbytes ) ); + for ( j = 0; j < samplesperblock; j++ ) { + if ( i == triblocks - 1 ) { + samplenum = randomnation( (int) + ( triangles.maxitems - ( i * TRIPERBLOCK ) ) ); + } + else { + samplenum = randomnation( TRIPERBLOCK ); + } + sampletri.tri = (triangle *) + ( firsttri + ( samplenum * triangles.itemwords ) ); + if ( sampletri.tri[3] != (triangle) NULL ) { + org( sampletri, torg ); + dist = ( searchpoint[0] - torg[0] ) * ( searchpoint[0] - torg[0] ) + + ( searchpoint[1] - torg[1] ) * ( searchpoint[1] - torg[1] ); + if ( dist < searchdist ) { + triedgecopy( sampletri, *searchtri ); + searchdist = dist; + if ( verbose > 2 ) { + printf( " Choosing triangle with origin (%.12g, %.12g).\n", + torg[0], torg[1] ); + } + } + } + } + sampleblock = (VOID **) *sampleblock; + } + /* Where are we? */ + org( *searchtri, torg ); + dest( *searchtri, tdest ); + /* Check the starting triangle's vertices. */ + if ( ( torg[0] == searchpoint[0] ) && ( torg[1] == searchpoint[1] ) ) { + return ONVERTEX; + } + if ( ( tdest[0] == searchpoint[0] ) && ( tdest[1] == searchpoint[1] ) ) { + lnextself( *searchtri ); + return ONVERTEX; + } + /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */ + ahead = counterclockwise( torg, tdest, searchpoint ); + if ( ahead < 0.0 ) { + /* Turn around so that `searchpoint' is to the left of the */ + /* edge specified by `searchtri'. */ + symself( *searchtri ); + } + else if ( ahead == 0.0 ) { + /* Check if `searchpoint' is between `torg' and `tdest'. */ + if ( ( ( torg[0] < searchpoint[0] ) == ( searchpoint[0] < tdest[0] ) ) + && ( ( torg[1] < searchpoint[1] ) == ( searchpoint[1] < tdest[1] ) ) ) { + return ONEDGE; + } + } + return preciselocate( searchpoint, searchtri ); } /** **/ @@ -5910,50 +5948,51 @@ struct triedge *searchtri; /* */ /*****************************************************************************/ -void insertshelle(tri, shellemark) +void insertshelle( tri, shellemark ) struct triedge *tri; /* Edge at which to insert the new shell edge. */ int shellemark; /* Marker for the new shell edge. */ { - struct triedge oppotri; - struct edge newshelle; - point triorg, tridest; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Mark points if possible. */ - org(*tri, triorg); - dest(*tri, tridest); - if (pointmark(triorg) == 0) { - setpointmark(triorg, shellemark); - } - if (pointmark(tridest) == 0) { - setpointmark(tridest, shellemark); - } - /* Check if there's already a shell edge here. */ - tspivot(*tri, newshelle); - if (newshelle.sh == dummysh) { - /* Make new shell edge and initialize its vertices. */ - makeshelle(&newshelle); - setsorg(newshelle, tridest); - setsdest(newshelle, triorg); - /* Bond new shell edge to the two triangles it is sandwiched between. */ - /* Note that the facing triangle `oppotri' might be equal to */ - /* `dummytri' (outer space), but the new shell edge is bonded to it */ - /* all the same. */ - tsbond(*tri, newshelle); - sym(*tri, oppotri); - ssymself(newshelle); - tsbond(oppotri, newshelle); - setmark(newshelle, shellemark); - if (verbose > 2) { - printf(" Inserting new "); - printshelle(&newshelle); - } - } else { - if (mark(newshelle) == 0) { - setmark(newshelle, shellemark); - } - } + struct triedge oppotri; + struct edge newshelle; + point triorg, tridest; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + /* Mark points if possible. */ + org( *tri, triorg ); + dest( *tri, tridest ); + if ( pointmark( triorg ) == 0 ) { + setpointmark( triorg, shellemark ); + } + if ( pointmark( tridest ) == 0 ) { + setpointmark( tridest, shellemark ); + } + /* Check if there's already a shell edge here. */ + tspivot( *tri, newshelle ); + if ( newshelle.sh == dummysh ) { + /* Make new shell edge and initialize its vertices. */ + makeshelle( &newshelle ); + setsorg( newshelle, tridest ); + setsdest( newshelle, triorg ); + /* Bond new shell edge to the two triangles it is sandwiched between. */ + /* Note that the facing triangle `oppotri' might be equal to */ + /* `dummytri' (outer space), but the new shell edge is bonded to it */ + /* all the same. */ + tsbond( *tri, newshelle ); + sym( *tri, oppotri ); + ssymself( newshelle ); + tsbond( oppotri, newshelle ); + setmark( newshelle, shellemark ); + if ( verbose > 2 ) { + printf( " Inserting new " ); + printshelle( &newshelle ); + } + } + else { + if ( mark( newshelle ) == 0 ) { + setmark( newshelle, shellemark ); + } + } } /*****************************************************************************/ @@ -6009,100 +6048,104 @@ int shellemark; /* Marker for the new shell edge. */ /* */ /*****************************************************************************/ -void flip(flipedge) +void flip( flipedge ) struct triedge *flipedge; /* Handle for the triangle abc. */ { - struct triedge botleft, botright; - struct triedge topleft, topright; - struct triedge top; - struct triedge botlcasing, botrcasing; - struct triedge toplcasing, toprcasing; - struct edge botlshelle, botrshelle; - struct edge toplshelle, toprshelle; - point leftpoint, rightpoint, botpoint; - point farpoint; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Identify the vertices of the quadrilateral. */ - org(*flipedge, rightpoint); - dest(*flipedge, leftpoint); - apex(*flipedge, botpoint); - sym(*flipedge, top); + struct triedge botleft, botright; + struct triedge topleft, topright; + struct triedge top; + struct triedge botlcasing, botrcasing; + struct triedge toplcasing, toprcasing; + struct edge botlshelle, botrshelle; + struct edge toplshelle, toprshelle; + point leftpoint, rightpoint, botpoint; + point farpoint; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + /* Identify the vertices of the quadrilateral. */ + org( *flipedge, rightpoint ); + dest( *flipedge, leftpoint ); + apex( *flipedge, botpoint ); + sym( *flipedge, top ); #ifdef SELF_CHECK - if (top.tri == dummytri) { - printf("Internal error in flip(): Attempt to flip on boundary.\n"); - lnextself(*flipedge); - return; - } - if (checksegments) { - tspivot(*flipedge, toplshelle); - if (toplshelle.sh != dummysh) { - printf("Internal error in flip(): Attempt to flip a segment.\n"); - lnextself(*flipedge); - return; - } - } + if ( top.tri == dummytri ) { + printf( "Internal error in flip(): Attempt to flip on boundary.\n" ); + lnextself( *flipedge ); + return; + } + if ( checksegments ) { + tspivot( *flipedge, toplshelle ); + if ( toplshelle.sh != dummysh ) { + printf( "Internal error in flip(): Attempt to flip a segment.\n" ); + lnextself( *flipedge ); + return; + } + } #endif /* SELF_CHECK */ - apex(top, farpoint); - - /* Identify the casing of the quadrilateral. */ - lprev(top, topleft); - sym(topleft, toplcasing); - lnext(top, topright); - sym(topright, toprcasing); - lnext(*flipedge, botleft); - sym(botleft, botlcasing); - lprev(*flipedge, botright); - sym(botright, botrcasing); - /* Rotate the quadrilateral one-quarter turn counterclockwise. */ - bond(topleft, botlcasing); - bond(botleft, botrcasing); - bond(botright, toprcasing); - bond(topright, toplcasing); - - if (checksegments) { - /* Check for shell edges and rebond them to the quadrilateral. */ - tspivot(topleft, toplshelle); - tspivot(botleft, botlshelle); - tspivot(botright, botrshelle); - tspivot(topright, toprshelle); - if (toplshelle.sh == dummysh) { - tsdissolve(topright); - } else { - tsbond(topright, toplshelle); - } - if (botlshelle.sh == dummysh) { - tsdissolve(topleft); - } else { - tsbond(topleft, botlshelle); - } - if (botrshelle.sh == dummysh) { - tsdissolve(botleft); - } else { - tsbond(botleft, botrshelle); - } - if (toprshelle.sh == dummysh) { - tsdissolve(botright); - } else { - tsbond(botright, toprshelle); - } - } - - /* New point assignments for the rotated quadrilateral. */ - setorg(*flipedge, farpoint); - setdest(*flipedge, botpoint); - setapex(*flipedge, rightpoint); - setorg(top, botpoint); - setdest(top, farpoint); - setapex(top, leftpoint); - if (verbose > 2) { - printf(" Edge flip results in left "); - lnextself(topleft); - printtriangle(&topleft); - printf(" and right "); - printtriangle(flipedge); - } + apex( top, farpoint ); + + /* Identify the casing of the quadrilateral. */ + lprev( top, topleft ); + sym( topleft, toplcasing ); + lnext( top, topright ); + sym( topright, toprcasing ); + lnext( *flipedge, botleft ); + sym( botleft, botlcasing ); + lprev( *flipedge, botright ); + sym( botright, botrcasing ); + /* Rotate the quadrilateral one-quarter turn counterclockwise. */ + bond( topleft, botlcasing ); + bond( botleft, botrcasing ); + bond( botright, toprcasing ); + bond( topright, toplcasing ); + + if ( checksegments ) { + /* Check for shell edges and rebond them to the quadrilateral. */ + tspivot( topleft, toplshelle ); + tspivot( botleft, botlshelle ); + tspivot( botright, botrshelle ); + tspivot( topright, toprshelle ); + if ( toplshelle.sh == dummysh ) { + tsdissolve( topright ); + } + else { + tsbond( topright, toplshelle ); + } + if ( botlshelle.sh == dummysh ) { + tsdissolve( topleft ); + } + else { + tsbond( topleft, botlshelle ); + } + if ( botrshelle.sh == dummysh ) { + tsdissolve( botleft ); + } + else { + tsbond( botleft, botrshelle ); + } + if ( toprshelle.sh == dummysh ) { + tsdissolve( botright ); + } + else { + tsbond( botright, toprshelle ); + } + } + + /* New point assignments for the rotated quadrilateral. */ + setorg( *flipedge, farpoint ); + setdest( *flipedge, botpoint ); + setapex( *flipedge, rightpoint ); + setorg( top, botpoint ); + setdest( top, farpoint ); + setapex( top, leftpoint ); + if ( verbose > 2 ) { + printf( " Edge flip results in left " ); + lnextself( topleft ); + printtriangle( &topleft ); + printf( " and right " ); + printtriangle( flipedge ); + } } /*****************************************************************************/ @@ -6152,531 +6195,545 @@ struct triedge *flipedge; /* Handle for the triangle abc. */ /* */ /*****************************************************************************/ -enum insertsiteresult insertsite(insertpoint, searchtri, splitedge, - segmentflaws, triflaws) +enum insertsiteresult insertsite( insertpoint, searchtri, splitedge, + segmentflaws, triflaws ) point insertpoint; struct triedge *searchtri; struct edge *splitedge; int segmentflaws; int triflaws; { - struct triedge horiz; - struct triedge top; - struct triedge botleft, botright; - struct triedge topleft, topright; - struct triedge newbotleft, newbotright; - struct triedge newtopright; - struct triedge botlcasing, botrcasing; - struct triedge toplcasing, toprcasing; - struct triedge testtri; - struct edge botlshelle, botrshelle; - struct edge toplshelle, toprshelle; - struct edge brokenshelle; - struct edge checkshelle; - struct edge rightedge; - struct edge newedge; - struct edge *encroached; - point first; - point leftpoint, rightpoint, botpoint, toppoint, farpoint; - REAL attrib; - REAL area; - enum insertsiteresult success; - enum locateresult intersect; - int doflip; - int mirrorflag; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by spivot() and tspivot(). */ - - if (verbose > 1) { - printf(" Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]); - } - if (splitedge == (struct edge *) NULL) { - /* Find the location of the point to be inserted. Check if a good */ - /* starting triangle has already been provided by the caller. */ - if (searchtri->tri == (triangle *) NULL) { - /* Find a boundary triangle. */ - horiz.tri = dummytri; - horiz.orient = 0; - symself(horiz); - /* Search for a triangle containing `insertpoint'. */ - intersect = locate(insertpoint, &horiz); - } else { - /* Start searching from the triangle provided by the caller. */ - triedgecopy(*searchtri, horiz); - intersect = preciselocate(insertpoint, &horiz); - } - } else { - /* The calling routine provides the edge in which the point is inserted. */ - triedgecopy(*searchtri, horiz); - intersect = ONEDGE; - } - if (intersect == ONVERTEX) { - /* There's already a vertex there. Return in `searchtri' a triangle */ - /* whose origin is the existing vertex. */ - triedgecopy(horiz, *searchtri); - triedgecopy(horiz, recenttri); - return DUPLICATEPOINT; - } - if ((intersect == ONEDGE) || (intersect == OUTSIDE)) { - /* The vertex falls on an edge or boundary. */ - if (checksegments && (splitedge == (struct edge *) NULL)) { - /* Check whether the vertex falls on a shell edge. */ - tspivot(horiz, brokenshelle); - if (brokenshelle.sh != dummysh) { - /* The vertex falls on a shell edge. */ - if (segmentflaws) { - if (nobisect == 0) { - /* Add the shell edge to the list of encroached segments. */ - encroached = (struct edge *) poolalloc(&badsegments); - shellecopy(brokenshelle, *encroached); - } else if ((nobisect == 1) && (intersect == ONEDGE)) { - /* This segment may be split only if it is an internal boundary. */ - sym(horiz, testtri); - if (testtri.tri != dummytri) { - /* Add the shell edge to the list of encroached segments. */ - encroached = (struct edge *) poolalloc(&badsegments); - shellecopy(brokenshelle, *encroached); - } - } - } - /* Return a handle whose primary edge contains the point, */ - /* which has not been inserted. */ - triedgecopy(horiz, *searchtri); - triedgecopy(horiz, recenttri); - return VIOLATINGPOINT; - } - } - /* Insert the point on an edge, dividing one triangle into two (if */ - /* the edge lies on a boundary) or two triangles into four. */ - lprev(horiz, botright); - sym(botright, botrcasing); - sym(horiz, topright); - /* Is there a second triangle? (Or does this edge lie on a boundary?) */ - mirrorflag = topright.tri != dummytri; - if (mirrorflag) { - lnextself(topright); - sym(topright, toprcasing); - maketriangle(&newtopright); - } else { - /* Splitting the boundary edge increases the number of boundary edges. */ - hullsize++; - } - maketriangle(&newbotright); - - /* Set the vertices of changed and new triangles. */ - org(horiz, rightpoint); - dest(horiz, leftpoint); - apex(horiz, botpoint); - setorg(newbotright, botpoint); - setdest(newbotright, rightpoint); - setapex(newbotright, insertpoint); - setorg(horiz, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of a new triangle. */ - setelemattribute(newbotright, i, elemattribute(botright, i)); - } - if (vararea) { - /* Set the area constraint of a new triangle. */ - setareabound(newbotright, areabound(botright)); - } - if (mirrorflag) { - dest(topright, toppoint); - setorg(newtopright, rightpoint); - setdest(newtopright, toppoint); - setapex(newtopright, insertpoint); - setorg(topright, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of another new triangle. */ - setelemattribute(newtopright, i, elemattribute(topright, i)); - } - if (vararea) { - /* Set the area constraint of another new triangle. */ - setareabound(newtopright, areabound(topright)); - } - } - - /* There may be shell edges that need to be bonded */ - /* to the new triangle(s). */ - if (checksegments) { - tspivot(botright, botrshelle); - if (botrshelle.sh != dummysh) { - tsdissolve(botright); - tsbond(newbotright, botrshelle); - } - if (mirrorflag) { - tspivot(topright, toprshelle); - if (toprshelle.sh != dummysh) { - tsdissolve(topright); - tsbond(newtopright, toprshelle); - } - } - } - - /* Bond the new triangle(s) to the surrounding triangles. */ - bond(newbotright, botrcasing); - lprevself(newbotright); - bond(newbotright, botright); - lprevself(newbotright); - if (mirrorflag) { - bond(newtopright, toprcasing); - lnextself(newtopright); - bond(newtopright, topright); - lnextself(newtopright); - bond(newtopright, newbotright); - } - - if (splitedge != (struct edge *) NULL) { - /* Split the shell edge into two. */ - setsdest(*splitedge, insertpoint); - ssymself(*splitedge); - spivot(*splitedge, rightedge); - insertshelle(&newbotright, mark(*splitedge)); - tspivot(newbotright, newedge); - sbond(*splitedge, newedge); - ssymself(newedge); - sbond(newedge, rightedge); - ssymself(*splitedge); - } + struct triedge horiz; + struct triedge top; + struct triedge botleft, botright; + struct triedge topleft, topright; + struct triedge newbotleft, newbotright; + struct triedge newtopright; + struct triedge botlcasing, botrcasing; + struct triedge toplcasing, toprcasing; + struct triedge testtri; + struct edge botlshelle, botrshelle; + struct edge toplshelle, toprshelle; + struct edge brokenshelle; + struct edge checkshelle; + struct edge rightedge; + struct edge newedge; + struct edge *encroached; + point first; + point leftpoint, rightpoint, botpoint, toppoint, farpoint; + REAL attrib; + REAL area; + enum insertsiteresult success; + enum locateresult intersect; + int doflip; + int mirrorflag; + int i; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by spivot() and tspivot(). */ + + if ( verbose > 1 ) { + printf( " Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1] ); + } + if ( splitedge == (struct edge *) NULL ) { + /* Find the location of the point to be inserted. Check if a good */ + /* starting triangle has already been provided by the caller. */ + if ( searchtri->tri == (triangle *) NULL ) { + /* Find a boundary triangle. */ + horiz.tri = dummytri; + horiz.orient = 0; + symself( horiz ); + /* Search for a triangle containing `insertpoint'. */ + intersect = locate( insertpoint, &horiz ); + } + else { + /* Start searching from the triangle provided by the caller. */ + triedgecopy( *searchtri, horiz ); + intersect = preciselocate( insertpoint, &horiz ); + } + } + else { + /* The calling routine provides the edge in which the point is inserted. */ + triedgecopy( *searchtri, horiz ); + intersect = ONEDGE; + } + if ( intersect == ONVERTEX ) { + /* There's already a vertex there. Return in `searchtri' a triangle */ + /* whose origin is the existing vertex. */ + triedgecopy( horiz, *searchtri ); + triedgecopy( horiz, recenttri ); + return DUPLICATEPOINT; + } + if ( ( intersect == ONEDGE ) || ( intersect == OUTSIDE ) ) { + /* The vertex falls on an edge or boundary. */ + if ( checksegments && ( splitedge == (struct edge *) NULL ) ) { + /* Check whether the vertex falls on a shell edge. */ + tspivot( horiz, brokenshelle ); + if ( brokenshelle.sh != dummysh ) { + /* The vertex falls on a shell edge. */ + if ( segmentflaws ) { + if ( nobisect == 0 ) { + /* Add the shell edge to the list of encroached segments. */ + encroached = (struct edge *) poolalloc( &badsegments ); + shellecopy( brokenshelle, *encroached ); + } + else if ( ( nobisect == 1 ) && ( intersect == ONEDGE ) ) { + /* This segment may be split only if it is an internal boundary. */ + sym( horiz, testtri ); + if ( testtri.tri != dummytri ) { + /* Add the shell edge to the list of encroached segments. */ + encroached = (struct edge *) poolalloc( &badsegments ); + shellecopy( brokenshelle, *encroached ); + } + } + } + /* Return a handle whose primary edge contains the point, */ + /* which has not been inserted. */ + triedgecopy( horiz, *searchtri ); + triedgecopy( horiz, recenttri ); + return VIOLATINGPOINT; + } + } + /* Insert the point on an edge, dividing one triangle into two (if */ + /* the edge lies on a boundary) or two triangles into four. */ + lprev( horiz, botright ); + sym( botright, botrcasing ); + sym( horiz, topright ); + /* Is there a second triangle? (Or does this edge lie on a boundary?) */ + mirrorflag = topright.tri != dummytri; + if ( mirrorflag ) { + lnextself( topright ); + sym( topright, toprcasing ); + maketriangle( &newtopright ); + } + else { + /* Splitting the boundary edge increases the number of boundary edges. */ + hullsize++; + } + maketriangle( &newbotright ); + + /* Set the vertices of changed and new triangles. */ + org( horiz, rightpoint ); + dest( horiz, leftpoint ); + apex( horiz, botpoint ); + setorg( newbotright, botpoint ); + setdest( newbotright, rightpoint ); + setapex( newbotright, insertpoint ); + setorg( horiz, insertpoint ); + for ( i = 0; i < eextras; i++ ) { + /* Set the element attributes of a new triangle. */ + setelemattribute( newbotright, i, elemattribute( botright, i ) ); + } + if ( vararea ) { + /* Set the area constraint of a new triangle. */ + setareabound( newbotright, areabound( botright ) ); + } + if ( mirrorflag ) { + dest( topright, toppoint ); + setorg( newtopright, rightpoint ); + setdest( newtopright, toppoint ); + setapex( newtopright, insertpoint ); + setorg( topright, insertpoint ); + for ( i = 0; i < eextras; i++ ) { + /* Set the element attributes of another new triangle. */ + setelemattribute( newtopright, i, elemattribute( topright, i ) ); + } + if ( vararea ) { + /* Set the area constraint of another new triangle. */ + setareabound( newtopright, areabound( topright ) ); + } + } + + /* There may be shell edges that need to be bonded */ + /* to the new triangle(s). */ + if ( checksegments ) { + tspivot( botright, botrshelle ); + if ( botrshelle.sh != dummysh ) { + tsdissolve( botright ); + tsbond( newbotright, botrshelle ); + } + if ( mirrorflag ) { + tspivot( topright, toprshelle ); + if ( toprshelle.sh != dummysh ) { + tsdissolve( topright ); + tsbond( newtopright, toprshelle ); + } + } + } + + /* Bond the new triangle(s) to the surrounding triangles. */ + bond( newbotright, botrcasing ); + lprevself( newbotright ); + bond( newbotright, botright ); + lprevself( newbotright ); + if ( mirrorflag ) { + bond( newtopright, toprcasing ); + lnextself( newtopright ); + bond( newtopright, topright ); + lnextself( newtopright ); + bond( newtopright, newbotright ); + } + + if ( splitedge != (struct edge *) NULL ) { + /* Split the shell edge into two. */ + setsdest( *splitedge, insertpoint ); + ssymself( *splitedge ); + spivot( *splitedge, rightedge ); + insertshelle( &newbotright, mark( *splitedge ) ); + tspivot( newbotright, newedge ); + sbond( *splitedge, newedge ); + ssymself( newedge ); + sbond( newedge, rightedge ); + ssymself( *splitedge ); + } #ifdef SELF_CHECK - if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge point insertion (bottom).\n"); - } - if (mirrorflag) { - if (counterclockwise(leftpoint, rightpoint, toppoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge point insertion (top).\n"); - } - if (counterclockwise(rightpoint, toppoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (top right).\n" - ); - } - if (counterclockwise(toppoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (top left).\n" - ); - } - } - if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (bottom left).\n" - ); - } - if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf( - " Clockwise triangle after edge point insertion (bottom right).\n"); - } + if ( counterclockwise( rightpoint, leftpoint, botpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle prior to edge point insertion (bottom).\n" ); + } + if ( mirrorflag ) { + if ( counterclockwise( leftpoint, rightpoint, toppoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle prior to edge point insertion (top).\n" ); + } + if ( counterclockwise( rightpoint, toppoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after edge point insertion (top right).\n" + ); + } + if ( counterclockwise( toppoint, leftpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after edge point insertion (top left).\n" + ); + } + } + if ( counterclockwise( leftpoint, botpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after edge point insertion (bottom left).\n" + ); + } + if ( counterclockwise( botpoint, rightpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( + " Clockwise triangle after edge point insertion (bottom right).\n" ); + } #endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Updating bottom left "); - printtriangle(&botright); - if (mirrorflag) { - printf(" Updating top left "); - printtriangle(&topright); - printf(" Creating top right "); - printtriangle(&newtopright); - } - printf(" Creating bottom right "); - printtriangle(&newbotright); - } - - /* Position `horiz' on the first edge to check for */ - /* the Delaunay property. */ - lnextself(horiz); - } else { - /* Insert the point in a triangle, splitting it into three. */ - lnext(horiz, botleft); - lprev(horiz, botright); - sym(botleft, botlcasing); - sym(botright, botrcasing); - maketriangle(&newbotleft); - maketriangle(&newbotright); - - /* Set the vertices of changed and new triangles. */ - org(horiz, rightpoint); - dest(horiz, leftpoint); - apex(horiz, botpoint); - setorg(newbotleft, leftpoint); - setdest(newbotleft, botpoint); - setapex(newbotleft, insertpoint); - setorg(newbotright, botpoint); - setdest(newbotright, rightpoint); - setapex(newbotright, insertpoint); - setapex(horiz, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of the new triangles. */ - attrib = elemattribute(horiz, i); - setelemattribute(newbotleft, i, attrib); - setelemattribute(newbotright, i, attrib); - } - if (vararea) { - /* Set the area constraint of the new triangles. */ - area = areabound(horiz); - setareabound(newbotleft, area); - setareabound(newbotright, area); - } - - /* There may be shell edges that need to be bonded */ - /* to the new triangles. */ - if (checksegments) { - tspivot(botleft, botlshelle); - if (botlshelle.sh != dummysh) { - tsdissolve(botleft); - tsbond(newbotleft, botlshelle); - } - tspivot(botright, botrshelle); - if (botrshelle.sh != dummysh) { - tsdissolve(botright); - tsbond(newbotright, botrshelle); - } - } - - /* Bond the new triangles to the surrounding triangles. */ - bond(newbotleft, botlcasing); - bond(newbotright, botrcasing); - lnextself(newbotleft); - lprevself(newbotright); - bond(newbotleft, newbotright); - lnextself(newbotleft); - bond(botleft, newbotleft); - lprevself(newbotright); - bond(botright, newbotright); + if ( verbose > 2 ) { + printf( " Updating bottom left " ); + printtriangle( &botright ); + if ( mirrorflag ) { + printf( " Updating top left " ); + printtriangle( &topright ); + printf( " Creating top right " ); + printtriangle( &newtopright ); + } + printf( " Creating bottom right " ); + printtriangle( &newbotright ); + } + + /* Position `horiz' on the first edge to check for */ + /* the Delaunay property. */ + lnextself( horiz ); + } + else { + /* Insert the point in a triangle, splitting it into three. */ + lnext( horiz, botleft ); + lprev( horiz, botright ); + sym( botleft, botlcasing ); + sym( botright, botrcasing ); + maketriangle( &newbotleft ); + maketriangle( &newbotright ); + + /* Set the vertices of changed and new triangles. */ + org( horiz, rightpoint ); + dest( horiz, leftpoint ); + apex( horiz, botpoint ); + setorg( newbotleft, leftpoint ); + setdest( newbotleft, botpoint ); + setapex( newbotleft, insertpoint ); + setorg( newbotright, botpoint ); + setdest( newbotright, rightpoint ); + setapex( newbotright, insertpoint ); + setapex( horiz, insertpoint ); + for ( i = 0; i < eextras; i++ ) { + /* Set the element attributes of the new triangles. */ + attrib = elemattribute( horiz, i ); + setelemattribute( newbotleft, i, attrib ); + setelemattribute( newbotright, i, attrib ); + } + if ( vararea ) { + /* Set the area constraint of the new triangles. */ + area = areabound( horiz ); + setareabound( newbotleft, area ); + setareabound( newbotright, area ); + } + + /* There may be shell edges that need to be bonded */ + /* to the new triangles. */ + if ( checksegments ) { + tspivot( botleft, botlshelle ); + if ( botlshelle.sh != dummysh ) { + tsdissolve( botleft ); + tsbond( newbotleft, botlshelle ); + } + tspivot( botright, botrshelle ); + if ( botrshelle.sh != dummysh ) { + tsdissolve( botright ); + tsbond( newbotright, botrshelle ); + } + } + + /* Bond the new triangles to the surrounding triangles. */ + bond( newbotleft, botlcasing ); + bond( newbotright, botrcasing ); + lnextself( newbotleft ); + lprevself( newbotright ); + bond( newbotleft, newbotright ); + lnextself( newbotleft ); + bond( botleft, newbotleft ); + lprevself( newbotright ); + bond( botright, newbotright ); #ifdef SELF_CHECK - if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to point insertion.\n"); - } - if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (top).\n"); - } - if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (left).\n"); - } - if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (right).\n"); - } + if ( counterclockwise( rightpoint, leftpoint, botpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle prior to point insertion.\n" ); + } + if ( counterclockwise( rightpoint, leftpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after point insertion (top).\n" ); + } + if ( counterclockwise( leftpoint, botpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after point insertion (left).\n" ); + } + if ( counterclockwise( botpoint, rightpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after point insertion (right).\n" ); + } #endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Updating top "); - printtriangle(&horiz); - printf(" Creating left "); - printtriangle(&newbotleft); - printf(" Creating right "); - printtriangle(&newbotright); - } - } - - /* The insertion is successful by default, unless an encroached */ - /* edge is found. */ - success = SUCCESSFULPOINT; - /* Circle around the newly inserted vertex, checking each edge opposite */ - /* it for the Delaunay property. Non-Delaunay edges are flipped. */ - /* `horiz' is always the edge being checked. `first' marks where to */ - /* stop circling. */ - org(horiz, first); - rightpoint = first; - dest(horiz, leftpoint); - /* Circle until finished. */ - while (1) { - /* By default, the edge will be flipped. */ - doflip = 1; - if (checksegments) { - /* Check for a segment, which cannot be flipped. */ - tspivot(horiz, checkshelle); - if (checkshelle.sh != dummysh) { - /* The edge is a segment and cannot be flipped. */ - doflip = 0; + if ( verbose > 2 ) { + printf( " Updating top " ); + printtriangle( &horiz ); + printf( " Creating left " ); + printtriangle( &newbotleft ); + printf( " Creating right " ); + printtriangle( &newbotright ); + } + } + + /* The insertion is successful by default, unless an encroached */ + /* edge is found. */ + success = SUCCESSFULPOINT; + /* Circle around the newly inserted vertex, checking each edge opposite */ + /* it for the Delaunay property. Non-Delaunay edges are flipped. */ + /* `horiz' is always the edge being checked. `first' marks where to */ + /* stop circling. */ + org( horiz, first ); + rightpoint = first; + dest( horiz, leftpoint ); + /* Circle until finished. */ + while ( 1 ) { + /* By default, the edge will be flipped. */ + doflip = 1; + if ( checksegments ) { + /* Check for a segment, which cannot be flipped. */ + tspivot( horiz, checkshelle ); + if ( checkshelle.sh != dummysh ) { + /* The edge is a segment and cannot be flipped. */ + doflip = 0; #ifndef CDT_ONLY - if (segmentflaws) { - /* Does the new point encroach upon this segment? */ - if (checkedge4encroach(&checkshelle)) { - success = ENCROACHINGPOINT; - } - } + if ( segmentflaws ) { + /* Does the new point encroach upon this segment? */ + if ( checkedge4encroach( &checkshelle ) ) { + success = ENCROACHINGPOINT; + } + } #endif /* not CDT_ONLY */ - } - } - if (doflip) { - /* Check if the edge is a boundary edge. */ - sym(horiz, top); - if (top.tri == dummytri) { - /* The edge is a boundary edge and cannot be flipped. */ - doflip = 0; - } else { - /* Find the point on the other side of the edge. */ - apex(top, farpoint); - /* In the incremental Delaunay triangulation algorithm, any of */ - /* `leftpoint', `rightpoint', and `farpoint' could be vertices */ - /* of the triangular bounding box. These vertices must be */ - /* treated as if they are infinitely distant, even though their */ - /* "coordinates" are not. */ - if ((leftpoint == infpoint1) || (leftpoint == infpoint2) - || (leftpoint == infpoint3)) { - /* `leftpoint' is infinitely distant. Check the convexity of */ - /* the boundary of the triangulation. 'farpoint' might be */ - /* infinite as well, but trust me, this same condition */ - /* should be applied. */ - doflip = counterclockwise(insertpoint, rightpoint, farpoint) > 0.0; - } else if ((rightpoint == infpoint1) || (rightpoint == infpoint2) - || (rightpoint == infpoint3)) { - /* `rightpoint' is infinitely distant. Check the convexity of */ - /* the boundary of the triangulation. 'farpoint' might be */ - /* infinite as well, but trust me, this same condition */ - /* should be applied. */ - doflip = counterclockwise(farpoint, leftpoint, insertpoint) > 0.0; - } else if ((farpoint == infpoint1) || (farpoint == infpoint2) - || (farpoint == infpoint3)) { - /* `farpoint' is infinitely distant and cannot be inside */ - /* the circumcircle of the triangle `horiz'. */ - doflip = 0; - } else { - /* Test whether the edge is locally Delaunay. */ - doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint) - > 0.0; - } - if (doflip) { - /* We made it! Flip the edge `horiz' by rotating its containing */ - /* quadrilateral (the two triangles adjacent to `horiz'). */ - /* Identify the casing of the quadrilateral. */ - lprev(top, topleft); - sym(topleft, toplcasing); - lnext(top, topright); - sym(topright, toprcasing); - lnext(horiz, botleft); - sym(botleft, botlcasing); - lprev(horiz, botright); - sym(botright, botrcasing); - /* Rotate the quadrilateral one-quarter turn counterclockwise. */ - bond(topleft, botlcasing); - bond(botleft, botrcasing); - bond(botright, toprcasing); - bond(topright, toplcasing); - if (checksegments) { - /* Check for shell edges and rebond them to the quadrilateral. */ - tspivot(topleft, toplshelle); - tspivot(botleft, botlshelle); - tspivot(botright, botrshelle); - tspivot(topright, toprshelle); - if (toplshelle.sh == dummysh) { - tsdissolve(topright); - } else { - tsbond(topright, toplshelle); - } - if (botlshelle.sh == dummysh) { - tsdissolve(topleft); - } else { - tsbond(topleft, botlshelle); - } - if (botrshelle.sh == dummysh) { - tsdissolve(botleft); - } else { - tsbond(botleft, botrshelle); - } - if (toprshelle.sh == dummysh) { - tsdissolve(botright); - } else { - tsbond(botright, toprshelle); - } - } - /* New point assignments for the rotated quadrilateral. */ - setorg(horiz, farpoint); - setdest(horiz, insertpoint); - setapex(horiz, rightpoint); - setorg(top, insertpoint); - setdest(top, farpoint); - setapex(top, leftpoint); - for (i = 0; i < eextras; i++) { - /* Take the average of the two triangles' attributes. */ - attrib = (REAL)(0.5 * (elemattribute(top, i) + elemattribute(horiz, i))); - setelemattribute(top, i, attrib); - setelemattribute(horiz, i, attrib); - } - if (vararea) { - if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) { - area = -1.0; - } else { - /* Take the average of the two triangles' area constraints. */ - /* This prevents small area constraints from migrating a */ - /* long, long way from their original location due to flips. */ - area = (REAL)(0.5 * (areabound(top) + areabound(horiz))); - } - setareabound(top, area); - setareabound(horiz, area); - } + } + } + if ( doflip ) { + /* Check if the edge is a boundary edge. */ + sym( horiz, top ); + if ( top.tri == dummytri ) { + /* The edge is a boundary edge and cannot be flipped. */ + doflip = 0; + } + else { + /* Find the point on the other side of the edge. */ + apex( top, farpoint ); + /* In the incremental Delaunay triangulation algorithm, any of */ + /* `leftpoint', `rightpoint', and `farpoint' could be vertices */ + /* of the triangular bounding box. These vertices must be */ + /* treated as if they are infinitely distant, even though their */ + /* "coordinates" are not. */ + if ( ( leftpoint == infpoint1 ) || ( leftpoint == infpoint2 ) + || ( leftpoint == infpoint3 ) ) { + /* `leftpoint' is infinitely distant. Check the convexity of */ + /* the boundary of the triangulation. 'farpoint' might be */ + /* infinite as well, but trust me, this same condition */ + /* should be applied. */ + doflip = counterclockwise( insertpoint, rightpoint, farpoint ) > 0.0; + } + else if ( ( rightpoint == infpoint1 ) || ( rightpoint == infpoint2 ) + || ( rightpoint == infpoint3 ) ) { + /* `rightpoint' is infinitely distant. Check the convexity of */ + /* the boundary of the triangulation. 'farpoint' might be */ + /* infinite as well, but trust me, this same condition */ + /* should be applied. */ + doflip = counterclockwise( farpoint, leftpoint, insertpoint ) > 0.0; + } + else if ( ( farpoint == infpoint1 ) || ( farpoint == infpoint2 ) + || ( farpoint == infpoint3 ) ) { + /* `farpoint' is infinitely distant and cannot be inside */ + /* the circumcircle of the triangle `horiz'. */ + doflip = 0; + } + else { + /* Test whether the edge is locally Delaunay. */ + doflip = incircle( leftpoint, insertpoint, rightpoint, farpoint ) + > 0.0; + } + if ( doflip ) { + /* We made it! Flip the edge `horiz' by rotating its containing */ + /* quadrilateral (the two triangles adjacent to `horiz'). */ + /* Identify the casing of the quadrilateral. */ + lprev( top, topleft ); + sym( topleft, toplcasing ); + lnext( top, topright ); + sym( topright, toprcasing ); + lnext( horiz, botleft ); + sym( botleft, botlcasing ); + lprev( horiz, botright ); + sym( botright, botrcasing ); + /* Rotate the quadrilateral one-quarter turn counterclockwise. */ + bond( topleft, botlcasing ); + bond( botleft, botrcasing ); + bond( botright, toprcasing ); + bond( topright, toplcasing ); + if ( checksegments ) { + /* Check for shell edges and rebond them to the quadrilateral. */ + tspivot( topleft, toplshelle ); + tspivot( botleft, botlshelle ); + tspivot( botright, botrshelle ); + tspivot( topright, toprshelle ); + if ( toplshelle.sh == dummysh ) { + tsdissolve( topright ); + } + else { + tsbond( topright, toplshelle ); + } + if ( botlshelle.sh == dummysh ) { + tsdissolve( topleft ); + } + else { + tsbond( topleft, botlshelle ); + } + if ( botrshelle.sh == dummysh ) { + tsdissolve( botleft ); + } + else { + tsbond( botleft, botrshelle ); + } + if ( toprshelle.sh == dummysh ) { + tsdissolve( botright ); + } + else { + tsbond( botright, toprshelle ); + } + } + /* New point assignments for the rotated quadrilateral. */ + setorg( horiz, farpoint ); + setdest( horiz, insertpoint ); + setapex( horiz, rightpoint ); + setorg( top, insertpoint ); + setdest( top, farpoint ); + setapex( top, leftpoint ); + for ( i = 0; i < eextras; i++ ) { + /* Take the average of the two triangles' attributes. */ + attrib = (REAL)( 0.5 * ( elemattribute( top, i ) + elemattribute( horiz, i ) ) ); + setelemattribute( top, i, attrib ); + setelemattribute( horiz, i, attrib ); + } + if ( vararea ) { + if ( ( areabound( top ) <= 0.0 ) || ( areabound( horiz ) <= 0.0 ) ) { + area = -1.0; + } + else { + /* Take the average of the two triangles' area constraints. */ + /* This prevents small area constraints from migrating a */ + /* long, long way from their original location due to flips. */ + area = (REAL)( 0.5 * ( areabound( top ) + areabound( horiz ) ) ); + } + setareabound( top, area ); + setareabound( horiz, area ); + } #ifdef SELF_CHECK - if (insertpoint != (point) NULL) { - if (counterclockwise(leftpoint, insertpoint, rightpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge flip (bottom).\n"); - } - /* The following test has been removed because constrainededge() */ - /* sometimes generates inverted triangles that insertsite() */ - /* removes. */ + if ( insertpoint != (point) NULL ) { + if ( counterclockwise( leftpoint, insertpoint, rightpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle prior to edge flip (bottom).\n" ); + } + /* The following test has been removed because constrainededge() */ + /* sometimes generates inverted triangles that insertsite() */ + /* removes. */ /* if (counterclockwise(rightpoint, farpoint, leftpoint) < 0.0) { printf("Internal error in insertsite():\n"); printf(" Clockwise triangle prior to edge flip (top).\n"); } -*/ - if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge flip (left).\n"); - } - if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge flip (right).\n"); - } - } + */ + if ( counterclockwise( farpoint, leftpoint, insertpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after edge flip (left).\n" ); + } + if ( counterclockwise( insertpoint, rightpoint, farpoint ) < 0.0 ) { + printf( "Internal error in insertsite():\n" ); + printf( " Clockwise triangle after edge flip (right).\n" ); + } + } #endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Edge flip results in left "); - lnextself(topleft); - printtriangle(&topleft); - printf(" and right "); - printtriangle(&horiz); - } - /* On the next iterations, consider the two edges that were */ - /* exposed (this is, are now visible to the newly inserted */ - /* point) by the edge flip. */ - lprevself(horiz); - leftpoint = farpoint; - } - } - } - if (!doflip) { - /* The handle `horiz' is accepted as locally Delaunay. */ + if ( verbose > 2 ) { + printf( " Edge flip results in left " ); + lnextself( topleft ); + printtriangle( &topleft ); + printf( " and right " ); + printtriangle( &horiz ); + } + /* On the next iterations, consider the two edges that were */ + /* exposed (this is, are now visible to the newly inserted */ + /* point) by the edge flip. */ + lprevself( horiz ); + leftpoint = farpoint; + } + } + } + if ( !doflip ) { + /* The handle `horiz' is accepted as locally Delaunay. */ #ifndef CDT_ONLY - if (triflaws) { - /* Check the triangle `horiz' for quality. */ - testtriangle(&horiz); - } + if ( triflaws ) { + /* Check the triangle `horiz' for quality. */ + testtriangle( &horiz ); + } #endif /* not CDT_ONLY */ - /* Look for the next edge around the newly inserted point. */ - lnextself(horiz); - sym(horiz, testtri); - /* Check for finishing a complete revolution about the new point, or */ - /* falling off the edge of the triangulation. The latter will */ - /* happen when a point is inserted at a boundary. */ - if ((leftpoint == first) || (testtri.tri == dummytri)) { - /* We're done. Return a triangle whose origin is the new point. */ - lnext(horiz, *searchtri); - lnext(horiz, recenttri); - return success; - } - /* Finish finding the next edge around the newly inserted point. */ - lnext(testtri, horiz); - rightpoint = leftpoint; - dest(horiz, leftpoint); - } - } + /* Look for the next edge around the newly inserted point. */ + lnextself( horiz ); + sym( horiz, testtri ); + /* Check for finishing a complete revolution about the new point, or */ + /* falling off the edge of the triangulation. The latter will */ + /* happen when a point is inserted at a boundary. */ + if ( ( leftpoint == first ) || ( testtri.tri == dummytri ) ) { + /* We're done. Return a triangle whose origin is the new point. */ + lnext( horiz, *searchtri ); + lnext( horiz, recenttri ); + return success; + } + /* Finish finding the next edge around the newly inserted point. */ + lnext( testtri, horiz ); + rightpoint = leftpoint; + dest( horiz, leftpoint ); + } + } } /*****************************************************************************/ @@ -6743,76 +6800,76 @@ int triflaws; /* */ /*****************************************************************************/ -void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws) +void triangulatepolygon( firstedge, lastedge, edgecount, doflip, triflaws ) struct triedge *firstedge; struct triedge *lastedge; int edgecount; int doflip; int triflaws; { - struct triedge testtri; - struct triedge besttri; - struct triedge tempedge; - point leftbasepoint, rightbasepoint; - point testpoint; - point bestpoint; - int bestnumber; - int i; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - - /* Identify the base vertices. */ - apex(*lastedge, leftbasepoint); - dest(*firstedge, rightbasepoint); - if (verbose > 2) { - printf(" Triangulating interior polygon at edge\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0], - leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]); - } - /* Find the best vertex to connect the base to. */ - onext(*firstedge, besttri); - dest(besttri, bestpoint); - triedgecopy(besttri, testtri); - bestnumber = 1; - for (i = 2; i <= edgecount - 2; i++) { - onextself(testtri); - dest(testtri, testpoint); - /* Is this a better vertex? */ - if (incircle(leftbasepoint, rightbasepoint, bestpoint, testpoint) > 0.0) { - triedgecopy(testtri, besttri); - bestpoint = testpoint; - bestnumber = i; - } - } - if (verbose > 2) { - printf(" Connecting edge to (%.12g, %.12g)\n", bestpoint[0], - bestpoint[1]); - } - if (bestnumber > 1) { - /* Recursively triangulate the smaller polygon on the right. */ - oprev(besttri, tempedge); - triangulatepolygon(firstedge, &tempedge, bestnumber + 1, 1, triflaws); - } - if (bestnumber < edgecount - 2) { - /* Recursively triangulate the smaller polygon on the left. */ - sym(besttri, tempedge); - triangulatepolygon(&besttri, lastedge, edgecount - bestnumber, 1, - triflaws); - /* Find `besttri' again; it may have been lost to edge flips. */ - sym(tempedge, besttri); - } - if (doflip) { - /* Do one final edge flip. */ - flip(&besttri); + struct triedge testtri; + struct triedge besttri; + struct triedge tempedge; + point leftbasepoint, rightbasepoint; + point testpoint; + point bestpoint; + int bestnumber; + int i; + triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ + + /* Identify the base vertices. */ + apex( *lastedge, leftbasepoint ); + dest( *firstedge, rightbasepoint ); + if ( verbose > 2 ) { + printf( " Triangulating interior polygon at edge\n" ); + printf( " (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0], + leftbasepoint[1], rightbasepoint[0], rightbasepoint[1] ); + } + /* Find the best vertex to connect the base to. */ + onext( *firstedge, besttri ); + dest( besttri, bestpoint ); + triedgecopy( besttri, testtri ); + bestnumber = 1; + for ( i = 2; i <= edgecount - 2; i++ ) { + onextself( testtri ); + dest( testtri, testpoint ); + /* Is this a better vertex? */ + if ( incircle( leftbasepoint, rightbasepoint, bestpoint, testpoint ) > 0.0 ) { + triedgecopy( testtri, besttri ); + bestpoint = testpoint; + bestnumber = i; + } + } + if ( verbose > 2 ) { + printf( " Connecting edge to (%.12g, %.12g)\n", bestpoint[0], + bestpoint[1] ); + } + if ( bestnumber > 1 ) { + /* Recursively triangulate the smaller polygon on the right. */ + oprev( besttri, tempedge ); + triangulatepolygon( firstedge, &tempedge, bestnumber + 1, 1, triflaws ); + } + if ( bestnumber < edgecount - 2 ) { + /* Recursively triangulate the smaller polygon on the left. */ + sym( besttri, tempedge ); + triangulatepolygon( &besttri, lastedge, edgecount - bestnumber, 1, + triflaws ); + /* Find `besttri' again; it may have been lost to edge flips. */ + sym( tempedge, besttri ); + } + if ( doflip ) { + /* Do one final edge flip. */ + flip( &besttri ); #ifndef CDT_ONLY - if (triflaws) { - /* Check the quality of the newly committed triangle. */ - sym(besttri, testtri); - testtriangle(&testtri); - } + if ( triflaws ) { + /* Check the quality of the newly committed triangle. */ + sym( besttri, testtri ); + testtriangle( &testtri ); + } #endif /* not CDT_ONLY */ - } - /* Return the base triangle. */ - triedgecopy(besttri, *lastedge); + } + /* Return the base triangle. */ + triedgecopy( besttri, *lastedge ); } /*****************************************************************************/ @@ -6831,84 +6888,84 @@ int triflaws; #ifndef CDT_ONLY -void deletesite(deltri) +void deletesite( deltri ) struct triedge *deltri; { - struct triedge countingtri; - struct triedge firstedge, lastedge; - struct triedge deltriright; - struct triedge lefttri, righttri; - struct triedge leftcasing, rightcasing; - struct edge leftshelle, rightshelle; - point delpoint; - point neworg; - int edgecount; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*deltri, delpoint); - if (verbose > 1) { - printf(" Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]); - } - pointdealloc(delpoint); - - /* Count the degree of the point being deleted. */ - onext(*deltri, countingtri); - edgecount = 1; - while (!triedgeequal(*deltri, countingtri)) { + struct triedge countingtri; + struct triedge firstedge, lastedge; + struct triedge deltriright; + struct triedge lefttri, righttri; + struct triedge leftcasing, rightcasing; + struct edge leftshelle, rightshelle; + point delpoint; + point neworg; + int edgecount; + triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + org( *deltri, delpoint ); + if ( verbose > 1 ) { + printf( " Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1] ); + } + pointdealloc( delpoint ); + + /* Count the degree of the point being deleted. */ + onext( *deltri, countingtri ); + edgecount = 1; + while ( !triedgeequal( *deltri, countingtri ) ) { #ifdef SELF_CHECK - if (countingtri.tri == dummytri) { - printf("Internal error in deletesite():\n"); - printf(" Attempt to delete boundary point.\n"); - internalerror(); - } + if ( countingtri.tri == dummytri ) { + printf( "Internal error in deletesite():\n" ); + printf( " Attempt to delete boundary point.\n" ); + internalerror(); + } #endif /* SELF_CHECK */ - edgecount++; - onextself(countingtri); - } + edgecount++; + onextself( countingtri ); + } #ifdef SELF_CHECK - if (edgecount < 3) { - printf("Internal error in deletesite():\n Point has degree %d.\n", - edgecount); - internalerror(); - } + if ( edgecount < 3 ) { + printf( "Internal error in deletesite():\n Point has degree %d.\n", + edgecount ); + internalerror(); + } #endif /* SELF_CHECK */ - if (edgecount > 3) { - /* Triangulate the polygon defined by the union of all triangles */ - /* adjacent to the point being deleted. Check the quality of */ - /* the resulting triangles. */ - onext(*deltri, firstedge); - oprev(*deltri, lastedge); - triangulatepolygon(&firstedge, &lastedge, edgecount, 0, !nobisect); - } - /* Splice out two triangles. */ - lprev(*deltri, deltriright); - dnext(*deltri, lefttri); - sym(lefttri, leftcasing); - oprev(deltriright, righttri); - sym(righttri, rightcasing); - bond(*deltri, leftcasing); - bond(deltriright, rightcasing); - tspivot(lefttri, leftshelle); - if (leftshelle.sh != dummysh) { - tsbond(*deltri, leftshelle); - } - tspivot(righttri, rightshelle); - if (rightshelle.sh != dummysh) { - tsbond(deltriright, rightshelle); - } - - /* Set the new origin of `deltri' and check its quality. */ - org(lefttri, neworg); - setorg(*deltri, neworg); - if (!nobisect) { - testtriangle(deltri); - } - - /* Delete the two spliced-out triangles. */ - triangledealloc(lefttri.tri); - triangledealloc(righttri.tri); + if ( edgecount > 3 ) { + /* Triangulate the polygon defined by the union of all triangles */ + /* adjacent to the point being deleted. Check the quality of */ + /* the resulting triangles. */ + onext( *deltri, firstedge ); + oprev( *deltri, lastedge ); + triangulatepolygon( &firstedge, &lastedge, edgecount, 0, !nobisect ); + } + /* Splice out two triangles. */ + lprev( *deltri, deltriright ); + dnext( *deltri, lefttri ); + sym( lefttri, leftcasing ); + oprev( deltriright, righttri ); + sym( righttri, rightcasing ); + bond( *deltri, leftcasing ); + bond( deltriright, rightcasing ); + tspivot( lefttri, leftshelle ); + if ( leftshelle.sh != dummysh ) { + tsbond( *deltri, leftshelle ); + } + tspivot( righttri, rightshelle ); + if ( rightshelle.sh != dummysh ) { + tsbond( deltriright, rightshelle ); + } + + /* Set the new origin of `deltri' and check its quality. */ + org( lefttri, neworg ); + setorg( *deltri, neworg ); + if ( !nobisect ) { + testtriangle( deltri ); + } + + /* Delete the two spliced-out triangles. */ + triangledealloc( lefttri.tri ); + triangledealloc( righttri.tri ); } #endif /* not CDT_ONLY */ @@ -6962,61 +7019,61 @@ struct triedge *deltri; /* */ /*****************************************************************************/ -void pointsort(sortarray, arraysize) -point *sortarray; +void pointsort( sortarray, arraysize ) +point * sortarray; int arraysize; { - int left, right; - int pivot; - REAL pivotx, pivoty; - point temp; - - if (arraysize == 2) { - /* Recursive base case. */ - if ((sortarray[0][0] > sortarray[1][0]) || - ((sortarray[0][0] == sortarray[1][0]) && - (sortarray[0][1] > sortarray[1][1]))) { - temp = sortarray[1]; - sortarray[1] = sortarray[0]; - sortarray[0] = temp; - } - return; - } - /* Choose a random pivot to split the array. */ - pivot = (int) randomnation(arraysize); - pivotx = sortarray[pivot][0]; - pivoty = sortarray[pivot][1]; - /* Split the array. */ - left = -1; - right = arraysize; - while (left < right) { - /* Search for a point whose x-coordinate is too large for the left. */ - do { - left++; - } while ((left <= right) && ((sortarray[left][0] < pivotx) || - ((sortarray[left][0] == pivotx) && - (sortarray[left][1] < pivoty)))); - /* Search for a point whose x-coordinate is too small for the right. */ - do { - right--; - } while ((left <= right) && ((sortarray[right][0] > pivotx) || - ((sortarray[right][0] == pivotx) && - (sortarray[right][1] > pivoty)))); - if (left < right) { - /* Swap the left and right points. */ - temp = sortarray[left]; - sortarray[left] = sortarray[right]; - sortarray[right] = temp; - } - } - if (left > 1) { - /* Recursively sort the left subset. */ - pointsort(sortarray, left); - } - if (right < arraysize - 2) { - /* Recursively sort the right subset. */ - pointsort(&sortarray[right + 1], arraysize - right - 1); - } + int left, right; + int pivot; + REAL pivotx, pivoty; + point temp; + + if ( arraysize == 2 ) { + /* Recursive base case. */ + if ( ( sortarray[0][0] > sortarray[1][0] ) || + ( ( sortarray[0][0] == sortarray[1][0] ) && + ( sortarray[0][1] > sortarray[1][1] ) ) ) { + temp = sortarray[1]; + sortarray[1] = sortarray[0]; + sortarray[0] = temp; + } + return; + } + /* Choose a random pivot to split the array. */ + pivot = (int) randomnation( arraysize ); + pivotx = sortarray[pivot][0]; + pivoty = sortarray[pivot][1]; + /* Split the array. */ + left = -1; + right = arraysize; + while ( left < right ) { + /* Search for a point whose x-coordinate is too large for the left. */ + do { + left++; + } while ( ( left <= right ) && ( ( sortarray[left][0] < pivotx ) || + ( ( sortarray[left][0] == pivotx ) && + ( sortarray[left][1] < pivoty ) ) ) ); + /* Search for a point whose x-coordinate is too small for the right. */ + do { + right--; + } while ( ( left <= right ) && ( ( sortarray[right][0] > pivotx ) || + ( ( sortarray[right][0] == pivotx ) && + ( sortarray[right][1] > pivoty ) ) ) ); + if ( left < right ) { + /* Swap the left and right points. */ + temp = sortarray[left]; + sortarray[left] = sortarray[right]; + sortarray[right] = temp; + } + } + if ( left > 1 ) { + /* Recursively sort the left subset. */ + pointsort( sortarray, left ); + } + if ( right < arraysize - 2 ) { + /* Recursively sort the right subset. */ + pointsort( &sortarray[right + 1], arraysize - right - 1 ); + } } /*****************************************************************************/ @@ -7031,66 +7088,66 @@ int arraysize; /* */ /*****************************************************************************/ -void pointmedian(sortarray, arraysize, median, axis) -point *sortarray; +void pointmedian( sortarray, arraysize, median, axis ) +point * sortarray; int arraysize; int median; int axis; { - int left, right; - int pivot; - REAL pivot1, pivot2; - point temp; - - if (arraysize == 2) { - /* Recursive base case. */ - if ((sortarray[0][axis] > sortarray[1][axis]) || - ((sortarray[0][axis] == sortarray[1][axis]) && - (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) { - temp = sortarray[1]; - sortarray[1] = sortarray[0]; - sortarray[0] = temp; - } - return; - } - /* Choose a random pivot to split the array. */ - pivot = (int) randomnation(arraysize); - pivot1 = sortarray[pivot][axis]; - pivot2 = sortarray[pivot][1 - axis]; - /* Split the array. */ - left = -1; - right = arraysize; - while (left < right) { - /* Search for a point whose x-coordinate is too large for the left. */ - do { - left++; - } while ((left <= right) && ((sortarray[left][axis] < pivot1) || - ((sortarray[left][axis] == pivot1) && - (sortarray[left][1 - axis] < pivot2)))); - /* Search for a point whose x-coordinate is too small for the right. */ - do { - right--; - } while ((left <= right) && ((sortarray[right][axis] > pivot1) || - ((sortarray[right][axis] == pivot1) && - (sortarray[right][1 - axis] > pivot2)))); - if (left < right) { - /* Swap the left and right points. */ - temp = sortarray[left]; - sortarray[left] = sortarray[right]; - sortarray[right] = temp; - } - } - /* Unlike in pointsort(), at most one of the following */ - /* conditionals is true. */ - if (left > median) { - /* Recursively shuffle the left subset. */ - pointmedian(sortarray, left, median, axis); - } - if (right < median - 1) { - /* Recursively shuffle the right subset. */ - pointmedian(&sortarray[right + 1], arraysize - right - 1, - median - right - 1, axis); - } + int left, right; + int pivot; + REAL pivot1, pivot2; + point temp; + + if ( arraysize == 2 ) { + /* Recursive base case. */ + if ( ( sortarray[0][axis] > sortarray[1][axis] ) || + ( ( sortarray[0][axis] == sortarray[1][axis] ) && + ( sortarray[0][1 - axis] > sortarray[1][1 - axis] ) ) ) { + temp = sortarray[1]; + sortarray[1] = sortarray[0]; + sortarray[0] = temp; + } + return; + } + /* Choose a random pivot to split the array. */ + pivot = (int) randomnation( arraysize ); + pivot1 = sortarray[pivot][axis]; + pivot2 = sortarray[pivot][1 - axis]; + /* Split the array. */ + left = -1; + right = arraysize; + while ( left < right ) { + /* Search for a point whose x-coordinate is too large for the left. */ + do { + left++; + } while ( ( left <= right ) && ( ( sortarray[left][axis] < pivot1 ) || + ( ( sortarray[left][axis] == pivot1 ) && + ( sortarray[left][1 - axis] < pivot2 ) ) ) ); + /* Search for a point whose x-coordinate is too small for the right. */ + do { + right--; + } while ( ( left <= right ) && ( ( sortarray[right][axis] > pivot1 ) || + ( ( sortarray[right][axis] == pivot1 ) && + ( sortarray[right][1 - axis] > pivot2 ) ) ) ); + if ( left < right ) { + /* Swap the left and right points. */ + temp = sortarray[left]; + sortarray[left] = sortarray[right]; + sortarray[right] = temp; + } + } + /* Unlike in pointsort(), at most one of the following */ + /* conditionals is true. */ + if ( left > median ) { + /* Recursively shuffle the left subset. */ + pointmedian( sortarray, left, median, axis ); + } + if ( right < median - 1 ) { + /* Recursively shuffle the right subset. */ + pointmedian( &sortarray[right + 1], arraysize - right - 1, + median - right - 1, axis ); + } } /*****************************************************************************/ @@ -7104,28 +7161,28 @@ int axis; /* */ /*****************************************************************************/ -void alternateaxes(sortarray, arraysize, axis) -point *sortarray; +void alternateaxes( sortarray, arraysize, axis ) +point * sortarray; int arraysize; int axis; { - int divider; - - divider = arraysize >> 1; - if (arraysize <= 3) { - /* Recursive base case: subsets of two or three points will be */ - /* handled specially, and should always be sorted by x-coordinate. */ - axis = 0; - } - /* Partition with a horizontal or vertical cut. */ - pointmedian(sortarray, arraysize, divider, axis); - /* Recursively partition the subsets with a cross cut. */ - if (arraysize - divider >= 2) { - if (divider >= 2) { - alternateaxes(sortarray, divider, 1 - axis); - } - alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis); - } + int divider; + + divider = arraysize >> 1; + if ( arraysize <= 3 ) { + /* Recursive base case: subsets of two or three points will be */ + /* handled specially, and should always be sorted by x-coordinate. */ + axis = 0; + } + /* Partition with a horizontal or vertical cut. */ + pointmedian( sortarray, arraysize, divider, axis ); + /* Recursively partition the subsets with a cross cut. */ + if ( arraysize - divider >= 2 ) { + if ( divider >= 2 ) { + alternateaxes( sortarray, divider, 1 - axis ); + } + alternateaxes( &sortarray[divider], arraysize - divider, 1 - axis ); + } } /*****************************************************************************/ @@ -7163,297 +7220,300 @@ int axis; /* */ /*****************************************************************************/ -void mergehulls(farleft, innerleft, innerright, farright, axis) +void mergehulls( farleft, innerleft, innerright, farright, axis ) struct triedge *farleft; struct triedge *innerleft; struct triedge *innerright; struct triedge *farright; int axis; { - struct triedge leftcand, rightcand; - struct triedge baseedge; - struct triedge nextedge; - struct triedge sidecasing, topcasing, outercasing; - struct triedge checkedge; - point innerleftdest; - point innerrightorg; - point innerleftapex, innerrightapex; - point farleftpt, farrightpt; - point farleftapex, farrightapex; - point lowerleft, lowerright; - point upperleft, upperright; - point nextapex; - point checkvertex; - int changemade; - int badedge; - int leftfinished, rightfinished; - triangle ptr; /* Temporary variable used by sym(). */ - - dest(*innerleft, innerleftdest); - apex(*innerleft, innerleftapex); - org(*innerright, innerrightorg); - apex(*innerright, innerrightapex); - /* Special treatment for horizontal cuts. */ - if (dwyer && (axis == 1)) { - org(*farleft, farleftpt); - apex(*farleft, farleftapex); - dest(*farright, farrightpt); - apex(*farright, farrightapex); - /* The pointers to the extremal points are shifted to point to the */ - /* topmost and bottommost point of each hull, rather than the */ - /* leftmost and rightmost points. */ - while (farleftapex[1] < farleftpt[1]) { - lnextself(*farleft); - symself(*farleft); - farleftpt = farleftapex; - apex(*farleft, farleftapex); - } - sym(*innerleft, checkedge); - apex(checkedge, checkvertex); - while (checkvertex[1] > innerleftdest[1]) { - lnext(checkedge, *innerleft); - innerleftapex = innerleftdest; - innerleftdest = checkvertex; - sym(*innerleft, checkedge); - apex(checkedge, checkvertex); - } - while (innerrightapex[1] < innerrightorg[1]) { - lnextself(*innerright); - symself(*innerright); - innerrightorg = innerrightapex; - apex(*innerright, innerrightapex); - } - sym(*farright, checkedge); - apex(checkedge, checkvertex); - while (checkvertex[1] > farrightpt[1]) { - lnext(checkedge, *farright); - farrightapex = farrightpt; - farrightpt = checkvertex; - sym(*farright, checkedge); - apex(checkedge, checkvertex); - } - } - /* Find a line tangent to and below both hulls. */ - do { - changemade = 0; - /* Make innerleftdest the "bottommost" point of the left hull. */ - if (counterclockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) { - lprevself(*innerleft); - symself(*innerleft); - innerleftdest = innerleftapex; - apex(*innerleft, innerleftapex); - changemade = 1; - } - /* Make innerrightorg the "bottommost" point of the right hull. */ - if (counterclockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) { - lnextself(*innerright); - symself(*innerright); - innerrightorg = innerrightapex; - apex(*innerright, innerrightapex); - changemade = 1; - } - } while (changemade); - /* Find the two candidates to be the next "gear tooth". */ - sym(*innerleft, leftcand); - sym(*innerright, rightcand); - /* Create the bottom new bounding triangle. */ - maketriangle(&baseedge); - /* Connect it to the bounding boxes of the left and right triangulations. */ - bond(baseedge, *innerleft); - lnextself(baseedge); - bond(baseedge, *innerright); - lnextself(baseedge); - setorg(baseedge, innerrightorg); - setdest(baseedge, innerleftdest); - /* Apex is intentionally left NULL. */ - if (verbose > 2) { - printf(" Creating base bounding "); - printtriangle(&baseedge); - } - /* Fix the extreme triangles if necessary. */ - org(*farleft, farleftpt); - if (innerleftdest == farleftpt) { - lnext(baseedge, *farleft); - } - dest(*farright, farrightpt); - if (innerrightorg == farrightpt) { - lprev(baseedge, *farright); - } - /* The vertices of the current knitting edge. */ - lowerleft = innerleftdest; - lowerright = innerrightorg; - /* The candidate vertices for knitting. */ - apex(leftcand, upperleft); - apex(rightcand, upperright); - /* Walk up the gap between the two triangulations, knitting them together. */ - while (1) { - /* Have we reached the top? (This isn't quite the right question, */ - /* because even though the left triangulation might seem finished now, */ - /* moving up on the right triangulation might reveal a new point of */ - /* the left triangulation. And vice-versa.) */ - leftfinished = counterclockwise(upperleft, lowerleft, lowerright) <= 0.0; - rightfinished = counterclockwise(upperright, lowerleft, lowerright) <= 0.0; - if (leftfinished && rightfinished) { - /* Create the top new bounding triangle. */ - maketriangle(&nextedge); - setorg(nextedge, lowerleft); - setdest(nextedge, lowerright); - /* Apex is intentionally left NULL. */ - /* Connect it to the bounding boxes of the two triangulations. */ - bond(nextedge, baseedge); - lnextself(nextedge); - bond(nextedge, rightcand); - lnextself(nextedge); - bond(nextedge, leftcand); - if (verbose > 2) { - printf(" Creating top bounding "); - printtriangle(&baseedge); - } - /* Special treatment for horizontal cuts. */ - if (dwyer && (axis == 1)) { - org(*farleft, farleftpt); - apex(*farleft, farleftapex); - dest(*farright, farrightpt); - apex(*farright, farrightapex); - sym(*farleft, checkedge); - apex(checkedge, checkvertex); - /* The pointers to the extremal points are restored to the leftmost */ - /* and rightmost points (rather than topmost and bottommost). */ - while (checkvertex[0] < farleftpt[0]) { - lprev(checkedge, *farleft); - farleftapex = farleftpt; - farleftpt = checkvertex; - sym(*farleft, checkedge); - apex(checkedge, checkvertex); - } - while (farrightapex[0] > farrightpt[0]) { - lprevself(*farright); - symself(*farright); - farrightpt = farrightapex; - apex(*farright, farrightapex); - } - } - return; - } - /* Consider eliminating edges from the left triangulation. */ - if (!leftfinished) { - /* What vertex would be exposed if an edge were deleted? */ - lprev(leftcand, nextedge); - symself(nextedge); - apex(nextedge, nextapex); - /* If nextapex is NULL, then no vertex would be exposed; the */ - /* triangulation would have been eaten right through. */ - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperleft, nextapex) > 0.0; - while (badedge) { - /* Eliminate the edge with an edge flip. As a result, the */ - /* left triangulation will have one more boundary triangle. */ - lnextself(nextedge); - sym(nextedge, topcasing); - lnextself(nextedge); - sym(nextedge, sidecasing); - bond(nextedge, topcasing); - bond(leftcand, sidecasing); - lnextself(leftcand); - sym(leftcand, outercasing); - lprevself(nextedge); - bond(nextedge, outercasing); - /* Correct the vertices to reflect the edge flip. */ - setorg(leftcand, lowerleft); - setdest(leftcand, NULL); - setapex(leftcand, nextapex); - setorg(nextedge, NULL); - setdest(nextedge, upperleft); - setapex(nextedge, nextapex); - /* Consider the newly exposed vertex. */ - upperleft = nextapex; - /* What vertex would be exposed if another edge were deleted? */ - triedgecopy(sidecasing, nextedge); - apex(nextedge, nextapex); - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperleft, nextapex) - > 0.0; - } else { - /* Avoid eating right through the triangulation. */ - badedge = 0; - } - } - } - } - /* Consider eliminating edges from the right triangulation. */ - if (!rightfinished) { - /* What vertex would be exposed if an edge were deleted? */ - lnext(rightcand, nextedge); - symself(nextedge); - apex(nextedge, nextapex); - /* If nextapex is NULL, then no vertex would be exposed; the */ - /* triangulation would have been eaten right through. */ - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperright, nextapex) > 0.0; - while (badedge) { - /* Eliminate the edge with an edge flip. As a result, the */ - /* right triangulation will have one more boundary triangle. */ - lprevself(nextedge); - sym(nextedge, topcasing); - lprevself(nextedge); - sym(nextedge, sidecasing); - bond(nextedge, topcasing); - bond(rightcand, sidecasing); - lprevself(rightcand); - sym(rightcand, outercasing); - lnextself(nextedge); - bond(nextedge, outercasing); - /* Correct the vertices to reflect the edge flip. */ - setorg(rightcand, NULL); - setdest(rightcand, lowerright); - setapex(rightcand, nextapex); - setorg(nextedge, upperright); - setdest(nextedge, NULL); - setapex(nextedge, nextapex); - /* Consider the newly exposed vertex. */ - upperright = nextapex; - /* What vertex would be exposed if another edge were deleted? */ - triedgecopy(sidecasing, nextedge); - apex(nextedge, nextapex); - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperright, nextapex) - > 0.0; - } else { - /* Avoid eating right through the triangulation. */ - badedge = 0; - } - } - } - } - if (leftfinished || (!rightfinished && - (incircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) { - /* Knit the triangulations, adding an edge from `lowerleft' */ - /* to `upperright'. */ - bond(baseedge, rightcand); - lprev(rightcand, baseedge); - setdest(baseedge, lowerleft); - lowerright = upperright; - sym(baseedge, rightcand); - apex(rightcand, upperright); - } else { - /* Knit the triangulations, adding an edge from `upperleft' */ - /* to `lowerright'. */ - bond(baseedge, leftcand); - lnext(leftcand, baseedge); - setorg(baseedge, lowerright); - lowerleft = upperleft; - sym(baseedge, leftcand); - apex(leftcand, upperleft); - } - if (verbose > 2) { - printf(" Connecting "); - printtriangle(&baseedge); - } - } + struct triedge leftcand, rightcand; + struct triedge baseedge; + struct triedge nextedge; + struct triedge sidecasing, topcasing, outercasing; + struct triedge checkedge; + point innerleftdest; + point innerrightorg; + point innerleftapex, innerrightapex; + point farleftpt, farrightpt; + point farleftapex, farrightapex; + point lowerleft, lowerright; + point upperleft, upperright; + point nextapex; + point checkvertex; + int changemade; + int badedge; + int leftfinished, rightfinished; + triangle ptr; /* Temporary variable used by sym(). */ + + dest( *innerleft, innerleftdest ); + apex( *innerleft, innerleftapex ); + org( *innerright, innerrightorg ); + apex( *innerright, innerrightapex ); + /* Special treatment for horizontal cuts. */ + if ( dwyer && ( axis == 1 ) ) { + org( *farleft, farleftpt ); + apex( *farleft, farleftapex ); + dest( *farright, farrightpt ); + apex( *farright, farrightapex ); + /* The pointers to the extremal points are shifted to point to the */ + /* topmost and bottommost point of each hull, rather than the */ + /* leftmost and rightmost points. */ + while ( farleftapex[1] < farleftpt[1] ) { + lnextself( *farleft ); + symself( *farleft ); + farleftpt = farleftapex; + apex( *farleft, farleftapex ); + } + sym( *innerleft, checkedge ); + apex( checkedge, checkvertex ); + while ( checkvertex[1] > innerleftdest[1] ) { + lnext( checkedge, *innerleft ); + innerleftapex = innerleftdest; + innerleftdest = checkvertex; + sym( *innerleft, checkedge ); + apex( checkedge, checkvertex ); + } + while ( innerrightapex[1] < innerrightorg[1] ) { + lnextself( *innerright ); + symself( *innerright ); + innerrightorg = innerrightapex; + apex( *innerright, innerrightapex ); + } + sym( *farright, checkedge ); + apex( checkedge, checkvertex ); + while ( checkvertex[1] > farrightpt[1] ) { + lnext( checkedge, *farright ); + farrightapex = farrightpt; + farrightpt = checkvertex; + sym( *farright, checkedge ); + apex( checkedge, checkvertex ); + } + } + /* Find a line tangent to and below both hulls. */ + do { + changemade = 0; + /* Make innerleftdest the "bottommost" point of the left hull. */ + if ( counterclockwise( innerleftdest, innerleftapex, innerrightorg ) > 0.0 ) { + lprevself( *innerleft ); + symself( *innerleft ); + innerleftdest = innerleftapex; + apex( *innerleft, innerleftapex ); + changemade = 1; + } + /* Make innerrightorg the "bottommost" point of the right hull. */ + if ( counterclockwise( innerrightapex, innerrightorg, innerleftdest ) > 0.0 ) { + lnextself( *innerright ); + symself( *innerright ); + innerrightorg = innerrightapex; + apex( *innerright, innerrightapex ); + changemade = 1; + } + } while ( changemade ); + /* Find the two candidates to be the next "gear tooth". */ + sym( *innerleft, leftcand ); + sym( *innerright, rightcand ); + /* Create the bottom new bounding triangle. */ + maketriangle( &baseedge ); + /* Connect it to the bounding boxes of the left and right triangulations. */ + bond( baseedge, *innerleft ); + lnextself( baseedge ); + bond( baseedge, *innerright ); + lnextself( baseedge ); + setorg( baseedge, innerrightorg ); + setdest( baseedge, innerleftdest ); + /* Apex is intentionally left NULL. */ + if ( verbose > 2 ) { + printf( " Creating base bounding " ); + printtriangle( &baseedge ); + } + /* Fix the extreme triangles if necessary. */ + org( *farleft, farleftpt ); + if ( innerleftdest == farleftpt ) { + lnext( baseedge, *farleft ); + } + dest( *farright, farrightpt ); + if ( innerrightorg == farrightpt ) { + lprev( baseedge, *farright ); + } + /* The vertices of the current knitting edge. */ + lowerleft = innerleftdest; + lowerright = innerrightorg; + /* The candidate vertices for knitting. */ + apex( leftcand, upperleft ); + apex( rightcand, upperright ); + /* Walk up the gap between the two triangulations, knitting them together. */ + while ( 1 ) { + /* Have we reached the top? (This isn't quite the right question, */ + /* because even though the left triangulation might seem finished now, */ + /* moving up on the right triangulation might reveal a new point of */ + /* the left triangulation. And vice-versa.) */ + leftfinished = counterclockwise( upperleft, lowerleft, lowerright ) <= 0.0; + rightfinished = counterclockwise( upperright, lowerleft, lowerright ) <= 0.0; + if ( leftfinished && rightfinished ) { + /* Create the top new bounding triangle. */ + maketriangle( &nextedge ); + setorg( nextedge, lowerleft ); + setdest( nextedge, lowerright ); + /* Apex is intentionally left NULL. */ + /* Connect it to the bounding boxes of the two triangulations. */ + bond( nextedge, baseedge ); + lnextself( nextedge ); + bond( nextedge, rightcand ); + lnextself( nextedge ); + bond( nextedge, leftcand ); + if ( verbose > 2 ) { + printf( " Creating top bounding " ); + printtriangle( &baseedge ); + } + /* Special treatment for horizontal cuts. */ + if ( dwyer && ( axis == 1 ) ) { + org( *farleft, farleftpt ); + apex( *farleft, farleftapex ); + dest( *farright, farrightpt ); + apex( *farright, farrightapex ); + sym( *farleft, checkedge ); + apex( checkedge, checkvertex ); + /* The pointers to the extremal points are restored to the leftmost */ + /* and rightmost points (rather than topmost and bottommost). */ + while ( checkvertex[0] < farleftpt[0] ) { + lprev( checkedge, *farleft ); + farleftapex = farleftpt; + farleftpt = checkvertex; + sym( *farleft, checkedge ); + apex( checkedge, checkvertex ); + } + while ( farrightapex[0] > farrightpt[0] ) { + lprevself( *farright ); + symself( *farright ); + farrightpt = farrightapex; + apex( *farright, farrightapex ); + } + } + return; + } + /* Consider eliminating edges from the left triangulation. */ + if ( !leftfinished ) { + /* What vertex would be exposed if an edge were deleted? */ + lprev( leftcand, nextedge ); + symself( nextedge ); + apex( nextedge, nextapex ); + /* If nextapex is NULL, then no vertex would be exposed; the */ + /* triangulation would have been eaten right through. */ + if ( nextapex != (point) NULL ) { + /* Check whether the edge is Delaunay. */ + badedge = incircle( lowerleft, lowerright, upperleft, nextapex ) > 0.0; + while ( badedge ) { + /* Eliminate the edge with an edge flip. As a result, the */ + /* left triangulation will have one more boundary triangle. */ + lnextself( nextedge ); + sym( nextedge, topcasing ); + lnextself( nextedge ); + sym( nextedge, sidecasing ); + bond( nextedge, topcasing ); + bond( leftcand, sidecasing ); + lnextself( leftcand ); + sym( leftcand, outercasing ); + lprevself( nextedge ); + bond( nextedge, outercasing ); + /* Correct the vertices to reflect the edge flip. */ + setorg( leftcand, lowerleft ); + setdest( leftcand, NULL ); + setapex( leftcand, nextapex ); + setorg( nextedge, NULL ); + setdest( nextedge, upperleft ); + setapex( nextedge, nextapex ); + /* Consider the newly exposed vertex. */ + upperleft = nextapex; + /* What vertex would be exposed if another edge were deleted? */ + triedgecopy( sidecasing, nextedge ); + apex( nextedge, nextapex ); + if ( nextapex != (point) NULL ) { + /* Check whether the edge is Delaunay. */ + badedge = incircle( lowerleft, lowerright, upperleft, nextapex ) + > 0.0; + } + else { + /* Avoid eating right through the triangulation. */ + badedge = 0; + } + } + } + } + /* Consider eliminating edges from the right triangulation. */ + if ( !rightfinished ) { + /* What vertex would be exposed if an edge were deleted? */ + lnext( rightcand, nextedge ); + symself( nextedge ); + apex( nextedge, nextapex ); + /* If nextapex is NULL, then no vertex would be exposed; the */ + /* triangulation would have been eaten right through. */ + if ( nextapex != (point) NULL ) { + /* Check whether the edge is Delaunay. */ + badedge = incircle( lowerleft, lowerright, upperright, nextapex ) > 0.0; + while ( badedge ) { + /* Eliminate the edge with an edge flip. As a result, the */ + /* right triangulation will have one more boundary triangle. */ + lprevself( nextedge ); + sym( nextedge, topcasing ); + lprevself( nextedge ); + sym( nextedge, sidecasing ); + bond( nextedge, topcasing ); + bond( rightcand, sidecasing ); + lprevself( rightcand ); + sym( rightcand, outercasing ); + lnextself( nextedge ); + bond( nextedge, outercasing ); + /* Correct the vertices to reflect the edge flip. */ + setorg( rightcand, NULL ); + setdest( rightcand, lowerright ); + setapex( rightcand, nextapex ); + setorg( nextedge, upperright ); + setdest( nextedge, NULL ); + setapex( nextedge, nextapex ); + /* Consider the newly exposed vertex. */ + upperright = nextapex; + /* What vertex would be exposed if another edge were deleted? */ + triedgecopy( sidecasing, nextedge ); + apex( nextedge, nextapex ); + if ( nextapex != (point) NULL ) { + /* Check whether the edge is Delaunay. */ + badedge = incircle( lowerleft, lowerright, upperright, nextapex ) + > 0.0; + } + else { + /* Avoid eating right through the triangulation. */ + badedge = 0; + } + } + } + } + if ( leftfinished || ( !rightfinished && + ( incircle( upperleft, lowerleft, lowerright, upperright ) > 0.0 ) ) ) { + /* Knit the triangulations, adding an edge from `lowerleft' */ + /* to `upperright'. */ + bond( baseedge, rightcand ); + lprev( rightcand, baseedge ); + setdest( baseedge, lowerleft ); + lowerright = upperright; + sym( baseedge, rightcand ); + apex( rightcand, upperright ); + } + else { + /* Knit the triangulations, adding an edge from `upperleft' */ + /* to `lowerright'. */ + bond( baseedge, leftcand ); + lnext( leftcand, baseedge ); + setorg( baseedge, lowerright ); + lowerleft = upperleft; + sym( baseedge, leftcand ); + apex( leftcand, upperleft ); + } + if ( verbose > 2 ) { + printf( " Connecting " ); + printtriangle( &baseedge ); + } + } } /*****************************************************************************/ @@ -7473,205 +7533,210 @@ int axis; /* */ /*****************************************************************************/ -void divconqrecurse(sortarray, vertices, axis, farleft, farright) -point *sortarray; +void divconqrecurse( sortarray, vertices, axis, farleft, farright ) +point * sortarray; int vertices; int axis; struct triedge *farleft; struct triedge *farright; { - struct triedge midtri, tri1, tri2, tri3; - struct triedge innerleft, innerright; - REAL area; - int divider; - - if (verbose > 2) { - printf(" Triangulating %d points.\n", vertices); - } - if (vertices == 2) { - /* The triangulation of two vertices is an edge. An edge is */ - /* represented by two bounding triangles. */ - maketriangle(farleft); - setorg(*farleft, sortarray[0]); - setdest(*farleft, sortarray[1]); - /* The apex is intentionally left NULL. */ - maketriangle(farright); - setorg(*farright, sortarray[1]); - setdest(*farright, sortarray[0]); - /* The apex is intentionally left NULL. */ - bond(*farleft, *farright); - lprevself(*farleft); - lnextself(*farright); - bond(*farleft, *farright); - lprevself(*farleft); - lnextself(*farright); - bond(*farleft, *farright); - if (verbose > 2) { - printf(" Creating "); - printtriangle(farleft); - printf(" Creating "); - printtriangle(farright); - } - /* Ensure that the origin of `farleft' is sortarray[0]. */ - lprev(*farright, *farleft); - return; - } else if (vertices == 3) { - /* The triangulation of three vertices is either a triangle (with */ - /* three bounding triangles) or two edges (with four bounding */ - /* triangles). In either case, four triangles are created. */ - maketriangle(&midtri); - maketriangle(&tri1); - maketriangle(&tri2); - maketriangle(&tri3); - area = counterclockwise(sortarray[0], sortarray[1], sortarray[2]); - if (area == 0.0) { - /* Three collinear points; the triangulation is two edges. */ - setorg(midtri, sortarray[0]); - setdest(midtri, sortarray[1]); - setorg(tri1, sortarray[1]); - setdest(tri1, sortarray[0]); - setorg(tri2, sortarray[2]); - setdest(tri2, sortarray[1]); - setorg(tri3, sortarray[1]); - setdest(tri3, sortarray[2]); - /* All apices are intentionally left NULL. */ - bond(midtri, tri1); - bond(tri2, tri3); - lnextself(midtri); - lprevself(tri1); - lnextself(tri2); - lprevself(tri3); - bond(midtri, tri3); - bond(tri1, tri2); - lnextself(midtri); - lprevself(tri1); - lnextself(tri2); - lprevself(tri3); - bond(midtri, tri1); - bond(tri2, tri3); - /* Ensure that the origin of `farleft' is sortarray[0]. */ - triedgecopy(tri1, *farleft); - /* Ensure that the destination of `farright' is sortarray[2]. */ - triedgecopy(tri2, *farright); - } else { - /* The three points are not collinear; the triangulation is one */ - /* triangle, namely `midtri'. */ - setorg(midtri, sortarray[0]); - setdest(tri1, sortarray[0]); - setorg(tri3, sortarray[0]); - /* Apices of tri1, tri2, and tri3 are left NULL. */ - if (area > 0.0) { - /* The vertices are in counterclockwise order. */ - setdest(midtri, sortarray[1]); - setorg(tri1, sortarray[1]); - setdest(tri2, sortarray[1]); - setapex(midtri, sortarray[2]); - setorg(tri2, sortarray[2]); - setdest(tri3, sortarray[2]); - } else { - /* The vertices are in clockwise order. */ - setdest(midtri, sortarray[2]); - setorg(tri1, sortarray[2]); - setdest(tri2, sortarray[2]); - setapex(midtri, sortarray[1]); - setorg(tri2, sortarray[1]); - setdest(tri3, sortarray[1]); - } - /* The topology does not depend on how the vertices are ordered. */ - bond(midtri, tri1); - lnextself(midtri); - bond(midtri, tri2); - lnextself(midtri); - bond(midtri, tri3); - lprevself(tri1); - lnextself(tri2); - bond(tri1, tri2); - lprevself(tri1); - lprevself(tri3); - bond(tri1, tri3); - lnextself(tri2); - lprevself(tri3); - bond(tri2, tri3); - /* Ensure that the origin of `farleft' is sortarray[0]. */ - triedgecopy(tri1, *farleft); - /* Ensure that the destination of `farright' is sortarray[2]. */ - if (area > 0.0) { - triedgecopy(tri2, *farright); - } else { - lnext(*farleft, *farright); - } - } - if (verbose > 2) { - printf(" Creating "); - printtriangle(&midtri); - printf(" Creating "); - printtriangle(&tri1); - printf(" Creating "); - printtriangle(&tri2); - printf(" Creating "); - printtriangle(&tri3); - } - return; - } else { - /* Split the vertices in half. */ - divider = vertices >> 1; - /* Recursively triangulate each half. */ - divconqrecurse(sortarray, divider, 1 - axis, farleft, &innerleft); - divconqrecurse(&sortarray[divider], vertices - divider, 1 - axis, - &innerright, farright); - if (verbose > 1) { - printf(" Joining triangulations with %d and %d vertices.\n", divider, - vertices - divider); - } - /* Merge the two triangulations into one. */ - mergehulls(farleft, &innerleft, &innerright, farright, axis); - } + struct triedge midtri, tri1, tri2, tri3; + struct triedge innerleft, innerright; + REAL area; + int divider; + + if ( verbose > 2 ) { + printf( " Triangulating %d points.\n", vertices ); + } + if ( vertices == 2 ) { + /* The triangulation of two vertices is an edge. An edge is */ + /* represented by two bounding triangles. */ + maketriangle( farleft ); + setorg( *farleft, sortarray[0] ); + setdest( *farleft, sortarray[1] ); + /* The apex is intentionally left NULL. */ + maketriangle( farright ); + setorg( *farright, sortarray[1] ); + setdest( *farright, sortarray[0] ); + /* The apex is intentionally left NULL. */ + bond( *farleft, *farright ); + lprevself( *farleft ); + lnextself( *farright ); + bond( *farleft, *farright ); + lprevself( *farleft ); + lnextself( *farright ); + bond( *farleft, *farright ); + if ( verbose > 2 ) { + printf( " Creating " ); + printtriangle( farleft ); + printf( " Creating " ); + printtriangle( farright ); + } + /* Ensure that the origin of `farleft' is sortarray[0]. */ + lprev( *farright, *farleft ); + return; + } + else if ( vertices == 3 ) { + /* The triangulation of three vertices is either a triangle (with */ + /* three bounding triangles) or two edges (with four bounding */ + /* triangles). In either case, four triangles are created. */ + maketriangle( &midtri ); + maketriangle( &tri1 ); + maketriangle( &tri2 ); + maketriangle( &tri3 ); + area = counterclockwise( sortarray[0], sortarray[1], sortarray[2] ); + if ( area == 0.0 ) { + /* Three collinear points; the triangulation is two edges. */ + setorg( midtri, sortarray[0] ); + setdest( midtri, sortarray[1] ); + setorg( tri1, sortarray[1] ); + setdest( tri1, sortarray[0] ); + setorg( tri2, sortarray[2] ); + setdest( tri2, sortarray[1] ); + setorg( tri3, sortarray[1] ); + setdest( tri3, sortarray[2] ); + /* All apices are intentionally left NULL. */ + bond( midtri, tri1 ); + bond( tri2, tri3 ); + lnextself( midtri ); + lprevself( tri1 ); + lnextself( tri2 ); + lprevself( tri3 ); + bond( midtri, tri3 ); + bond( tri1, tri2 ); + lnextself( midtri ); + lprevself( tri1 ); + lnextself( tri2 ); + lprevself( tri3 ); + bond( midtri, tri1 ); + bond( tri2, tri3 ); + /* Ensure that the origin of `farleft' is sortarray[0]. */ + triedgecopy( tri1, *farleft ); + /* Ensure that the destination of `farright' is sortarray[2]. */ + triedgecopy( tri2, *farright ); + } + else { + /* The three points are not collinear; the triangulation is one */ + /* triangle, namely `midtri'. */ + setorg( midtri, sortarray[0] ); + setdest( tri1, sortarray[0] ); + setorg( tri3, sortarray[0] ); + /* Apices of tri1, tri2, and tri3 are left NULL. */ + if ( area > 0.0 ) { + /* The vertices are in counterclockwise order. */ + setdest( midtri, sortarray[1] ); + setorg( tri1, sortarray[1] ); + setdest( tri2, sortarray[1] ); + setapex( midtri, sortarray[2] ); + setorg( tri2, sortarray[2] ); + setdest( tri3, sortarray[2] ); + } + else { + /* The vertices are in clockwise order. */ + setdest( midtri, sortarray[2] ); + setorg( tri1, sortarray[2] ); + setdest( tri2, sortarray[2] ); + setapex( midtri, sortarray[1] ); + setorg( tri2, sortarray[1] ); + setdest( tri3, sortarray[1] ); + } + /* The topology does not depend on how the vertices are ordered. */ + bond( midtri, tri1 ); + lnextself( midtri ); + bond( midtri, tri2 ); + lnextself( midtri ); + bond( midtri, tri3 ); + lprevself( tri1 ); + lnextself( tri2 ); + bond( tri1, tri2 ); + lprevself( tri1 ); + lprevself( tri3 ); + bond( tri1, tri3 ); + lnextself( tri2 ); + lprevself( tri3 ); + bond( tri2, tri3 ); + /* Ensure that the origin of `farleft' is sortarray[0]. */ + triedgecopy( tri1, *farleft ); + /* Ensure that the destination of `farright' is sortarray[2]. */ + if ( area > 0.0 ) { + triedgecopy( tri2, *farright ); + } + else { + lnext( *farleft, *farright ); + } + } + if ( verbose > 2 ) { + printf( " Creating " ); + printtriangle( &midtri ); + printf( " Creating " ); + printtriangle( &tri1 ); + printf( " Creating " ); + printtriangle( &tri2 ); + printf( " Creating " ); + printtriangle( &tri3 ); + } + return; + } + else { + /* Split the vertices in half. */ + divider = vertices >> 1; + /* Recursively triangulate each half. */ + divconqrecurse( sortarray, divider, 1 - axis, farleft, &innerleft ); + divconqrecurse( &sortarray[divider], vertices - divider, 1 - axis, + &innerright, farright ); + if ( verbose > 1 ) { + printf( " Joining triangulations with %d and %d vertices.\n", divider, + vertices - divider ); + } + /* Merge the two triangulations into one. */ + mergehulls( farleft, &innerleft, &innerright, farright, axis ); + } } -long removeghosts(startghost) +long removeghosts( startghost ) struct triedge *startghost; { - struct triedge searchedge; - struct triedge dissolveedge; - struct triedge deadtri; - point markorg; - long hullsize; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose) { - printf(" Removing ghost triangles.\n"); - } - /* Find an edge on the convex hull to start point location from. */ - lprev(*startghost, searchedge); - symself(searchedge); - dummytri[0] = encode(searchedge); - /* Remove the bounding box and count the convex hull edges. */ - triedgecopy(*startghost, dissolveedge); - hullsize = 0; - do { - hullsize++; - lnext(dissolveedge, deadtri); - lprevself(dissolveedge); - symself(dissolveedge); - /* If no PSLG is involved, set the boundary markers of all the points */ - /* on the convex hull. If a PSLG is used, this step is done later. */ - if (!poly) { - /* Watch out for the case where all the input points are collinear. */ - if (dissolveedge.tri != dummytri) { - org(dissolveedge, markorg); - if (pointmark(markorg) == 0) { - setpointmark(markorg, 1); - } - } - } - /* Remove a bounding triangle from a convex hull triangle. */ - dissolve(dissolveedge); - /* Find the next bounding triangle. */ - sym(deadtri, dissolveedge); - /* Delete the bounding triangle. */ - triangledealloc(deadtri.tri); - } while (!triedgeequal(dissolveedge, *startghost)); - return hullsize; + struct triedge searchedge; + struct triedge dissolveedge; + struct triedge deadtri; + point markorg; + long hullsize; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( verbose ) { + printf( " Removing ghost triangles.\n" ); + } + /* Find an edge on the convex hull to start point location from. */ + lprev( *startghost, searchedge ); + symself( searchedge ); + dummytri[0] = encode( searchedge ); + /* Remove the bounding box and count the convex hull edges. */ + triedgecopy( *startghost, dissolveedge ); + hullsize = 0; + do { + hullsize++; + lnext( dissolveedge, deadtri ); + lprevself( dissolveedge ); + symself( dissolveedge ); + /* If no PSLG is involved, set the boundary markers of all the points */ + /* on the convex hull. If a PSLG is used, this step is done later. */ + if ( !poly ) { + /* Watch out for the case where all the input points are collinear. */ + if ( dissolveedge.tri != dummytri ) { + org( dissolveedge, markorg ); + if ( pointmark( markorg ) == 0 ) { + setpointmark( markorg, 1 ); + } + } + } + /* Remove a bounding triangle from a convex hull triangle. */ + dissolve( dissolveedge ); + /* Find the next bounding triangle. */ + sym( deadtri, dissolveedge ); + /* Delete the bounding triangle. */ + triangledealloc( deadtri.tri ); + } while ( !triedgeequal( dissolveedge, *startghost ) ); + return hullsize; } /*****************************************************************************/ @@ -7684,66 +7749,66 @@ struct triedge *startghost; /* */ /*****************************************************************************/ -long divconqdelaunay() -{ - point *sortarray; - struct triedge hullleft, hullright; - int divider; - int i, j; - - /* Allocate an array of pointers to points for sorting. */ - sortarray = (point *) malloc(inpoints * sizeof(point)); - if (sortarray == (point *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - traversalinit(&points); - for (i = 0; i < inpoints; i++) { - sortarray[i] = pointtraverse(); - } - if (verbose) { - printf(" Sorting points.\n"); - } - /* Sort the points. */ - pointsort(sortarray, inpoints); - /* Discard duplicate points, which can really mess up the algorithm. */ - i = 0; - for (j = 1; j < inpoints; j++) { - if ((sortarray[i][0] == sortarray[j][0]) - && (sortarray[i][1] == sortarray[j][1])) { - if (!quiet) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - sortarray[j][0], sortarray[j][1]); - } +long divconqdelaunay(){ + point *sortarray; + struct triedge hullleft, hullright; + int divider; + int i, j; + + /* Allocate an array of pointers to points for sorting. */ + sortarray = (point *) malloc( inpoints * sizeof( point ) ); + if ( sortarray == (point *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + traversalinit( &points ); + for ( i = 0; i < inpoints; i++ ) { + sortarray[i] = pointtraverse(); + } + if ( verbose ) { + printf( " Sorting points.\n" ); + } + /* Sort the points. */ + pointsort( sortarray, inpoints ); + /* Discard duplicate points, which can really mess up the algorithm. */ + i = 0; + for ( j = 1; j < inpoints; j++ ) { + if ( ( sortarray[i][0] == sortarray[j][0] ) + && ( sortarray[i][1] == sortarray[j][1] ) ) { + if ( !quiet ) { + printf( + "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", + sortarray[j][0], sortarray[j][1] ); + } /* Commented out - would eliminate point from output .node file, but causes a failure if some segment has this point as an endpoint. setpointmark(sortarray[j], DEADPOINT); -*/ - } else { - i++; - sortarray[i] = sortarray[j]; - } - } - i++; - if (dwyer) { - /* Re-sort the array of points to accommodate alternating cuts. */ - divider = i >> 1; - if (i - divider >= 2) { - if (divider >= 2) { - alternateaxes(sortarray, divider, 1); - } - alternateaxes(&sortarray[divider], i - divider, 1); - } - } - if (verbose) { - printf(" Forming triangulation.\n"); - } - /* Form the Delaunay triangulation. */ - divconqrecurse(sortarray, i, 0, &hullleft, &hullright); - free(sortarray); - - return removeghosts(&hullleft); + */ + } + else { + i++; + sortarray[i] = sortarray[j]; + } + } + i++; + if ( dwyer ) { + /* Re-sort the array of points to accommodate alternating cuts. */ + divider = i >> 1; + if ( i - divider >= 2 ) { + if ( divider >= 2 ) { + alternateaxes( sortarray, divider, 1 ); + } + alternateaxes( &sortarray[divider], i - divider, 1 ); + } + } + if ( verbose ) { + printf( " Forming triangulation.\n" ); + } + /* Form the Delaunay triangulation. */ + divconqrecurse( sortarray, i, 0, &hullleft, &hullright ); + free( sortarray ); + + return removeghosts( &hullleft ); } /** **/ @@ -7767,50 +7832,49 @@ long divconqdelaunay() #ifndef REDUCED -void boundingbox() -{ - struct triedge inftri; /* Handle for the triangular bounding box. */ - REAL width; - - if (verbose) { - printf(" Creating triangular bounding box.\n"); - } - /* Find the width (or height, whichever is larger) of the triangulation. */ - width = xmax - xmin; - if (ymax - ymin > width) { - width = ymax - ymin; - } - if (width == 0.0) { - width = 1.0; - } - /* Create the vertices of the bounding box. */ - infpoint1 = (point) malloc(points.itembytes); - infpoint2 = (point) malloc(points.itembytes); - infpoint3 = (point) malloc(points.itembytes); - if ((infpoint1 == (point) NULL) || (infpoint2 == (point) NULL) - || (infpoint3 == (point) NULL)) { - printf("Error: Out of memory.\n"); - exit(1); - } - infpoint1[0] = xmin - 50.0 * width; - infpoint1[1] = ymin - 40.0 * width; - infpoint2[0] = xmax + 50.0 * width; - infpoint2[1] = ymin - 40.0 * width; - infpoint3[0] = 0.5 * (xmin + xmax); - infpoint3[1] = ymax + 60.0 * width; - - /* Create the bounding box. */ - maketriangle(&inftri); - setorg(inftri, infpoint1); - setdest(inftri, infpoint2); - setapex(inftri, infpoint3); - /* Link dummytri to the bounding box so we can always find an */ - /* edge to begin searching (point location) from. */ - dummytri[0] = (triangle) inftri.tri; - if (verbose > 2) { - printf(" Creating "); - printtriangle(&inftri); - } +void boundingbox(){ + struct triedge inftri; /* Handle for the triangular bounding box. */ + REAL width; + + if ( verbose ) { + printf( " Creating triangular bounding box.\n" ); + } + /* Find the width (or height, whichever is larger) of the triangulation. */ + width = xmax - xmin; + if ( ymax - ymin > width ) { + width = ymax - ymin; + } + if ( width == 0.0 ) { + width = 1.0; + } + /* Create the vertices of the bounding box. */ + infpoint1 = (point) malloc( points.itembytes ); + infpoint2 = (point) malloc( points.itembytes ); + infpoint3 = (point) malloc( points.itembytes ); + if ( ( infpoint1 == (point) NULL ) || ( infpoint2 == (point) NULL ) + || ( infpoint3 == (point) NULL ) ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + infpoint1[0] = xmin - 50.0 * width; + infpoint1[1] = ymin - 40.0 * width; + infpoint2[0] = xmax + 50.0 * width; + infpoint2[1] = ymin - 40.0 * width; + infpoint3[0] = 0.5 * ( xmin + xmax ); + infpoint3[1] = ymax + 60.0 * width; + + /* Create the bounding box. */ + maketriangle( &inftri ); + setorg( inftri, infpoint1 ); + setdest( inftri, infpoint2 ); + setapex( inftri, infpoint3 ); + /* Link dummytri to the bounding box so we can always find an */ + /* edge to begin searching (point location) from. */ + dummytri[0] = (triangle) inftri.tri; + if ( verbose > 2 ) { + printf( " Creating " ); + printtriangle( &inftri ); + } } #endif /* not REDUCED */ @@ -7829,83 +7893,82 @@ void boundingbox() #ifndef REDUCED -long removebox() -{ - struct triedge deadtri; - struct triedge searchedge; - struct triedge checkedge; - struct triedge nextedge, finaledge, dissolveedge; - point markorg; - long hullsize; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose) { - printf(" Removing triangular bounding box.\n"); - } - /* Find a boundary triangle. */ - nextedge.tri = dummytri; - nextedge.orient = 0; - symself(nextedge); - /* Mark a place to stop. */ - lprev(nextedge, finaledge); - lnextself(nextedge); - symself(nextedge); - /* Find a triangle (on the boundary of the point set) that isn't */ - /* a bounding box triangle. */ - lprev(nextedge, searchedge); - symself(searchedge); - /* Check whether nextedge is another boundary triangle */ - /* adjacent to the first one. */ - lnext(nextedge, checkedge); - symself(checkedge); - if (checkedge.tri == dummytri) { - /* Go on to the next triangle. There are only three boundary */ - /* triangles, and this next triangle cannot be the third one, */ - /* so it's safe to stop here. */ - lprevself(searchedge); - symself(searchedge); - } - /* Find a new boundary edge to search from, as the current search */ - /* edge lies on a bounding box triangle and will be deleted. */ - dummytri[0] = encode(searchedge); - hullsize = -2l; - while (!triedgeequal(nextedge, finaledge)) { - hullsize++; - lprev(nextedge, dissolveedge); - symself(dissolveedge); - /* If not using a PSLG, the vertices should be marked now. */ - /* (If using a PSLG, markhull() will do the job.) */ - if (!poly) { - /* Be careful! One must check for the case where all the input */ - /* points are collinear, and thus all the triangles are part of */ - /* the bounding box. Otherwise, the setpointmark() call below */ - /* will cause a bad pointer reference. */ - if (dissolveedge.tri != dummytri) { - org(dissolveedge, markorg); - if (pointmark(markorg) == 0) { - setpointmark(markorg, 1); - } - } - } - /* Disconnect the bounding box triangle from the mesh triangle. */ - dissolve(dissolveedge); - lnext(nextedge, deadtri); - sym(deadtri, nextedge); - /* Get rid of the bounding box triangle. */ - triangledealloc(deadtri.tri); - /* Do we need to turn the corner? */ - if (nextedge.tri == dummytri) { - /* Turn the corner. */ - triedgecopy(dissolveedge, nextedge); - } - } - triangledealloc(finaledge.tri); - - free(infpoint1); /* Deallocate the bounding box vertices. */ - free(infpoint2); - free(infpoint3); - - return hullsize; +long removebox(){ + struct triedge deadtri; + struct triedge searchedge; + struct triedge checkedge; + struct triedge nextedge, finaledge, dissolveedge; + point markorg; + long hullsize; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( verbose ) { + printf( " Removing triangular bounding box.\n" ); + } + /* Find a boundary triangle. */ + nextedge.tri = dummytri; + nextedge.orient = 0; + symself( nextedge ); + /* Mark a place to stop. */ + lprev( nextedge, finaledge ); + lnextself( nextedge ); + symself( nextedge ); + /* Find a triangle (on the boundary of the point set) that isn't */ + /* a bounding box triangle. */ + lprev( nextedge, searchedge ); + symself( searchedge ); + /* Check whether nextedge is another boundary triangle */ + /* adjacent to the first one. */ + lnext( nextedge, checkedge ); + symself( checkedge ); + if ( checkedge.tri == dummytri ) { + /* Go on to the next triangle. There are only three boundary */ + /* triangles, and this next triangle cannot be the third one, */ + /* so it's safe to stop here. */ + lprevself( searchedge ); + symself( searchedge ); + } + /* Find a new boundary edge to search from, as the current search */ + /* edge lies on a bounding box triangle and will be deleted. */ + dummytri[0] = encode( searchedge ); + hullsize = -2l; + while ( !triedgeequal( nextedge, finaledge ) ) { + hullsize++; + lprev( nextedge, dissolveedge ); + symself( dissolveedge ); + /* If not using a PSLG, the vertices should be marked now. */ + /* (If using a PSLG, markhull() will do the job.) */ + if ( !poly ) { + /* Be careful! One must check for the case where all the input */ + /* points are collinear, and thus all the triangles are part of */ + /* the bounding box. Otherwise, the setpointmark() call below */ + /* will cause a bad pointer reference. */ + if ( dissolveedge.tri != dummytri ) { + org( dissolveedge, markorg ); + if ( pointmark( markorg ) == 0 ) { + setpointmark( markorg, 1 ); + } + } + } + /* Disconnect the bounding box triangle from the mesh triangle. */ + dissolve( dissolveedge ); + lnext( nextedge, deadtri ); + sym( deadtri, nextedge ); + /* Get rid of the bounding box triangle. */ + triangledealloc( deadtri.tri ); + /* Do we need to turn the corner? */ + if ( nextedge.tri == dummytri ) { + /* Turn the corner. */ + triedgecopy( dissolveedge, nextedge ); + } + } + triangledealloc( finaledge.tri ); + + free( infpoint1 ); /* Deallocate the bounding box vertices. */ + free( infpoint2 ); + free( infpoint3 ); + + return hullsize; } #endif /* not REDUCED */ @@ -7919,39 +7982,38 @@ long removebox() #ifndef REDUCED -long incrementaldelaunay() -{ - struct triedge starttri; - point pointloop; - int i; - - /* Create a triangular bounding box. */ - boundingbox(); - if (verbose) { - printf(" Incrementally inserting points.\n"); - } - traversalinit(&points); - pointloop = pointtraverse(); - i = 1; - while (pointloop != (point) NULL) { - /* Find a boundary triangle to search from. */ - starttri.tri = (triangle *) NULL; - if (insertsite(pointloop, &starttri, (struct edge *) NULL, 0, 0) == - DUPLICATEPOINT) { - if (!quiet) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - pointloop[0], pointloop[1]); - } +long incrementaldelaunay(){ + struct triedge starttri; + point pointloop; + int i; + + /* Create a triangular bounding box. */ + boundingbox(); + if ( verbose ) { + printf( " Incrementally inserting points.\n" ); + } + traversalinit( &points ); + pointloop = pointtraverse(); + i = 1; + while ( pointloop != (point) NULL ) { + /* Find a boundary triangle to search from. */ + starttri.tri = (triangle *) NULL; + if ( insertsite( pointloop, &starttri, (struct edge *) NULL, 0, 0 ) == + DUPLICATEPOINT ) { + if ( !quiet ) { + printf( + "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", + pointloop[0], pointloop[1] ); + } /* Commented out - would eliminate point from output .node file. setpointmark(pointloop, DEADPOINT); -*/ - } - pointloop = pointtraverse(); - i++; - } - /* Remove the bounding box. */ - return removebox(); + */ + } + pointloop = pointtraverse(); + i++; + } + /* Remove the bounding box. */ + return removebox(); } #endif /* not REDUCED */ @@ -7966,398 +8028,417 @@ long incrementaldelaunay() #ifndef REDUCED -void eventheapinsert(heap, heapsize, newevent) +void eventheapinsert( heap, heapsize, newevent ) struct event **heap; int heapsize; struct event *newevent; { - REAL eventx, eventy; - int eventnum; - int parent; - int notdone; - - eventx = newevent->xkey; - eventy = newevent->ykey; - eventnum = heapsize; - notdone = eventnum > 0; - while (notdone) { - parent = (eventnum - 1) >> 1; - if ((heap[parent]->ykey < eventy) || - ((heap[parent]->ykey == eventy) - && (heap[parent]->xkey <= eventx))) { - notdone = 0; - } else { - heap[eventnum] = heap[parent]; - heap[eventnum]->heapposition = eventnum; - - eventnum = parent; - notdone = eventnum > 0; - } - } - heap[eventnum] = newevent; - newevent->heapposition = eventnum; + REAL eventx, eventy; + int eventnum; + int parent; + int notdone; + + eventx = newevent->xkey; + eventy = newevent->ykey; + eventnum = heapsize; + notdone = eventnum > 0; + while ( notdone ) { + parent = ( eventnum - 1 ) >> 1; + if ( ( heap[parent]->ykey < eventy ) || + ( ( heap[parent]->ykey == eventy ) + && ( heap[parent]->xkey <= eventx ) ) ) { + notdone = 0; + } + else { + heap[eventnum] = heap[parent]; + heap[eventnum]->heapposition = eventnum; + + eventnum = parent; + notdone = eventnum > 0; + } + } + heap[eventnum] = newevent; + newevent->heapposition = eventnum; } #endif /* not REDUCED */ #ifndef REDUCED -void eventheapify(heap, heapsize, eventnum) +void eventheapify( heap, heapsize, eventnum ) struct event **heap; int heapsize; int eventnum; { - struct event *thisevent; - REAL eventx, eventy; - int leftchild, rightchild; - int smallest; - int notdone; - - thisevent = heap[eventnum]; - eventx = thisevent->xkey; - eventy = thisevent->ykey; - leftchild = 2 * eventnum + 1; - notdone = leftchild < heapsize; - while (notdone) { - if ((heap[leftchild]->ykey < eventy) || - ((heap[leftchild]->ykey == eventy) - && (heap[leftchild]->xkey < eventx))) { - smallest = leftchild; - } else { - smallest = eventnum; - } - rightchild = leftchild + 1; - if (rightchild < heapsize) { - if ((heap[rightchild]->ykey < heap[smallest]->ykey) || - ((heap[rightchild]->ykey == heap[smallest]->ykey) - && (heap[rightchild]->xkey < heap[smallest]->xkey))) { - smallest = rightchild; - } - } - if (smallest == eventnum) { - notdone = 0; - } else { - heap[eventnum] = heap[smallest]; - heap[eventnum]->heapposition = eventnum; - heap[smallest] = thisevent; - thisevent->heapposition = smallest; - - eventnum = smallest; - leftchild = 2 * eventnum + 1; - notdone = leftchild < heapsize; - } - } + struct event *thisevent; + REAL eventx, eventy; + int leftchild, rightchild; + int smallest; + int notdone; + + thisevent = heap[eventnum]; + eventx = thisevent->xkey; + eventy = thisevent->ykey; + leftchild = 2 * eventnum + 1; + notdone = leftchild < heapsize; + while ( notdone ) { + if ( ( heap[leftchild]->ykey < eventy ) || + ( ( heap[leftchild]->ykey == eventy ) + && ( heap[leftchild]->xkey < eventx ) ) ) { + smallest = leftchild; + } + else { + smallest = eventnum; + } + rightchild = leftchild + 1; + if ( rightchild < heapsize ) { + if ( ( heap[rightchild]->ykey < heap[smallest]->ykey ) || + ( ( heap[rightchild]->ykey == heap[smallest]->ykey ) + && ( heap[rightchild]->xkey < heap[smallest]->xkey ) ) ) { + smallest = rightchild; + } + } + if ( smallest == eventnum ) { + notdone = 0; + } + else { + heap[eventnum] = heap[smallest]; + heap[eventnum]->heapposition = eventnum; + heap[smallest] = thisevent; + thisevent->heapposition = smallest; + + eventnum = smallest; + leftchild = 2 * eventnum + 1; + notdone = leftchild < heapsize; + } + } } #endif /* not REDUCED */ #ifndef REDUCED -void eventheapdelete(heap, heapsize, eventnum) +void eventheapdelete( heap, heapsize, eventnum ) struct event **heap; int heapsize; int eventnum; { - struct event *moveevent; - REAL eventx, eventy; - int parent; - int notdone; - - moveevent = heap[heapsize - 1]; - if (eventnum > 0) { - eventx = moveevent->xkey; - eventy = moveevent->ykey; - do { - parent = (eventnum - 1) >> 1; - if ((heap[parent]->ykey < eventy) || - ((heap[parent]->ykey == eventy) - && (heap[parent]->xkey <= eventx))) { - notdone = 0; - } else { - heap[eventnum] = heap[parent]; - heap[eventnum]->heapposition = eventnum; - - eventnum = parent; - notdone = eventnum > 0; - } - } while (notdone); - } - heap[eventnum] = moveevent; - moveevent->heapposition = eventnum; - eventheapify(heap, heapsize - 1, eventnum); + struct event *moveevent; + REAL eventx, eventy; + int parent; + int notdone; + + moveevent = heap[heapsize - 1]; + if ( eventnum > 0 ) { + eventx = moveevent->xkey; + eventy = moveevent->ykey; + do { + parent = ( eventnum - 1 ) >> 1; + if ( ( heap[parent]->ykey < eventy ) || + ( ( heap[parent]->ykey == eventy ) + && ( heap[parent]->xkey <= eventx ) ) ) { + notdone = 0; + } + else { + heap[eventnum] = heap[parent]; + heap[eventnum]->heapposition = eventnum; + + eventnum = parent; + notdone = eventnum > 0; + } + } while ( notdone ); + } + heap[eventnum] = moveevent; + moveevent->heapposition = eventnum; + eventheapify( heap, heapsize - 1, eventnum ); } #endif /* not REDUCED */ #ifndef REDUCED -void createeventheap(eventheap, events, freeevents) +void createeventheap( eventheap, events, freeevents ) struct event ***eventheap; struct event **events; struct event **freeevents; { - point thispoint; - int maxevents; - int i; - - maxevents = (3 * inpoints) / 2; - *eventheap = (struct event **) malloc(maxevents * sizeof(struct event *)); - if (*eventheap == (struct event **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - *events = (struct event *) malloc(maxevents * sizeof(struct event)); - if (*events == (struct event *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - traversalinit(&points); - for (i = 0; i < inpoints; i++) { - thispoint = pointtraverse(); - (*events)[i].eventptr = (VOID *) thispoint; - (*events)[i].xkey = thispoint[0]; - (*events)[i].ykey = thispoint[1]; - eventheapinsert(*eventheap, i, *events + i); - } - *freeevents = (struct event *) NULL; - for (i = maxevents - 1; i >= inpoints; i--) { - (*events)[i].eventptr = (VOID *) *freeevents; - *freeevents = *events + i; - } + point thispoint; + int maxevents; + int i; + + maxevents = ( 3 * inpoints ) / 2; + *eventheap = (struct event **) malloc( maxevents * sizeof( struct event * ) ); + if ( *eventheap == (struct event **) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + *events = (struct event *) malloc( maxevents * sizeof( struct event ) ); + if ( *events == (struct event *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + traversalinit( &points ); + for ( i = 0; i < inpoints; i++ ) { + thispoint = pointtraverse(); + ( *events )[i].eventptr = (VOID *) thispoint; + ( *events )[i].xkey = thispoint[0]; + ( *events )[i].ykey = thispoint[1]; + eventheapinsert( *eventheap, i, *events + i ); + } + *freeevents = (struct event *) NULL; + for ( i = maxevents - 1; i >= inpoints; i-- ) { + ( *events )[i].eventptr = (VOID *) *freeevents; + *freeevents = *events + i; + } } #endif /* not REDUCED */ #ifndef REDUCED -int rightofhyperbola(fronttri, newsite) +int rightofhyperbola( fronttri, newsite ) struct triedge *fronttri; point newsite; { - point leftpoint, rightpoint; - REAL dxa, dya, dxb, dyb; - - hyperbolacount++; - - dest(*fronttri, leftpoint); - apex(*fronttri, rightpoint); - if ((leftpoint[1] < rightpoint[1]) - || ((leftpoint[1] == rightpoint[1]) && (leftpoint[0] < rightpoint[0]))) { - if (newsite[0] >= rightpoint[0]) { - return 1; - } - } else { - if (newsite[0] <= leftpoint[0]) { - return 0; - } - } - dxa = leftpoint[0] - newsite[0]; - dya = leftpoint[1] - newsite[1]; - dxb = rightpoint[0] - newsite[0]; - dyb = rightpoint[1] - newsite[1]; - return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya); + point leftpoint, rightpoint; + REAL dxa, dya, dxb, dyb; + + hyperbolacount++; + + dest( *fronttri, leftpoint ); + apex( *fronttri, rightpoint ); + if ( ( leftpoint[1] < rightpoint[1] ) + || ( ( leftpoint[1] == rightpoint[1] ) && ( leftpoint[0] < rightpoint[0] ) ) ) { + if ( newsite[0] >= rightpoint[0] ) { + return 1; + } + } + else { + if ( newsite[0] <= leftpoint[0] ) { + return 0; + } + } + dxa = leftpoint[0] - newsite[0]; + dya = leftpoint[1] - newsite[1]; + dxb = rightpoint[0] - newsite[0]; + dyb = rightpoint[1] - newsite[1]; + return dya * ( dxb * dxb + dyb * dyb ) > dyb * ( dxa * dxa + dya * dya ); } #endif /* not REDUCED */ #ifndef REDUCED -REAL circletop(pa, pb, pc, ccwabc) +REAL circletop( pa, pb, pc, ccwabc ) point pa; point pb; point pc; REAL ccwabc; { - REAL xac, yac, xbc, ybc, xab, yab; - REAL aclen2, bclen2, ablen2; - - circletopcount++; - - xac = pa[0] - pc[0]; - yac = pa[1] - pc[1]; - xbc = pb[0] - pc[0]; - ybc = pb[1] - pc[1]; - xab = pa[0] - pb[0]; - yab = pa[1] - pb[1]; - aclen2 = xac * xac + yac * yac; - bclen2 = xbc * xbc + ybc * ybc; - ablen2 = xab * xab + yab * yab; - return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2)) - / (2.0 * ccwabc); + REAL xac, yac, xbc, ybc, xab, yab; + REAL aclen2, bclen2, ablen2; + + circletopcount++; + + xac = pa[0] - pc[0]; + yac = pa[1] - pc[1]; + xbc = pb[0] - pc[0]; + ybc = pb[1] - pc[1]; + xab = pa[0] - pb[0]; + yab = pa[1] - pb[1]; + aclen2 = xac * xac + yac * yac; + bclen2 = xbc * xbc + ybc * ybc; + ablen2 = xab * xab + yab * yab; + return pc[1] + ( xac * bclen2 - xbc * aclen2 + sqrt( aclen2 * bclen2 * ablen2 ) ) + / ( 2.0 * ccwabc ); } #endif /* not REDUCED */ #ifndef REDUCED -void check4deadevent(checktri, freeevents, eventheap, heapsize) +void check4deadevent( checktri, freeevents, eventheap, heapsize ) struct triedge *checktri; struct event **freeevents; struct event **eventheap; int *heapsize; { - struct event *deadevent; - point eventpoint; - int eventnum; - - org(*checktri, eventpoint); - if (eventpoint != (point) NULL) { - deadevent = (struct event *) eventpoint; - eventnum = deadevent->heapposition; - deadevent->eventptr = (VOID *) *freeevents; - *freeevents = deadevent; - eventheapdelete(eventheap, *heapsize, eventnum); - (*heapsize)--; - setorg(*checktri, NULL); - } + struct event *deadevent; + point eventpoint; + int eventnum; + + org( *checktri, eventpoint ); + if ( eventpoint != (point) NULL ) { + deadevent = (struct event *) eventpoint; + eventnum = deadevent->heapposition; + deadevent->eventptr = (VOID *) *freeevents; + *freeevents = deadevent; + eventheapdelete( eventheap, *heapsize, eventnum ); + ( *heapsize )--; + setorg( *checktri, NULL ); + } } #endif /* not REDUCED */ #ifndef REDUCED -struct splaynode *splay(splaytree, searchpoint, searchtri) +struct splaynode *splay( splaytree, searchpoint, searchtri ) struct splaynode *splaytree; point searchpoint; struct triedge *searchtri; { - struct splaynode *child, *grandchild; - struct splaynode *lefttree, *righttree; - struct splaynode *leftright; - point checkpoint; - int rightofroot, rightofchild; - - if (splaytree == (struct splaynode *) NULL) { - return (struct splaynode *) NULL; - } - dest(splaytree->keyedge, checkpoint); - if (checkpoint == splaytree->keydest) { - rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint); - if (rightofroot) { - triedgecopy(splaytree->keyedge, *searchtri); - child = splaytree->rchild; - } else { - child = splaytree->lchild; - } - if (child == (struct splaynode *) NULL) { - return splaytree; - } - dest(child->keyedge, checkpoint); - if (checkpoint != child->keydest) { - child = splay(child, searchpoint, searchtri); - if (child == (struct splaynode *) NULL) { - if (rightofroot) { - splaytree->rchild = (struct splaynode *) NULL; - } else { - splaytree->lchild = (struct splaynode *) NULL; - } - return splaytree; - } - } - rightofchild = rightofhyperbola(&child->keyedge, searchpoint); - if (rightofchild) { - triedgecopy(child->keyedge, *searchtri); - grandchild = splay(child->rchild, searchpoint, searchtri); - child->rchild = grandchild; - } else { - grandchild = splay(child->lchild, searchpoint, searchtri); - child->lchild = grandchild; - } - if (grandchild == (struct splaynode *) NULL) { - if (rightofroot) { - splaytree->rchild = child->lchild; - child->lchild = splaytree; - } else { - splaytree->lchild = child->rchild; - child->rchild = splaytree; - } - return child; - } - if (rightofchild) { - if (rightofroot) { - splaytree->rchild = child->lchild; - child->lchild = splaytree; - } else { - splaytree->lchild = grandchild->rchild; - grandchild->rchild = splaytree; - } - child->rchild = grandchild->lchild; - grandchild->lchild = child; - } else { - if (rightofroot) { - splaytree->rchild = grandchild->lchild; - grandchild->lchild = splaytree; - } else { - splaytree->lchild = child->rchild; - child->rchild = splaytree; - } - child->lchild = grandchild->rchild; - grandchild->rchild = child; - } - return grandchild; - } else { - lefttree = splay(splaytree->lchild, searchpoint, searchtri); - righttree = splay(splaytree->rchild, searchpoint, searchtri); - - pooldealloc(&splaynodes, (VOID *) splaytree); - if (lefttree == (struct splaynode *) NULL) { - return righttree; - } else if (righttree == (struct splaynode *) NULL) { - return lefttree; - } else if (lefttree->rchild == (struct splaynode *) NULL) { - lefttree->rchild = righttree->lchild; - righttree->lchild = lefttree; - return righttree; - } else if (righttree->lchild == (struct splaynode *) NULL) { - righttree->lchild = lefttree->rchild; - lefttree->rchild = righttree; - return lefttree; - } else { + struct splaynode *child, *grandchild; + struct splaynode *lefttree, *righttree; + struct splaynode *leftright; + point checkpoint; + int rightofroot, rightofchild; + + if ( splaytree == (struct splaynode *) NULL ) { + return (struct splaynode *) NULL; + } + dest( splaytree->keyedge, checkpoint ); + if ( checkpoint == splaytree->keydest ) { + rightofroot = rightofhyperbola( &splaytree->keyedge, searchpoint ); + if ( rightofroot ) { + triedgecopy( splaytree->keyedge, *searchtri ); + child = splaytree->rchild; + } + else { + child = splaytree->lchild; + } + if ( child == (struct splaynode *) NULL ) { + return splaytree; + } + dest( child->keyedge, checkpoint ); + if ( checkpoint != child->keydest ) { + child = splay( child, searchpoint, searchtri ); + if ( child == (struct splaynode *) NULL ) { + if ( rightofroot ) { + splaytree->rchild = (struct splaynode *) NULL; + } + else { + splaytree->lchild = (struct splaynode *) NULL; + } + return splaytree; + } + } + rightofchild = rightofhyperbola( &child->keyedge, searchpoint ); + if ( rightofchild ) { + triedgecopy( child->keyedge, *searchtri ); + grandchild = splay( child->rchild, searchpoint, searchtri ); + child->rchild = grandchild; + } + else { + grandchild = splay( child->lchild, searchpoint, searchtri ); + child->lchild = grandchild; + } + if ( grandchild == (struct splaynode *) NULL ) { + if ( rightofroot ) { + splaytree->rchild = child->lchild; + child->lchild = splaytree; + } + else { + splaytree->lchild = child->rchild; + child->rchild = splaytree; + } + return child; + } + if ( rightofchild ) { + if ( rightofroot ) { + splaytree->rchild = child->lchild; + child->lchild = splaytree; + } + else { + splaytree->lchild = grandchild->rchild; + grandchild->rchild = splaytree; + } + child->rchild = grandchild->lchild; + grandchild->lchild = child; + } + else { + if ( rightofroot ) { + splaytree->rchild = grandchild->lchild; + grandchild->lchild = splaytree; + } + else { + splaytree->lchild = child->rchild; + child->rchild = splaytree; + } + child->lchild = grandchild->rchild; + grandchild->rchild = child; + } + return grandchild; + } + else { + lefttree = splay( splaytree->lchild, searchpoint, searchtri ); + righttree = splay( splaytree->rchild, searchpoint, searchtri ); + + pooldealloc( &splaynodes, (VOID *) splaytree ); + if ( lefttree == (struct splaynode *) NULL ) { + return righttree; + } + else if ( righttree == (struct splaynode *) NULL ) { + return lefttree; + } + else if ( lefttree->rchild == (struct splaynode *) NULL ) { + lefttree->rchild = righttree->lchild; + righttree->lchild = lefttree; + return righttree; + } + else if ( righttree->lchild == (struct splaynode *) NULL ) { + righttree->lchild = lefttree->rchild; + lefttree->rchild = righttree; + return lefttree; + } + else { /* printf("Holy Toledo!!!\n"); */ - leftright = lefttree->rchild; - while (leftright->rchild != (struct splaynode *) NULL) { - leftright = leftright->rchild; - } - leftright->rchild = righttree; - return lefttree; - } - } + leftright = lefttree->rchild; + while ( leftright->rchild != (struct splaynode *) NULL ) { + leftright = leftright->rchild; + } + leftright->rchild = righttree; + return lefttree; + } + } } #endif /* not REDUCED */ #ifndef REDUCED -struct splaynode *splayinsert(splayroot, newkey, searchpoint) +struct splaynode *splayinsert( splayroot, newkey, searchpoint ) struct splaynode *splayroot; struct triedge *newkey; point searchpoint; { - struct splaynode *newsplaynode; - - newsplaynode = (struct splaynode *) poolalloc(&splaynodes); - triedgecopy(*newkey, newsplaynode->keyedge); - dest(*newkey, newsplaynode->keydest); - if (splayroot == (struct splaynode *) NULL) { - newsplaynode->lchild = (struct splaynode *) NULL; - newsplaynode->rchild = (struct splaynode *) NULL; - } else if (rightofhyperbola(&splayroot->keyedge, searchpoint)) { - newsplaynode->lchild = splayroot; - newsplaynode->rchild = splayroot->rchild; - splayroot->rchild = (struct splaynode *) NULL; - } else { - newsplaynode->lchild = splayroot->lchild; - newsplaynode->rchild = splayroot; - splayroot->lchild = (struct splaynode *) NULL; - } - return newsplaynode; + struct splaynode *newsplaynode; + + newsplaynode = (struct splaynode *) poolalloc( &splaynodes ); + triedgecopy( *newkey, newsplaynode->keyedge ); + dest( *newkey, newsplaynode->keydest ); + if ( splayroot == (struct splaynode *) NULL ) { + newsplaynode->lchild = (struct splaynode *) NULL; + newsplaynode->rchild = (struct splaynode *) NULL; + } + else if ( rightofhyperbola( &splayroot->keyedge, searchpoint ) ) { + newsplaynode->lchild = splayroot; + newsplaynode->rchild = splayroot->rchild; + splayroot->rchild = (struct splaynode *) NULL; + } + else { + newsplaynode->lchild = splayroot->lchild; + newsplaynode->rchild = splayroot; + splayroot->lchild = (struct splaynode *) NULL; + } + return newsplaynode; } #endif /* not REDUCED */ #ifndef REDUCED -struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy) +struct splaynode *circletopinsert( splayroot, newkey, pa, pb, pc, topy ) struct splaynode *splayroot; struct triedge *newkey; point pa; @@ -8365,176 +8446,177 @@ point pb; point pc; REAL topy; { - REAL ccwabc; - REAL xac, yac, xbc, ybc; - REAL aclen2, bclen2; - REAL searchpoint[2]; - struct triedge dummytri; - - ccwabc = counterclockwise(pa, pb, pc); - xac = pa[0] - pc[0]; - yac = pa[1] - pc[1]; - xbc = pb[0] - pc[0]; - ybc = pb[1] - pc[1]; - aclen2 = xac * xac + yac * yac; - bclen2 = xbc * xbc + ybc * ybc; - searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc); - searchpoint[1] = topy; - return splayinsert(splay(splayroot, (point) searchpoint, &dummytri), newkey, - (point) searchpoint); + REAL ccwabc; + REAL xac, yac, xbc, ybc; + REAL aclen2, bclen2; + REAL searchpoint[2]; + struct triedge dummytri; + + ccwabc = counterclockwise( pa, pb, pc ); + xac = pa[0] - pc[0]; + yac = pa[1] - pc[1]; + xbc = pb[0] - pc[0]; + ybc = pb[1] - pc[1]; + aclen2 = xac * xac + yac * yac; + bclen2 = xbc * xbc + ybc * ybc; + searchpoint[0] = pc[0] - ( yac * bclen2 - ybc * aclen2 ) / ( 2.0 * ccwabc ); + searchpoint[1] = topy; + return splayinsert( splay( splayroot, (point) searchpoint, &dummytri ), newkey, + (point) searchpoint ); } #endif /* not REDUCED */ #ifndef REDUCED -struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri, - farright) +struct splaynode *frontlocate( splayroot, bottommost, searchpoint, searchtri, + farright ) struct splaynode *splayroot; struct triedge *bottommost; point searchpoint; struct triedge *searchtri; int *farright; { - int farrightflag; - triangle ptr; /* Temporary variable used by onext(). */ - - triedgecopy(*bottommost, *searchtri); - splayroot = splay(splayroot, searchpoint, searchtri); - - farrightflag = 0; - while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) { - onextself(*searchtri); - farrightflag = triedgeequal(*searchtri, *bottommost); - } - *farright = farrightflag; - return splayroot; + int farrightflag; + triangle ptr; /* Temporary variable used by onext(). */ + + triedgecopy( *bottommost, *searchtri ); + splayroot = splay( splayroot, searchpoint, searchtri ); + + farrightflag = 0; + while ( !farrightflag && rightofhyperbola( searchtri, searchpoint ) ) { + onextself( *searchtri ); + farrightflag = triedgeequal( *searchtri, *bottommost ); + } + *farright = farrightflag; + return splayroot; } #endif /* not REDUCED */ #ifndef REDUCED -long sweeplinedelaunay() -{ - struct event **eventheap; - struct event *events; - struct event *freeevents; - struct event *nextevent; - struct event *newevent; - struct splaynode *splayroot; - struct triedge bottommost; - struct triedge searchtri; - struct triedge fliptri; - struct triedge lefttri, righttri, farlefttri, farrighttri; - struct triedge inserttri; - point firstpoint, secondpoint; - point nextpoint, lastpoint; - point connectpoint; - point leftpoint, midpoint, rightpoint; - REAL lefttest, righttest; - int heapsize; - int check4events, farrightflag; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - - poolinit(&splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK, POINTER, - 0); - splayroot = (struct splaynode *) NULL; - - if (verbose) { - printf(" Placing points in event heap.\n"); - } - createeventheap(&eventheap, &events, &freeevents); - heapsize = inpoints; - - if (verbose) { - printf(" Forming triangulation.\n"); - } - maketriangle(&lefttri); - maketriangle(&righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - firstpoint = (point) eventheap[0]->eventptr; - eventheap[0]->eventptr = (VOID *) freeevents; - freeevents = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - do { - if (heapsize == 0) { - printf("Error: Input points are all identical.\n"); - exit(1); - } - secondpoint = (point) eventheap[0]->eventptr; - eventheap[0]->eventptr = (VOID *) freeevents; - freeevents = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - if ((firstpoint[0] == secondpoint[0]) - && (firstpoint[1] == secondpoint[1])) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - secondpoint[0], secondpoint[1]); +long sweeplinedelaunay(){ + struct event **eventheap; + struct event *events; + struct event *freeevents; + struct event *nextevent; + struct event *newevent; + struct splaynode *splayroot; + struct triedge bottommost; + struct triedge searchtri; + struct triedge fliptri; + struct triedge lefttri, righttri, farlefttri, farrighttri; + struct triedge inserttri; + point firstpoint, secondpoint; + point nextpoint, lastpoint; + point connectpoint; + point leftpoint, midpoint, rightpoint; + REAL lefttest, righttest; + int heapsize; + int check4events, farrightflag; + triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ + + poolinit( &splaynodes, sizeof( struct splaynode ), SPLAYNODEPERBLOCK, POINTER, + 0 ); + splayroot = (struct splaynode *) NULL; + + if ( verbose ) { + printf( " Placing points in event heap.\n" ); + } + createeventheap( &eventheap, &events, &freeevents ); + heapsize = inpoints; + + if ( verbose ) { + printf( " Forming triangulation.\n" ); + } + maketriangle( &lefttri ); + maketriangle( &righttri ); + bond( lefttri, righttri ); + lnextself( lefttri ); + lprevself( righttri ); + bond( lefttri, righttri ); + lnextself( lefttri ); + lprevself( righttri ); + bond( lefttri, righttri ); + firstpoint = (point) eventheap[0]->eventptr; + eventheap[0]->eventptr = (VOID *) freeevents; + freeevents = eventheap[0]; + eventheapdelete( eventheap, heapsize, 0 ); + heapsize--; + do { + if ( heapsize == 0 ) { + printf( "Error: Input points are all identical.\n" ); + exit( 1 ); + } + secondpoint = (point) eventheap[0]->eventptr; + eventheap[0]->eventptr = (VOID *) freeevents; + freeevents = eventheap[0]; + eventheapdelete( eventheap, heapsize, 0 ); + heapsize--; + if ( ( firstpoint[0] == secondpoint[0] ) + && ( firstpoint[1] == secondpoint[1] ) ) { + printf( + "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", + secondpoint[0], secondpoint[1] ); /* Commented out - would eliminate point from output .node file. setpointmark(secondpoint, DEADPOINT); -*/ - } - } while ((firstpoint[0] == secondpoint[0]) - && (firstpoint[1] == secondpoint[1])); - setorg(lefttri, firstpoint); - setdest(lefttri, secondpoint); - setorg(righttri, secondpoint); - setdest(righttri, firstpoint); - lprev(lefttri, bottommost); - lastpoint = secondpoint; - while (heapsize > 0) { - nextevent = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - check4events = 1; - if (nextevent->xkey < xmin) { - decode(nextevent->eventptr, fliptri); - oprev(fliptri, farlefttri); - check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize); - onext(fliptri, farrighttri); - check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize); - - if (triedgeequal(farlefttri, bottommost)) { - lprev(fliptri, bottommost); - } - flip(&fliptri); - setapex(fliptri, NULL); - lprev(fliptri, lefttri); - lnext(fliptri, righttri); - sym(lefttri, farlefttri); - - if (randomnation(SAMPLERATE) == 0) { - symself(fliptri); - dest(fliptri, leftpoint); - apex(fliptri, midpoint); - org(fliptri, rightpoint); - splayroot = circletopinsert(splayroot, &lefttri, leftpoint, midpoint, - rightpoint, nextevent->ykey); - } - } else { - nextpoint = (point) nextevent->eventptr; - if ((nextpoint[0] == lastpoint[0]) && (nextpoint[1] == lastpoint[1])) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - nextpoint[0], nextpoint[1]); + */ + } + } while ( ( firstpoint[0] == secondpoint[0] ) + && ( firstpoint[1] == secondpoint[1] ) ); + setorg( lefttri, firstpoint ); + setdest( lefttri, secondpoint ); + setorg( righttri, secondpoint ); + setdest( righttri, firstpoint ); + lprev( lefttri, bottommost ); + lastpoint = secondpoint; + while ( heapsize > 0 ) { + nextevent = eventheap[0]; + eventheapdelete( eventheap, heapsize, 0 ); + heapsize--; + check4events = 1; + if ( nextevent->xkey < xmin ) { + decode( nextevent->eventptr, fliptri ); + oprev( fliptri, farlefttri ); + check4deadevent( &farlefttri, &freeevents, eventheap, &heapsize ); + onext( fliptri, farrighttri ); + check4deadevent( &farrighttri, &freeevents, eventheap, &heapsize ); + + if ( triedgeequal( farlefttri, bottommost ) ) { + lprev( fliptri, bottommost ); + } + flip( &fliptri ); + setapex( fliptri, NULL ); + lprev( fliptri, lefttri ); + lnext( fliptri, righttri ); + sym( lefttri, farlefttri ); + + if ( randomnation( SAMPLERATE ) == 0 ) { + symself( fliptri ); + dest( fliptri, leftpoint ); + apex( fliptri, midpoint ); + org( fliptri, rightpoint ); + splayroot = circletopinsert( splayroot, &lefttri, leftpoint, midpoint, + rightpoint, nextevent->ykey ); + } + } + else { + nextpoint = (point) nextevent->eventptr; + if ( ( nextpoint[0] == lastpoint[0] ) && ( nextpoint[1] == lastpoint[1] ) ) { + printf( + "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", + nextpoint[0], nextpoint[1] ); /* Commented out - would eliminate point from output .node file. setpointmark(nextpoint, DEADPOINT); -*/ - check4events = 0; - } else { - lastpoint = nextpoint; - - splayroot = frontlocate(splayroot, &bottommost, nextpoint, &searchtri, - &farrightflag); + */ + check4events = 0; + } + else { + lastpoint = nextpoint; + + splayroot = frontlocate( splayroot, &bottommost, nextpoint, &searchtri, + &farrightflag ); /* triedgecopy(bottommost, searchtri); farrightflag = 0; @@ -8542,79 +8624,80 @@ long sweeplinedelaunay() onextself(searchtri); farrightflag = triedgeequal(searchtri, bottommost); } -*/ - - check4deadevent(&searchtri, &freeevents, eventheap, &heapsize); - - triedgecopy(searchtri, farrighttri); - sym(searchtri, farlefttri); - maketriangle(&lefttri); - maketriangle(&righttri); - dest(farrighttri, connectpoint); - setorg(lefttri, connectpoint); - setdest(lefttri, nextpoint); - setorg(righttri, nextpoint); - setdest(righttri, connectpoint); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, farlefttri); - bond(righttri, farrighttri); - if (!farrightflag && triedgeequal(farrighttri, bottommost)) { - triedgecopy(lefttri, bottommost); - } + */ + + check4deadevent( &searchtri, &freeevents, eventheap, &heapsize ); + + triedgecopy( searchtri, farrighttri ); + sym( searchtri, farlefttri ); + maketriangle( &lefttri ); + maketriangle( &righttri ); + dest( farrighttri, connectpoint ); + setorg( lefttri, connectpoint ); + setdest( lefttri, nextpoint ); + setorg( righttri, nextpoint ); + setdest( righttri, connectpoint ); + bond( lefttri, righttri ); + lnextself( lefttri ); + lprevself( righttri ); + bond( lefttri, righttri ); + lnextself( lefttri ); + lprevself( righttri ); + bond( lefttri, farlefttri ); + bond( righttri, farrighttri ); + if ( !farrightflag && triedgeequal( farrighttri, bottommost ) ) { + triedgecopy( lefttri, bottommost ); + } + + if ( randomnation( SAMPLERATE ) == 0 ) { + splayroot = splayinsert( splayroot, &lefttri, nextpoint ); + } + else if ( randomnation( SAMPLERATE ) == 0 ) { + lnext( righttri, inserttri ); + splayroot = splayinsert( splayroot, &inserttri, nextpoint ); + } + } + } + nextevent->eventptr = (VOID *) freeevents; + freeevents = nextevent; + + if ( check4events ) { + apex( farlefttri, leftpoint ); + dest( lefttri, midpoint ); + apex( lefttri, rightpoint ); + lefttest = counterclockwise( leftpoint, midpoint, rightpoint ); + if ( lefttest > 0.0 ) { + newevent = freeevents; + freeevents = (struct event *) freeevents->eventptr; + newevent->xkey = xminextreme; + newevent->ykey = circletop( leftpoint, midpoint, rightpoint, + lefttest ); + newevent->eventptr = (VOID *) encode( lefttri ); + eventheapinsert( eventheap, heapsize, newevent ); + heapsize++; + setorg( lefttri, newevent ); + } + apex( righttri, leftpoint ); + org( righttri, midpoint ); + apex( farrighttri, rightpoint ); + righttest = counterclockwise( leftpoint, midpoint, rightpoint ); + if ( righttest > 0.0 ) { + newevent = freeevents; + freeevents = (struct event *) freeevents->eventptr; + newevent->xkey = xminextreme; + newevent->ykey = circletop( leftpoint, midpoint, rightpoint, + righttest ); + newevent->eventptr = (VOID *) encode( farrighttri ); + eventheapinsert( eventheap, heapsize, newevent ); + heapsize++; + setorg( farrighttri, newevent ); + } + } + } - if (randomnation(SAMPLERATE) == 0) { - splayroot = splayinsert(splayroot, &lefttri, nextpoint); - } else if (randomnation(SAMPLERATE) == 0) { - lnext(righttri, inserttri); - splayroot = splayinsert(splayroot, &inserttri, nextpoint); - } - } - } - nextevent->eventptr = (VOID *) freeevents; - freeevents = nextevent; - - if (check4events) { - apex(farlefttri, leftpoint); - dest(lefttri, midpoint); - apex(lefttri, rightpoint); - lefttest = counterclockwise(leftpoint, midpoint, rightpoint); - if (lefttest > 0.0) { - newevent = freeevents; - freeevents = (struct event *) freeevents->eventptr; - newevent->xkey = xminextreme; - newevent->ykey = circletop(leftpoint, midpoint, rightpoint, - lefttest); - newevent->eventptr = (VOID *) encode(lefttri); - eventheapinsert(eventheap, heapsize, newevent); - heapsize++; - setorg(lefttri, newevent); - } - apex(righttri, leftpoint); - org(righttri, midpoint); - apex(farrighttri, rightpoint); - righttest = counterclockwise(leftpoint, midpoint, rightpoint); - if (righttest > 0.0) { - newevent = freeevents; - freeevents = (struct event *) freeevents->eventptr; - newevent->xkey = xminextreme; - newevent->ykey = circletop(leftpoint, midpoint, rightpoint, - righttest); - newevent->eventptr = (VOID *) encode(farrighttri); - eventheapinsert(eventheap, heapsize, newevent); - heapsize++; - setorg(farrighttri, newevent); - } - } - } - - pooldeinit(&splaynodes); - lprevself(bottommost); - return removeghosts(&bottommost); + pooldeinit( &splaynodes ); + lprevself( bottommost ); + return removeghosts( &bottommost ); } #endif /* not REDUCED */ @@ -8633,35 +8716,38 @@ long sweeplinedelaunay() /* */ /*****************************************************************************/ -long delaunay() -{ - eextras = 0; - initializetrisegpools(); +long delaunay(){ + eextras = 0; + initializetrisegpools(); #ifdef REDUCED - if (!quiet) { - printf( - "Constructing Delaunay triangulation by divide-and-conquer method.\n"); - } - return divconqdelaunay(); + if ( !quiet ) { + printf( + "Constructing Delaunay triangulation by divide-and-conquer method.\n" ); + } + return divconqdelaunay(); #else /* not REDUCED */ - if (!quiet) { - printf("Constructing Delaunay triangulation "); - if (incremental) { - printf("by incremental method.\n"); - } else if (sweepline) { - printf("by sweepline method.\n"); - } else { - printf("by divide-and-conquer method.\n"); - } - } - if (incremental) { - return incrementaldelaunay(); - } else if (sweepline) { - return sweeplinedelaunay(); - } else { - return divconqdelaunay(); - } + if ( !quiet ) { + printf( "Constructing Delaunay triangulation " ); + if ( incremental ) { + printf( "by incremental method.\n" ); + } + else if ( sweepline ) { + printf( "by sweepline method.\n" ); + } + else { + printf( "by divide-and-conquer method.\n" ); + } + } + if ( incremental ) { + return incrementaldelaunay(); + } + else if ( sweepline ) { + return sweeplinedelaunay(); + } + else { + return divconqdelaunay(); + } #endif /* not REDUCED */ } @@ -8694,9 +8780,9 @@ long delaunay() #ifdef TRILIBRARY -int reconstruct(trianglelist, triangleattriblist, trianglearealist, elements, - corners, attribs, segmentlist, segmentmarkerlist, - numberofsegments) +int reconstruct( trianglelist, triangleattriblist, trianglearealist, elements, + corners, attribs, segmentlist, segmentmarkerlist, + numberofsegments ) int *trianglelist; REAL *triangleattriblist; REAL *trianglearealist; @@ -8709,7 +8795,7 @@ int numberofsegments; #else /* not TRILIBRARY */ -long reconstruct(elefilename, areafilename, polyfilename, polyfile) +long reconstruct( elefilename, areafilename, polyfilename, polyfile ) char *elefilename; char *areafilename; char *polyfilename; @@ -8719,433 +8805,442 @@ FILE *polyfile; { #ifdef TRILIBRARY - int pointindex; - int attribindex; + int pointindex; + int attribindex; #else /* not TRILIBRARY */ - FILE *elefile; - FILE *areafile; - char inputline[INPUTLINESIZE]; - char *stringptr; - int areaelements; + FILE *elefile; + FILE *areafile; + char inputline[INPUTLINESIZE]; + char *stringptr; + int areaelements; #endif /* not TRILIBRARY */ - struct triedge triangleloop; - struct triedge triangleleft; - struct triedge checktri; - struct triedge checkleft; - struct triedge checkneighbor; - struct edge shelleloop; - triangle *vertexarray; - triangle *prevlink; - triangle nexttri; - point tdest, tapex; - point checkdest, checkapex; - point shorg; - point killpoint; - REAL area; - int corner[3]; - int end[2]; - int killpointindex; - int incorners; - int segmentmarkers; - int boundmarker; - int aroundpoint; - long hullsize; - int notfound; - int elementnumber, segmentnumber; - int i, j; - triangle ptr; /* Temporary variable used by sym(). */ + struct triedge triangleloop; + struct triedge triangleleft; + struct triedge checktri; + struct triedge checkleft; + struct triedge checkneighbor; + struct edge shelleloop; + triangle *vertexarray; + triangle *prevlink; + triangle nexttri; + point tdest, tapex; + point checkdest, checkapex; + point shorg; + point killpoint; + REAL area; + int corner[3]; + int end[2]; + int killpointindex; + int incorners; + int segmentmarkers; + int boundmarker; + int aroundpoint; + long hullsize; + int notfound; + int elementnumber, segmentnumber; + int i, j; + triangle ptr; /* Temporary variable used by sym(). */ #ifdef TRILIBRARY - inelements = elements; - incorners = corners; - if (incorners < 3) { - printf("Error: Triangles must have at least 3 points.\n"); - exit(1); - } - eextras = attribs; + inelements = elements; + incorners = corners; + if ( incorners < 3 ) { + printf( "Error: Triangles must have at least 3 points.\n" ); + exit( 1 ); + } + eextras = attribs; #else /* not TRILIBRARY */ - /* Read the triangles from an .ele file. */ - if (!quiet) { - printf("Opening %s.\n", elefilename); - } - elefile = fopen(elefilename, "r"); - if (elefile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", elefilename); - exit(1); - } - /* Read number of triangles, number of points per triangle, and */ - /* number of triangle attributes from .ele file. */ - stringptr = readline(inputline, elefile, elefilename); - inelements = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - incorners = 3; - } else { - incorners = (int) strtol (stringptr, &stringptr, 0); - if (incorners < 3) { - printf("Error: Triangles in %s must have at least 3 points.\n", - elefilename); - exit(1); - } - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - eextras = 0; - } else { - eextras = (int) strtol (stringptr, &stringptr, 0); - } + /* Read the triangles from an .ele file. */ + if ( !quiet ) { + printf( "Opening %s.\n", elefilename ); + } + elefile = fopen( elefilename, "r" ); + if ( elefile == (FILE *) NULL ) { + printf( " Error: Cannot access file %s.\n", elefilename ); + exit( 1 ); + } + /* Read number of triangles, number of points per triangle, and */ + /* number of triangle attributes from .ele file. */ + stringptr = readline( inputline, elefile, elefilename ); + inelements = (int) strtol( stringptr, &stringptr, 0 ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + incorners = 3; + } + else { + incorners = (int) strtol( stringptr, &stringptr, 0 ); + if ( incorners < 3 ) { + printf( "Error: Triangles in %s must have at least 3 points.\n", + elefilename ); + exit( 1 ); + } + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + eextras = 0; + } + else { + eextras = (int) strtol( stringptr, &stringptr, 0 ); + } #endif /* not TRILIBRARY */ - initializetrisegpools(); + initializetrisegpools(); - /* Create the triangles. */ - for (elementnumber = 1; elementnumber <= inelements; elementnumber++) { - maketriangle(&triangleloop); - /* Mark the triangle as living. */ - triangleloop.tri[3] = (triangle) triangleloop.tri; - } + /* Create the triangles. */ + for ( elementnumber = 1; elementnumber <= inelements; elementnumber++ ) { + maketriangle( &triangleloop ); + /* Mark the triangle as living. */ + triangleloop.tri[3] = (triangle) triangleloop.tri; + } - if (poly) { + if ( poly ) { #ifdef TRILIBRARY - insegments = numberofsegments; - segmentmarkers = segmentmarkerlist != (int *) NULL; + insegments = numberofsegments; + segmentmarkers = segmentmarkerlist != (int *) NULL; #else /* not TRILIBRARY */ - /* Read number of segments and number of segment */ - /* boundary markers from .poly file. */ - stringptr = readline(inputline, polyfile, inpolyfilename); - insegments = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - segmentmarkers = 0; - } else { - segmentmarkers = (int) strtol (stringptr, &stringptr, 0); - } + /* Read number of segments and number of segment */ + /* boundary markers from .poly file. */ + stringptr = readline( inputline, polyfile, inpolyfilename ); + insegments = (int) strtol( stringptr, &stringptr, 0 ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + segmentmarkers = 0; + } + else { + segmentmarkers = (int) strtol( stringptr, &stringptr, 0 ); + } #endif /* not TRILIBRARY */ - /* Create the shell edges. */ - for (segmentnumber = 1; segmentnumber <= insegments; segmentnumber++) { - makeshelle(&shelleloop); - /* Mark the shell edge as living. */ - shelleloop.sh[2] = (shelle) shelleloop.sh; - } - } + /* Create the shell edges. */ + for ( segmentnumber = 1; segmentnumber <= insegments; segmentnumber++ ) { + makeshelle( &shelleloop ); + /* Mark the shell edge as living. */ + shelleloop.sh[2] = (shelle) shelleloop.sh; + } + } #ifdef TRILIBRARY - pointindex = 0; - attribindex = 0; + pointindex = 0; + attribindex = 0; #else /* not TRILIBRARY */ - if (vararea) { - /* Open an .area file, check for consistency with the .ele file. */ - if (!quiet) { - printf("Opening %s.\n", areafilename); - } - areafile = fopen(areafilename, "r"); - if (areafile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", areafilename); - exit(1); - } - stringptr = readline(inputline, areafile, areafilename); - areaelements = (int) strtol (stringptr, &stringptr, 0); - if (areaelements != inelements) { - printf("Error: %s and %s disagree on number of triangles.\n", - elefilename, areafilename); - exit(1); - } - } + if ( vararea ) { + /* Open an .area file, check for consistency with the .ele file. */ + if ( !quiet ) { + printf( "Opening %s.\n", areafilename ); + } + areafile = fopen( areafilename, "r" ); + if ( areafile == (FILE *) NULL ) { + printf( " Error: Cannot access file %s.\n", areafilename ); + exit( 1 ); + } + stringptr = readline( inputline, areafile, areafilename ); + areaelements = (int) strtol( stringptr, &stringptr, 0 ); + if ( areaelements != inelements ) { + printf( "Error: %s and %s disagree on number of triangles.\n", + elefilename, areafilename ); + exit( 1 ); + } + } #endif /* not TRILIBRARY */ - if (!quiet) { - printf("Reconstructing mesh.\n"); - } - /* Allocate a temporary array that maps each point to some adjacent */ - /* triangle. I took care to allocate all the permanent memory for */ - /* triangles and shell edges first. */ - vertexarray = (triangle *) malloc(points.items * sizeof(triangle)); - if (vertexarray == (triangle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Each point is initially unrepresented. */ - for (i = 0; i < points.items; i++) { - vertexarray[i] = (triangle) dummytri; - } - - if (verbose) { - printf(" Assembling triangles.\n"); - } - /* Read the triangles from the .ele file, and link */ - /* together those that share an edge. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { + if ( !quiet ) { + printf( "Reconstructing mesh.\n" ); + } + /* Allocate a temporary array that maps each point to some adjacent */ + /* triangle. I took care to allocate all the permanent memory for */ + /* triangles and shell edges first. */ + vertexarray = (triangle *) malloc( points.items * sizeof( triangle ) ); + if ( vertexarray == (triangle *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + /* Each point is initially unrepresented. */ + for ( i = 0; i < points.items; i++ ) { + vertexarray[i] = (triangle) dummytri; + } + + if ( verbose ) { + printf( " Assembling triangles.\n" ); + } + /* Read the triangles from the .ele file, and link */ + /* together those that share an edge. */ + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + elementnumber = firstnumber; + while ( triangleloop.tri != (triangle *) NULL ) { #ifdef TRILIBRARY - /* Copy the triangle's three corners. */ - for (j = 0; j < 3; j++) { - corner[j] = trianglelist[pointindex++]; - if ((corner[j] < firstnumber) || (corner[j] >= firstnumber + inpoints)) { - printf("Error: Triangle %d has an invalid vertex index.\n", - elementnumber); - exit(1); - } - } + /* Copy the triangle's three corners. */ + for ( j = 0; j < 3; j++ ) { + corner[j] = trianglelist[pointindex++]; + if ( ( corner[j] < firstnumber ) || ( corner[j] >= firstnumber + inpoints ) ) { + printf( "Error: Triangle %d has an invalid vertex index.\n", + elementnumber ); + exit( 1 ); + } + } #else /* not TRILIBRARY */ - /* Read triangle number and the triangle's three corners. */ - stringptr = readline(inputline, elefile, elefilename); - for (j = 0; j < 3; j++) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Triangle %d is missing point %d in %s.\n", - elementnumber, j + 1, elefilename); - exit(1); - } else { - corner[j] = (int) strtol (stringptr, &stringptr, 0); - if ((corner[j] < firstnumber) || - (corner[j] >= firstnumber + inpoints)) { - printf("Error: Triangle %d has an invalid vertex index.\n", - elementnumber); - exit(1); - } - } - } + /* Read triangle number and the triangle's three corners. */ + stringptr = readline( inputline, elefile, elefilename ); + for ( j = 0; j < 3; j++ ) { + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Triangle %d is missing point %d in %s.\n", + elementnumber, j + 1, elefilename ); + exit( 1 ); + } + else { + corner[j] = (int) strtol( stringptr, &stringptr, 0 ); + if ( ( corner[j] < firstnumber ) || + ( corner[j] >= firstnumber + inpoints ) ) { + printf( "Error: Triangle %d has an invalid vertex index.\n", + elementnumber ); + exit( 1 ); + } + } + } #endif /* not TRILIBRARY */ - /* Find out about (and throw away) extra nodes. */ - for (j = 3; j < incorners; j++) { + /* Find out about (and throw away) extra nodes. */ + for ( j = 3; j < incorners; j++ ) { #ifdef TRILIBRARY - killpointindex = trianglelist[pointindex++]; + killpointindex = trianglelist[pointindex++]; #else /* not TRILIBRARY */ - stringptr = findfield(stringptr); - if (*stringptr != '\0') { - killpointindex = (int) strtol (stringptr, &stringptr, 0); + stringptr = findfield( stringptr ); + if ( *stringptr != '\0' ) { + killpointindex = (int) strtol( stringptr, &stringptr, 0 ); #endif /* not TRILIBRARY */ - if ((killpointindex >= firstnumber) && - (killpointindex < firstnumber + inpoints)) { - /* Delete the non-corner point if it's not already deleted. */ - killpoint = getpoint(killpointindex); - if (pointmark(killpoint) != DEADPOINT) { - pointdealloc(killpoint); - } - } + if ( ( killpointindex >= firstnumber ) && + ( killpointindex < firstnumber + inpoints ) ) { + /* Delete the non-corner point if it's not already deleted. */ + killpoint = getpoint( killpointindex ); + if ( pointmark( killpoint ) != DEADPOINT ) { + pointdealloc( killpoint ); + } + } #ifndef TRILIBRARY - } + } #endif /* not TRILIBRARY */ - } + } - /* Read the triangle's attributes. */ - for (j = 0; j < eextras; j++) { + /* Read the triangle's attributes. */ + for ( j = 0; j < eextras; j++ ) { #ifdef TRILIBRARY - setelemattribute(triangleloop, j, triangleattriblist[attribindex++]); + setelemattribute( triangleloop, j, triangleattriblist[attribindex++] ); #else /* not TRILIBRARY */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - setelemattribute(triangleloop, j, 0); - } else { - setelemattribute(triangleloop, j, - (REAL) strtod (stringptr, &stringptr)); - } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + setelemattribute( triangleloop, j, 0 ); + } + else { + setelemattribute( triangleloop, j, + (REAL) strtod( stringptr, &stringptr ) ); + } #endif /* not TRILIBRARY */ - } + } - if (vararea) { + if ( vararea ) { #ifdef TRILIBRARY - area = trianglearealist[elementnumber - firstnumber]; + area = trianglearealist[elementnumber - firstnumber]; #else /* not TRILIBRARY */ - /* Read an area constraint from the .area file. */ - stringptr = readline(inputline, areafile, areafilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - area = -1.0; /* No constraint on this triangle. */ - } else { - area = (REAL) strtod(stringptr, &stringptr); - } + /* Read an area constraint from the .area file. */ + stringptr = readline( inputline, areafile, areafilename ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + area = -1.0; /* No constraint on this triangle. */ + } + else { + area = (REAL) strtod( stringptr, &stringptr ); + } #endif /* not TRILIBRARY */ - setareabound(triangleloop, area); - } - - /* Set the triangle's vertices. */ - triangleloop.orient = 0; - setorg(triangleloop, getpoint(corner[0])); - setdest(triangleloop, getpoint(corner[1])); - setapex(triangleloop, getpoint(corner[2])); - /* Try linking the triangle to others that share these vertices. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - /* Take the number for the origin of triangleloop. */ - aroundpoint = corner[triangleloop.orient]; - /* Look for other triangles having this vertex. */ - nexttri = vertexarray[aroundpoint - firstnumber]; - /* Link the current triangle to the next one in the stack. */ - triangleloop.tri[6 + triangleloop.orient] = nexttri; - /* Push the current triangle onto the stack. */ - vertexarray[aroundpoint - firstnumber] = encode(triangleloop); - decode(nexttri, checktri); - if (checktri.tri != dummytri) { - dest(triangleloop, tdest); - apex(triangleloop, tapex); - /* Look for other triangles that share an edge. */ - do { - dest(checktri, checkdest); - apex(checktri, checkapex); - if (tapex == checkdest) { - /* The two triangles share an edge; bond them together. */ - lprev(triangleloop, triangleleft); - bond(triangleleft, checktri); - } - if (tdest == checkapex) { - /* The two triangles share an edge; bond them together. */ - lprev(checktri, checkleft); - bond(triangleloop, checkleft); - } - /* Find the next triangle in the stack. */ - nexttri = checktri.tri[6 + checktri.orient]; - decode(nexttri, checktri); - } while (checktri.tri != dummytri); - } - } - triangleloop.tri = triangletraverse(); - elementnumber++; - } + setareabound( triangleloop, area ); + } + + /* Set the triangle's vertices. */ + triangleloop.orient = 0; + setorg( triangleloop, getpoint( corner[0] ) ); + setdest( triangleloop, getpoint( corner[1] ) ); + setapex( triangleloop, getpoint( corner[2] ) ); + /* Try linking the triangle to others that share these vertices. */ + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + /* Take the number for the origin of triangleloop. */ + aroundpoint = corner[triangleloop.orient]; + /* Look for other triangles having this vertex. */ + nexttri = vertexarray[aroundpoint - firstnumber]; + /* Link the current triangle to the next one in the stack. */ + triangleloop.tri[6 + triangleloop.orient] = nexttri; + /* Push the current triangle onto the stack. */ + vertexarray[aroundpoint - firstnumber] = encode( triangleloop ); + decode( nexttri, checktri ); + if ( checktri.tri != dummytri ) { + dest( triangleloop, tdest ); + apex( triangleloop, tapex ); + /* Look for other triangles that share an edge. */ + do { + dest( checktri, checkdest ); + apex( checktri, checkapex ); + if ( tapex == checkdest ) { + /* The two triangles share an edge; bond them together. */ + lprev( triangleloop, triangleleft ); + bond( triangleleft, checktri ); + } + if ( tdest == checkapex ) { + /* The two triangles share an edge; bond them together. */ + lprev( checktri, checkleft ); + bond( triangleloop, checkleft ); + } + /* Find the next triangle in the stack. */ + nexttri = checktri.tri[6 + checktri.orient]; + decode( nexttri, checktri ); + } while ( checktri.tri != dummytri ); + } + } + triangleloop.tri = triangletraverse(); + elementnumber++; + } #ifdef TRILIBRARY - pointindex = 0; + pointindex = 0; #else /* not TRILIBRARY */ - fclose(elefile); - if (vararea) { - fclose(areafile); - } + fclose( elefile ); + if ( vararea ) { + fclose( areafile ); + } #endif /* not TRILIBRARY */ - hullsize = 0; /* Prepare to count the boundary edges. */ - if (poly) { - if (verbose) { - printf(" Marking segments in triangulation.\n"); - } - /* Read the segments from the .poly file, and link them */ - /* to their neighboring triangles. */ - boundmarker = 0; - traversalinit(&shelles); - shelleloop.sh = shelletraverse(); - segmentnumber = firstnumber; - while (shelleloop.sh != (shelle *) NULL) { + hullsize = 0; /* Prepare to count the boundary edges. */ + if ( poly ) { + if ( verbose ) { + printf( " Marking segments in triangulation.\n" ); + } + /* Read the segments from the .poly file, and link them */ + /* to their neighboring triangles. */ + boundmarker = 0; + traversalinit( &shelles ); + shelleloop.sh = shelletraverse(); + segmentnumber = firstnumber; + while ( shelleloop.sh != (shelle *) NULL ) { #ifdef TRILIBRARY - end[0] = segmentlist[pointindex++]; - end[1] = segmentlist[pointindex++]; - if (segmentmarkers) { - boundmarker = segmentmarkerlist[segmentnumber - firstnumber]; - } + end[0] = segmentlist[pointindex++]; + end[1] = segmentlist[pointindex++]; + if ( segmentmarkers ) { + boundmarker = segmentmarkerlist[segmentnumber - firstnumber]; + } #else /* not TRILIBRARY */ - /* Read the endpoints of each segment, and possibly a boundary marker. */ - stringptr = readline(inputline, polyfile, inpolyfilename); - /* Skip the first (segment number) field. */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d has no endpoints in %s.\n", segmentnumber, - polyfilename); - exit(1); - } else { - end[0] = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d is missing its second endpoint in %s.\n", - segmentnumber, polyfilename); - exit(1); - } else { - end[1] = (int) strtol (stringptr, &stringptr, 0); - } - if (segmentmarkers) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - boundmarker = 0; - } else { - boundmarker = (int) strtol (stringptr, &stringptr, 0); - } - } + /* Read the endpoints of each segment, and possibly a boundary marker. */ + stringptr = readline( inputline, polyfile, inpolyfilename ); + /* Skip the first (segment number) field. */ + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Segment %d has no endpoints in %s.\n", segmentnumber, + polyfilename ); + exit( 1 ); + } + else { + end[0] = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Segment %d is missing its second endpoint in %s.\n", + segmentnumber, polyfilename ); + exit( 1 ); + } + else { + end[1] = (int) strtol( stringptr, &stringptr, 0 ); + } + if ( segmentmarkers ) { + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + boundmarker = 0; + } + else { + boundmarker = (int) strtol( stringptr, &stringptr, 0 ); + } + } #endif /* not TRILIBRARY */ - for (j = 0; j < 2; j++) { - if ((end[j] < firstnumber) || (end[j] >= firstnumber + inpoints)) { - printf("Error: Segment %d has an invalid vertex index.\n", - segmentnumber); - exit(1); - } - } - - /* set the shell edge's vertices. */ - shelleloop.shorient = 0; - setsorg(shelleloop, getpoint(end[0])); - setsdest(shelleloop, getpoint(end[1])); - setmark(shelleloop, boundmarker); - /* Try linking the shell edge to triangles that share these vertices. */ - for (shelleloop.shorient = 0; shelleloop.shorient < 2; - shelleloop.shorient++) { - /* Take the number for the destination of shelleloop. */ - aroundpoint = end[1 - shelleloop.shorient]; - /* Look for triangles having this vertex. */ - prevlink = &vertexarray[aroundpoint - firstnumber]; - nexttri = vertexarray[aroundpoint - firstnumber]; - decode(nexttri, checktri); - sorg(shelleloop, shorg); - notfound = 1; - /* Look for triangles having this edge. Note that I'm only */ - /* comparing each triangle's destination with the shell edge; */ - /* each triangle's apex is handled through a different vertex. */ - /* Because each triangle appears on three vertices' lists, each */ - /* occurrence of a triangle on a list can (and does) represent */ - /* an edge. In this way, most edges are represented twice, and */ - /* every triangle-segment bond is represented once. */ - while (notfound && (checktri.tri != dummytri)) { - dest(checktri, checkdest); - if (shorg == checkdest) { - /* We have a match. Remove this triangle from the list. */ - *prevlink = checktri.tri[6 + checktri.orient]; - /* Bond the shell edge to the triangle. */ - tsbond(checktri, shelleloop); - /* Check if this is a boundary edge. */ - sym(checktri, checkneighbor); - if (checkneighbor.tri == dummytri) { - /* The next line doesn't insert a shell edge (because there's */ - /* already one there), but it sets the boundary markers of */ - /* the existing shell edge and its vertices. */ - insertshelle(&checktri, 1); - hullsize++; - } - notfound = 0; - } - /* Find the next triangle in the stack. */ - prevlink = &checktri.tri[6 + checktri.orient]; - nexttri = checktri.tri[6 + checktri.orient]; - decode(nexttri, checktri); - } - } - shelleloop.sh = shelletraverse(); - segmentnumber++; - } - } - - /* Mark the remaining edges as not being attached to any shell edge. */ - /* Also, count the (yet uncounted) boundary edges. */ - for (i = 0; i < points.items; i++) { - /* Search the stack of triangles adjacent to a point. */ - nexttri = vertexarray[i]; - decode(nexttri, checktri); - while (checktri.tri != dummytri) { - /* Find the next triangle in the stack before this */ - /* information gets overwritten. */ - nexttri = checktri.tri[6 + checktri.orient]; - /* No adjacent shell edge. (This overwrites the stack info.) */ - tsdissolve(checktri); - sym(checktri, checkneighbor); - if (checkneighbor.tri == dummytri) { - insertshelle(&checktri, 1); - hullsize++; - } - decode(nexttri, checktri); - } - } - - free(vertexarray); - return hullsize; + for ( j = 0; j < 2; j++ ) { + if ( ( end[j] < firstnumber ) || ( end[j] >= firstnumber + inpoints ) ) { + printf( "Error: Segment %d has an invalid vertex index.\n", + segmentnumber ); + exit( 1 ); + } + } + + /* set the shell edge's vertices. */ + shelleloop.shorient = 0; + setsorg( shelleloop, getpoint( end[0] ) ); + setsdest( shelleloop, getpoint( end[1] ) ); + setmark( shelleloop, boundmarker ); + /* Try linking the shell edge to triangles that share these vertices. */ + for ( shelleloop.shorient = 0; shelleloop.shorient < 2; + shelleloop.shorient++ ) { + /* Take the number for the destination of shelleloop. */ + aroundpoint = end[1 - shelleloop.shorient]; + /* Look for triangles having this vertex. */ + prevlink = &vertexarray[aroundpoint - firstnumber]; + nexttri = vertexarray[aroundpoint - firstnumber]; + decode( nexttri, checktri ); + sorg( shelleloop, shorg ); + notfound = 1; + /* Look for triangles having this edge. Note that I'm only */ + /* comparing each triangle's destination with the shell edge; */ + /* each triangle's apex is handled through a different vertex. */ + /* Because each triangle appears on three vertices' lists, each */ + /* occurrence of a triangle on a list can (and does) represent */ + /* an edge. In this way, most edges are represented twice, and */ + /* every triangle-segment bond is represented once. */ + while ( notfound && ( checktri.tri != dummytri ) ) { + dest( checktri, checkdest ); + if ( shorg == checkdest ) { + /* We have a match. Remove this triangle from the list. */ + *prevlink = checktri.tri[6 + checktri.orient]; + /* Bond the shell edge to the triangle. */ + tsbond( checktri, shelleloop ); + /* Check if this is a boundary edge. */ + sym( checktri, checkneighbor ); + if ( checkneighbor.tri == dummytri ) { + /* The next line doesn't insert a shell edge (because there's */ + /* already one there), but it sets the boundary markers of */ + /* the existing shell edge and its vertices. */ + insertshelle( &checktri, 1 ); + hullsize++; + } + notfound = 0; + } + /* Find the next triangle in the stack. */ + prevlink = &checktri.tri[6 + checktri.orient]; + nexttri = checktri.tri[6 + checktri.orient]; + decode( nexttri, checktri ); + } + } + shelleloop.sh = shelletraverse(); + segmentnumber++; + } + } + + /* Mark the remaining edges as not being attached to any shell edge. */ + /* Also, count the (yet uncounted) boundary edges. */ + for ( i = 0; i < points.items; i++ ) { + /* Search the stack of triangles adjacent to a point. */ + nexttri = vertexarray[i]; + decode( nexttri, checktri ); + while ( checktri.tri != dummytri ) { + /* Find the next triangle in the stack before this */ + /* information gets overwritten. */ + nexttri = checktri.tri[6 + checktri.orient]; + /* No adjacent shell edge. (This overwrites the stack info.) */ + tsdissolve( checktri ); + sym( checktri, checkneighbor ); + if ( checkneighbor.tri == dummytri ) { + insertshelle( &checktri, 1 ); + hullsize++; + } + decode( nexttri, checktri ); + } + } + + free( vertexarray ); + return hullsize; } #endif /* not CDT_ONLY */ @@ -9175,74 +9270,77 @@ FILE *polyfile; /* */ /*****************************************************************************/ -enum finddirectionresult finddirection(searchtri, endpoint) +enum finddirectionresult finddirection( searchtri, endpoint ) struct triedge *searchtri; point endpoint; { - struct triedge checktri; - point startpoint; - point leftpoint, rightpoint; - REAL leftccw, rightccw; - int leftflag, rightflag; - triangle ptr; /* Temporary variable used by onext() and oprev(). */ - - org(*searchtri, startpoint); - dest(*searchtri, rightpoint); - apex(*searchtri, leftpoint); - /* Is `endpoint' to the left? */ - leftccw = counterclockwise(endpoint, startpoint, leftpoint); - leftflag = leftccw > 0.0; - /* Is `endpoint' to the right? */ - rightccw = counterclockwise(startpoint, endpoint, rightpoint); - rightflag = rightccw > 0.0; - if (leftflag && rightflag) { - /* `searchtri' faces directly away from `endpoint'. We could go */ - /* left or right. Ask whether it's a triangle or a boundary */ - /* on the left. */ - onext(*searchtri, checktri); - if (checktri.tri == dummytri) { - leftflag = 0; - } else { - rightflag = 0; - } - } - while (leftflag) { - /* Turn left until satisfied. */ - onextself(*searchtri); - if (searchtri->tri == dummytri) { - printf("Internal error in finddirection(): Unable to find a\n"); - printf(" triangle leading from (%.12g, %.12g) to", startpoint[0], - startpoint[1]); - printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]); - internalerror(); - } - apex(*searchtri, leftpoint); - rightccw = leftccw; - leftccw = counterclockwise(endpoint, startpoint, leftpoint); - leftflag = leftccw > 0.0; - } - while (rightflag) { - /* Turn right until satisfied. */ - oprevself(*searchtri); - if (searchtri->tri == dummytri) { - printf("Internal error in finddirection(): Unable to find a\n"); - printf(" triangle leading from (%.12g, %.12g) to", startpoint[0], - startpoint[1]); - printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]); - internalerror(); - } - dest(*searchtri, rightpoint); - leftccw = rightccw; - rightccw = counterclockwise(startpoint, endpoint, rightpoint); - rightflag = rightccw > 0.0; - } - if (leftccw == 0.0) { - return LEFTCOLLINEAR; - } else if (rightccw == 0.0) { - return RIGHTCOLLINEAR; - } else { - return WITHIN; - } + struct triedge checktri; + point startpoint; + point leftpoint, rightpoint; + REAL leftccw, rightccw; + int leftflag, rightflag; + triangle ptr; /* Temporary variable used by onext() and oprev(). */ + + org( *searchtri, startpoint ); + dest( *searchtri, rightpoint ); + apex( *searchtri, leftpoint ); + /* Is `endpoint' to the left? */ + leftccw = counterclockwise( endpoint, startpoint, leftpoint ); + leftflag = leftccw > 0.0; + /* Is `endpoint' to the right? */ + rightccw = counterclockwise( startpoint, endpoint, rightpoint ); + rightflag = rightccw > 0.0; + if ( leftflag && rightflag ) { + /* `searchtri' faces directly away from `endpoint'. We could go */ + /* left or right. Ask whether it's a triangle or a boundary */ + /* on the left. */ + onext( *searchtri, checktri ); + if ( checktri.tri == dummytri ) { + leftflag = 0; + } + else { + rightflag = 0; + } + } + while ( leftflag ) { + /* Turn left until satisfied. */ + onextself( *searchtri ); + if ( searchtri->tri == dummytri ) { + printf( "Internal error in finddirection(): Unable to find a\n" ); + printf( " triangle leading from (%.12g, %.12g) to", startpoint[0], + startpoint[1] ); + printf( " (%.12g, %.12g).\n", endpoint[0], endpoint[1] ); + internalerror(); + } + apex( *searchtri, leftpoint ); + rightccw = leftccw; + leftccw = counterclockwise( endpoint, startpoint, leftpoint ); + leftflag = leftccw > 0.0; + } + while ( rightflag ) { + /* Turn right until satisfied. */ + oprevself( *searchtri ); + if ( searchtri->tri == dummytri ) { + printf( "Internal error in finddirection(): Unable to find a\n" ); + printf( " triangle leading from (%.12g, %.12g) to", startpoint[0], + startpoint[1] ); + printf( " (%.12g, %.12g).\n", endpoint[0], endpoint[1] ); + internalerror(); + } + dest( *searchtri, rightpoint ); + leftccw = rightccw; + rightccw = counterclockwise( startpoint, endpoint, rightpoint ); + rightflag = rightccw > 0.0; + } + if ( leftccw == 0.0 ) { + return LEFTCOLLINEAR; + } + else if ( rightccw == 0.0 ) { + return RIGHTCOLLINEAR; + } + else { + return WITHIN; + } } /*****************************************************************************/ @@ -9262,78 +9360,79 @@ point endpoint; /* */ /*****************************************************************************/ -void segmentintersection(splittri, splitshelle, endpoint2) +void segmentintersection( splittri, splitshelle, endpoint2 ) struct triedge *splittri; struct edge *splitshelle; point endpoint2; { - point endpoint1; - point torg, tdest; - point leftpoint, rightpoint; - point newpoint; - enum insertsiteresult success; - enum finddirectionresult collinear; - REAL ex, ey; - REAL tx, ty; - REAL etx, ety; - REAL split, denom; - int i; - triangle ptr; /* Temporary variable used by onext(). */ - - /* Find the other three segment endpoints. */ - apex(*splittri, endpoint1); - org(*splittri, torg); - dest(*splittri, tdest); - /* Segment intersection formulae; see the Antonio reference. */ - tx = tdest[0] - torg[0]; - ty = tdest[1] - torg[1]; - ex = endpoint2[0] - endpoint1[0]; - ey = endpoint2[1] - endpoint1[1]; - etx = torg[0] - endpoint2[0]; - ety = torg[1] - endpoint2[1]; - denom = ty * ex - tx * ey; - if (denom == 0.0) { - printf("Internal error in segmentintersection():"); - printf(" Attempt to find intersection of parallel segments.\n"); - internalerror(); - } - split = (ey * etx - ex * ety) / denom; - /* Create the new point. */ - newpoint = (point) poolalloc(&points); - /* Interpolate its coordinate and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = torg[i] + split * (tdest[i] - torg[i]); - } - setpointmark(newpoint, mark(*splitshelle)); - if (verbose > 1) { - printf( - " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", - torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1]); - } - /* Insert the intersection point. This should always succeed. */ - success = insertsite(newpoint, splittri, splitshelle, 0, 0); - if (success != SUCCESSFULPOINT) { - printf("Internal error in segmentintersection():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - if (steinerleft > 0) { - steinerleft--; - } - /* Inserting the point may have caused edge flips. We wish to rediscover */ - /* the edge connecting endpoint1 to the new intersection point. */ - collinear = finddirection(splittri, endpoint1); - dest(*splittri, rightpoint); - apex(*splittri, leftpoint); - if ((leftpoint[0] == endpoint1[0]) && (leftpoint[1] == endpoint1[1])) { - onextself(*splittri); - } else if ((rightpoint[0] != endpoint1[0]) || - (rightpoint[1] != endpoint1[1])) { - printf("Internal error in segmentintersection():\n"); - printf(" Topological inconsistency after splitting a segment.\n"); - internalerror(); - } - /* `splittri' should have destination endpoint1. */ + point endpoint1; + point torg, tdest; + point leftpoint, rightpoint; + point newpoint; + enum insertsiteresult success; + enum finddirectionresult collinear; + REAL ex, ey; + REAL tx, ty; + REAL etx, ety; + REAL split, denom; + int i; + triangle ptr; /* Temporary variable used by onext(). */ + + /* Find the other three segment endpoints. */ + apex( *splittri, endpoint1 ); + org( *splittri, torg ); + dest( *splittri, tdest ); + /* Segment intersection formulae; see the Antonio reference. */ + tx = tdest[0] - torg[0]; + ty = tdest[1] - torg[1]; + ex = endpoint2[0] - endpoint1[0]; + ey = endpoint2[1] - endpoint1[1]; + etx = torg[0] - endpoint2[0]; + ety = torg[1] - endpoint2[1]; + denom = ty * ex - tx * ey; + if ( denom == 0.0 ) { + printf( "Internal error in segmentintersection():" ); + printf( " Attempt to find intersection of parallel segments.\n" ); + internalerror(); + } + split = ( ey * etx - ex * ety ) / denom; + /* Create the new point. */ + newpoint = (point) poolalloc( &points ); + /* Interpolate its coordinate and attributes. */ + for ( i = 0; i < 2 + nextras; i++ ) { + newpoint[i] = torg[i] + split * ( tdest[i] - torg[i] ); + } + setpointmark( newpoint, mark( *splitshelle ) ); + if ( verbose > 1 ) { + printf( + " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", + torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1] ); + } + /* Insert the intersection point. This should always succeed. */ + success = insertsite( newpoint, splittri, splitshelle, 0, 0 ); + if ( success != SUCCESSFULPOINT ) { + printf( "Internal error in segmentintersection():\n" ); + printf( " Failure to split a segment.\n" ); + internalerror(); + } + if ( steinerleft > 0 ) { + steinerleft--; + } + /* Inserting the point may have caused edge flips. We wish to rediscover */ + /* the edge connecting endpoint1 to the new intersection point. */ + collinear = finddirection( splittri, endpoint1 ); + dest( *splittri, rightpoint ); + apex( *splittri, leftpoint ); + if ( ( leftpoint[0] == endpoint1[0] ) && ( leftpoint[1] == endpoint1[1] ) ) { + onextself( *splittri ); + } + else if ( ( rightpoint[0] != endpoint1[0] ) || + ( rightpoint[1] != endpoint1[1] ) ) { + printf( "Internal error in segmentintersection():\n" ); + printf( " Topological inconsistency after splitting a segment.\n" ); + internalerror(); + } + /* `splittri' should have destination endpoint1. */ } /*****************************************************************************/ @@ -9362,60 +9461,64 @@ point endpoint2; /* */ /*****************************************************************************/ -int scoutsegment(searchtri, endpoint2, newmark) +int scoutsegment( searchtri, endpoint2, newmark ) struct triedge *searchtri; point endpoint2; int newmark; { - struct triedge crosstri; - struct edge crossedge; - point leftpoint, rightpoint; - point endpoint1; - enum finddirectionresult collinear; - shelle sptr; /* Temporary variable used by tspivot(). */ - - collinear = finddirection(searchtri, endpoint2); - dest(*searchtri, rightpoint); - apex(*searchtri, leftpoint); - if (((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) || - ((rightpoint[0] == endpoint2[0]) && (rightpoint[1] == endpoint2[1]))) { - /* The segment is already an edge in the mesh. */ - if ((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) { - lprevself(*searchtri); - } - /* Insert a shell edge, if there isn't already one there. */ - insertshelle(searchtri, newmark); - return 1; - } else if (collinear == LEFTCOLLINEAR) { - /* We've collided with a point between the segment's endpoints. */ - /* Make the collinear point be the triangle's origin. */ - lprevself(*searchtri); - insertshelle(searchtri, newmark); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } else if (collinear == RIGHTCOLLINEAR) { - /* We've collided with a point between the segment's endpoints. */ - insertshelle(searchtri, newmark); - /* Make the collinear point be the triangle's origin. */ - lnextself(*searchtri); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } else { - lnext(*searchtri, crosstri); - tspivot(crosstri, crossedge); - /* Check for a crossing segment. */ - if (crossedge.sh == dummysh) { - return 0; - } else { - org(*searchtri, endpoint1); - /* Insert a point at the intersection. */ - segmentintersection(&crosstri, &crossedge, endpoint2); - triedgecopy(crosstri, *searchtri); - insertshelle(searchtri, newmark); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } - } + struct triedge crosstri; + struct edge crossedge; + point leftpoint, rightpoint; + point endpoint1; + enum finddirectionresult collinear; + shelle sptr; /* Temporary variable used by tspivot(). */ + + collinear = finddirection( searchtri, endpoint2 ); + dest( *searchtri, rightpoint ); + apex( *searchtri, leftpoint ); + if ( ( ( leftpoint[0] == endpoint2[0] ) && ( leftpoint[1] == endpoint2[1] ) ) || + ( ( rightpoint[0] == endpoint2[0] ) && ( rightpoint[1] == endpoint2[1] ) ) ) { + /* The segment is already an edge in the mesh. */ + if ( ( leftpoint[0] == endpoint2[0] ) && ( leftpoint[1] == endpoint2[1] ) ) { + lprevself( *searchtri ); + } + /* Insert a shell edge, if there isn't already one there. */ + insertshelle( searchtri, newmark ); + return 1; + } + else if ( collinear == LEFTCOLLINEAR ) { + /* We've collided with a point between the segment's endpoints. */ + /* Make the collinear point be the triangle's origin. */ + lprevself( *searchtri ); + insertshelle( searchtri, newmark ); + /* Insert the remainder of the segment. */ + return scoutsegment( searchtri, endpoint2, newmark ); + } + else if ( collinear == RIGHTCOLLINEAR ) { + /* We've collided with a point between the segment's endpoints. */ + insertshelle( searchtri, newmark ); + /* Make the collinear point be the triangle's origin. */ + lnextself( *searchtri ); + /* Insert the remainder of the segment. */ + return scoutsegment( searchtri, endpoint2, newmark ); + } + else { + lnext( *searchtri, crosstri ); + tspivot( crosstri, crossedge ); + /* Check for a crossing segment. */ + if ( crossedge.sh == dummysh ) { + return 0; + } + else { + org( *searchtri, endpoint1 ); + /* Insert a point at the intersection. */ + segmentintersection( &crosstri, &crossedge, endpoint2 ); + triedgecopy( crosstri, *searchtri ); + insertshelle( searchtri, newmark ); + /* Insert the remainder of the segment. */ + return scoutsegment( searchtri, endpoint2, newmark ); + } + } } /*****************************************************************************/ @@ -9440,79 +9543,80 @@ int newmark; #ifndef REDUCED #ifndef CDT_ONLY -void conformingedge(endpoint1, endpoint2, newmark) +void conformingedge( endpoint1, endpoint2, newmark ) point endpoint1; point endpoint2; int newmark; { - struct triedge searchtri1, searchtri2; - struct edge brokenshelle; - point newpoint; - point midpoint1, midpoint2; - enum insertsiteresult success; - int result1, result2; - int i; - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose > 2) { - printf("Forcing segment into triangulation by recursive splitting:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1], - endpoint2[0], endpoint2[1]); - } - /* Create a new point to insert in the middle of the segment. */ - newpoint = (point) poolalloc(&points); - /* Interpolate coordinates and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = 0.5 * (endpoint1[i] + endpoint2[i]); - } - setpointmark(newpoint, newmark); - /* Find a boundary triangle to search from. */ - searchtri1.tri = (triangle *) NULL; - /* Attempt to insert the new point. */ - success = insertsite(newpoint, &searchtri1, (struct edge *) NULL, 0, 0); - if (success == DUPLICATEPOINT) { - if (verbose > 2) { - printf(" Segment intersects existing point (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - } - /* Use the point that's already there. */ - pointdealloc(newpoint); - org(searchtri1, newpoint); - } else { - if (success == VIOLATINGPOINT) { - if (verbose > 2) { - printf(" Two segments intersect at (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - } - /* By fluke, we've landed right on another segment. Split it. */ - tspivot(searchtri1, brokenshelle); - success = insertsite(newpoint, &searchtri1, &brokenshelle, 0, 0); - if (success != SUCCESSFULPOINT) { - printf("Internal error in conformingedge():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - } - /* The point has been inserted successfully. */ - if (steinerleft > 0) { - steinerleft--; - } - } - triedgecopy(searchtri1, searchtri2); - result1 = scoutsegment(&searchtri1, endpoint1, newmark); - result2 = scoutsegment(&searchtri2, endpoint2, newmark); - if (!result1) { - /* The origin of searchtri1 may have changed if a collision with an */ - /* intervening vertex on the segment occurred. */ - org(searchtri1, midpoint1); - conformingedge(midpoint1, endpoint1, newmark); - } - if (!result2) { - /* The origin of searchtri2 may have changed if a collision with an */ - /* intervening vertex on the segment occurred. */ - org(searchtri2, midpoint2); - conformingedge(midpoint2, endpoint2, newmark); - } + struct triedge searchtri1, searchtri2; + struct edge brokenshelle; + point newpoint; + point midpoint1, midpoint2; + enum insertsiteresult success; + int result1, result2; + int i; + shelle sptr; /* Temporary variable used by tspivot(). */ + + if ( verbose > 2 ) { + printf( "Forcing segment into triangulation by recursive splitting:\n" ); + printf( " (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1], + endpoint2[0], endpoint2[1] ); + } + /* Create a new point to insert in the middle of the segment. */ + newpoint = (point) poolalloc( &points ); + /* Interpolate coordinates and attributes. */ + for ( i = 0; i < 2 + nextras; i++ ) { + newpoint[i] = 0.5 * ( endpoint1[i] + endpoint2[i] ); + } + setpointmark( newpoint, newmark ); + /* Find a boundary triangle to search from. */ + searchtri1.tri = (triangle *) NULL; + /* Attempt to insert the new point. */ + success = insertsite( newpoint, &searchtri1, (struct edge *) NULL, 0, 0 ); + if ( success == DUPLICATEPOINT ) { + if ( verbose > 2 ) { + printf( " Segment intersects existing point (%.12g, %.12g).\n", + newpoint[0], newpoint[1] ); + } + /* Use the point that's already there. */ + pointdealloc( newpoint ); + org( searchtri1, newpoint ); + } + else { + if ( success == VIOLATINGPOINT ) { + if ( verbose > 2 ) { + printf( " Two segments intersect at (%.12g, %.12g).\n", + newpoint[0], newpoint[1] ); + } + /* By fluke, we've landed right on another segment. Split it. */ + tspivot( searchtri1, brokenshelle ); + success = insertsite( newpoint, &searchtri1, &brokenshelle, 0, 0 ); + if ( success != SUCCESSFULPOINT ) { + printf( "Internal error in conformingedge():\n" ); + printf( " Failure to split a segment.\n" ); + internalerror(); + } + } + /* The point has been inserted successfully. */ + if ( steinerleft > 0 ) { + steinerleft--; + } + } + triedgecopy( searchtri1, searchtri2 ); + result1 = scoutsegment( &searchtri1, endpoint1, newmark ); + result2 = scoutsegment( &searchtri2, endpoint2, newmark ); + if ( !result1 ) { + /* The origin of searchtri1 may have changed if a collision with an */ + /* intervening vertex on the segment occurred. */ + org( searchtri1, midpoint1 ); + conformingedge( midpoint1, endpoint1, newmark ); + } + if ( !result2 ) { + /* The origin of searchtri2 may have changed if a collision with an */ + /* intervening vertex on the segment occurred. */ + org( searchtri2, midpoint2 ); + conformingedge( midpoint2, endpoint2, newmark ); + } } #endif /* not CDT_ONLY */ @@ -9556,61 +9660,62 @@ int newmark; /* */ /*****************************************************************************/ -void delaunayfixup(fixuptri, leftside) +void delaunayfixup( fixuptri, leftside ) struct triedge *fixuptri; int leftside; { - struct triedge neartri; - struct triedge fartri; - struct edge faredge; - point nearpoint, leftpoint, rightpoint, farpoint; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - lnext(*fixuptri, neartri); - sym(neartri, fartri); - /* Check if the edge opposite the origin of fixuptri can be flipped. */ - if (fartri.tri == dummytri) { - return; - } - tspivot(neartri, faredge); - if (faredge.sh != dummysh) { - return; - } - /* Find all the relevant vertices. */ - apex(neartri, nearpoint); - org(neartri, leftpoint); - dest(neartri, rightpoint); - apex(fartri, farpoint); - /* Check whether the previous polygon vertex is a reflex vertex. */ - if (leftside) { - if (counterclockwise(nearpoint, leftpoint, farpoint) <= 0.0) { - /* leftpoint is a reflex vertex too. Nothing can */ - /* be done until a convex section is found. */ - return; - } - } else { - if (counterclockwise(farpoint, rightpoint, nearpoint) <= 0.0) { - /* rightpoint is a reflex vertex too. Nothing can */ - /* be done until a convex section is found. */ - return; - } - } - if (counterclockwise(rightpoint, leftpoint, farpoint) > 0.0) { - /* fartri is not an inverted triangle, and farpoint is not a reflex */ - /* vertex. As there are no reflex vertices, fixuptri isn't an */ - /* inverted triangle, either. Hence, test the edge between the */ - /* triangles to ensure it is locally Delaunay. */ - if (incircle(leftpoint, farpoint, rightpoint, nearpoint) <= 0.0) { - return; - } - /* Not locally Delaunay; go on to an edge flip. */ - } /* else fartri is inverted; remove it from the stack by flipping. */ - flip(&neartri); - lprevself(*fixuptri); /* Restore the origin of fixuptri after the flip. */ - /* Recursively process the two triangles that result from the flip. */ - delaunayfixup(fixuptri, leftside); - delaunayfixup(&fartri, leftside); + struct triedge neartri; + struct triedge fartri; + struct edge faredge; + point nearpoint, leftpoint, rightpoint, farpoint; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + lnext( *fixuptri, neartri ); + sym( neartri, fartri ); + /* Check if the edge opposite the origin of fixuptri can be flipped. */ + if ( fartri.tri == dummytri ) { + return; + } + tspivot( neartri, faredge ); + if ( faredge.sh != dummysh ) { + return; + } + /* Find all the relevant vertices. */ + apex( neartri, nearpoint ); + org( neartri, leftpoint ); + dest( neartri, rightpoint ); + apex( fartri, farpoint ); + /* Check whether the previous polygon vertex is a reflex vertex. */ + if ( leftside ) { + if ( counterclockwise( nearpoint, leftpoint, farpoint ) <= 0.0 ) { + /* leftpoint is a reflex vertex too. Nothing can */ + /* be done until a convex section is found. */ + return; + } + } + else { + if ( counterclockwise( farpoint, rightpoint, nearpoint ) <= 0.0 ) { + /* rightpoint is a reflex vertex too. Nothing can */ + /* be done until a convex section is found. */ + return; + } + } + if ( counterclockwise( rightpoint, leftpoint, farpoint ) > 0.0 ) { + /* fartri is not an inverted triangle, and farpoint is not a reflex */ + /* vertex. As there are no reflex vertices, fixuptri isn't an */ + /* inverted triangle, either. Hence, test the edge between the */ + /* triangles to ensure it is locally Delaunay. */ + if ( incircle( leftpoint, farpoint, rightpoint, nearpoint ) <= 0.0 ) { + return; + } + /* Not locally Delaunay; go on to an edge flip. */ + } /* else fartri is inverted; remove it from the stack by flipping. */ + flip( &neartri ); + lprevself( *fixuptri ); /* Restore the origin of fixuptri after the flip. */ + /* Recursively process the two triangles that result from the flip. */ + delaunayfixup( fixuptri, leftside ); + delaunayfixup( &fartri, leftside ); } /*****************************************************************************/ @@ -9667,92 +9772,96 @@ int leftside; /* */ /*****************************************************************************/ -void constrainededge(starttri, endpoint2, newmark) +void constrainededge( starttri, endpoint2, newmark ) struct triedge *starttri; point endpoint2; int newmark; { - struct triedge fixuptri, fixuptri2; - struct edge fixupedge; - point endpoint1; - point farpoint; - REAL area; - int collision; - int done; - triangle ptr; /* Temporary variable used by sym() and oprev(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*starttri, endpoint1); - lnext(*starttri, fixuptri); - flip(&fixuptri); - /* `collision' indicates whether we have found a point directly */ - /* between endpoint1 and endpoint2. */ - collision = 0; - done = 0; - do { - org(fixuptri, farpoint); - /* `farpoint' is the extreme point of the polygon we are "digging" */ - /* to get from endpoint1 to endpoint2. */ - if ((farpoint[0] == endpoint2[0]) && (farpoint[1] == endpoint2[1])) { - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around endpoint2. */ - delaunayfixup(&fixuptri, 0); - delaunayfixup(&fixuptri2, 1); - done = 1; - } else { - /* Check whether farpoint is to the left or right of the segment */ - /* being inserted, to decide which edge of fixuptri to dig */ - /* through next. */ - area = counterclockwise(endpoint1, endpoint2, farpoint); - if (area == 0.0) { - /* We've collided with a point between endpoint1 and endpoint2. */ - collision = 1; - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around farpoint. */ - delaunayfixup(&fixuptri, 0); - delaunayfixup(&fixuptri2, 1); - done = 1; - } else { - if (area > 0.0) { /* farpoint is to the left of the segment. */ - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around farpoint, on the */ - /* left side of the segment only. */ - delaunayfixup(&fixuptri2, 1); - /* Flip the edge that crosses the segment. After the edge is */ - /* flipped, one of its endpoints is the fan vertex, and the */ - /* destination of fixuptri is the fan vertex. */ - lprevself(fixuptri); - } else { /* farpoint is to the right of the segment. */ - delaunayfixup(&fixuptri, 0); - /* Flip the edge that crosses the segment. After the edge is */ - /* flipped, one of its endpoints is the fan vertex, and the */ - /* destination of fixuptri is the fan vertex. */ - oprevself(fixuptri); - } - /* Check for two intersecting segments. */ - tspivot(fixuptri, fixupedge); - if (fixupedge.sh == dummysh) { - flip(&fixuptri); /* May create an inverted triangle on the left. */ - } else { - /* We've collided with a segment between endpoint1 and endpoint2. */ - collision = 1; - /* Insert a point at the intersection. */ - segmentintersection(&fixuptri, &fixupedge, endpoint2); - done = 1; - } - } - } - } while (!done); - /* Insert a shell edge to make the segment permanent. */ - insertshelle(&fixuptri, newmark); - /* If there was a collision with an interceding vertex, install another */ - /* segment connecting that vertex with endpoint2. */ - if (collision) { - /* Insert the remainder of the segment. */ - if (!scoutsegment(&fixuptri, endpoint2, newmark)) { - constrainededge(&fixuptri, endpoint2, newmark); - } - } + struct triedge fixuptri, fixuptri2; + struct edge fixupedge; + point endpoint1; + point farpoint; + REAL area; + int collision; + int done; + triangle ptr; /* Temporary variable used by sym() and oprev(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + org( *starttri, endpoint1 ); + lnext( *starttri, fixuptri ); + flip( &fixuptri ); + /* `collision' indicates whether we have found a point directly */ + /* between endpoint1 and endpoint2. */ + collision = 0; + done = 0; + do { + org( fixuptri, farpoint ); + /* `farpoint' is the extreme point of the polygon we are "digging" */ + /* to get from endpoint1 to endpoint2. */ + if ( ( farpoint[0] == endpoint2[0] ) && ( farpoint[1] == endpoint2[1] ) ) { + oprev( fixuptri, fixuptri2 ); + /* Enforce the Delaunay condition around endpoint2. */ + delaunayfixup( &fixuptri, 0 ); + delaunayfixup( &fixuptri2, 1 ); + done = 1; + } + else { + /* Check whether farpoint is to the left or right of the segment */ + /* being inserted, to decide which edge of fixuptri to dig */ + /* through next. */ + area = counterclockwise( endpoint1, endpoint2, farpoint ); + if ( area == 0.0 ) { + /* We've collided with a point between endpoint1 and endpoint2. */ + collision = 1; + oprev( fixuptri, fixuptri2 ); + /* Enforce the Delaunay condition around farpoint. */ + delaunayfixup( &fixuptri, 0 ); + delaunayfixup( &fixuptri2, 1 ); + done = 1; + } + else { + if ( area > 0.0 ) { /* farpoint is to the left of the segment. */ + oprev( fixuptri, fixuptri2 ); + /* Enforce the Delaunay condition around farpoint, on the */ + /* left side of the segment only. */ + delaunayfixup( &fixuptri2, 1 ); + /* Flip the edge that crosses the segment. After the edge is */ + /* flipped, one of its endpoints is the fan vertex, and the */ + /* destination of fixuptri is the fan vertex. */ + lprevself( fixuptri ); + } + else { /* farpoint is to the right of the segment. */ + delaunayfixup( &fixuptri, 0 ); + /* Flip the edge that crosses the segment. After the edge is */ + /* flipped, one of its endpoints is the fan vertex, and the */ + /* destination of fixuptri is the fan vertex. */ + oprevself( fixuptri ); + } + /* Check for two intersecting segments. */ + tspivot( fixuptri, fixupedge ); + if ( fixupedge.sh == dummysh ) { + flip( &fixuptri ); /* May create an inverted triangle on the left. */ + } + else { + /* We've collided with a segment between endpoint1 and endpoint2. */ + collision = 1; + /* Insert a point at the intersection. */ + segmentintersection( &fixuptri, &fixupedge, endpoint2 ); + done = 1; + } + } + } + } while ( !done ); + /* Insert a shell edge to make the segment permanent. */ + insertshelle( &fixuptri, newmark ); + /* If there was a collision with an interceding vertex, install another */ + /* segment connecting that vertex with endpoint2. */ + if ( collision ) { + /* Insert the remainder of the segment. */ + if ( !scoutsegment( &fixuptri, endpoint2, newmark ) ) { + constrainededge( &fixuptri, endpoint2, newmark ); + } + } } /*****************************************************************************/ @@ -9761,100 +9870,101 @@ int newmark; /* */ /*****************************************************************************/ -void insertsegment(endpoint1, endpoint2, newmark) +void insertsegment( endpoint1, endpoint2, newmark ) point endpoint1; point endpoint2; int newmark; { - struct triedge searchtri1, searchtri2; - triangle encodedtri; - point checkpoint; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 1) { - printf(" Connecting (%.12g, %.12g) to (%.12g, %.12g).\n", - endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]); - } - - /* Find a triangle whose origin is the segment's first endpoint. */ - checkpoint = (point) NULL; - encodedtri = point2tri(endpoint1); - if (encodedtri != (triangle) NULL) { - decode(encodedtri, searchtri1); - org(searchtri1, checkpoint); - } - if (checkpoint != endpoint1) { - /* Find a boundary triangle to search from. */ - searchtri1.tri = dummytri; - searchtri1.orient = 0; - symself(searchtri1); - /* Search for the segment's first endpoint by point location. */ - if (locate(endpoint1, &searchtri1) != ONVERTEX) { - printf( - "Internal error in insertsegment(): Unable to locate PSLG point\n"); - printf(" (%.12g, %.12g) in triangulation.\n", - endpoint1[0], endpoint1[1]); - internalerror(); - } - } - /* Remember this triangle to improve subsequent point location. */ - triedgecopy(searchtri1, recenttri); - /* Scout the beginnings of a path from the first endpoint */ - /* toward the second. */ - if (scoutsegment(&searchtri1, endpoint2, newmark)) { - /* The segment was easily inserted. */ - return; - } - /* The first endpoint may have changed if a collision with an intervening */ - /* vertex on the segment occurred. */ - org(searchtri1, endpoint1); - - /* Find a triangle whose origin is the segment's second endpoint. */ - checkpoint = (point) NULL; - encodedtri = point2tri(endpoint2); - if (encodedtri != (triangle) NULL) { - decode(encodedtri, searchtri2); - org(searchtri2, checkpoint); - } - if (checkpoint != endpoint2) { - /* Find a boundary triangle to search from. */ - searchtri2.tri = dummytri; - searchtri2.orient = 0; - symself(searchtri2); - /* Search for the segment's second endpoint by point location. */ - if (locate(endpoint2, &searchtri2) != ONVERTEX) { - printf( - "Internal error in insertsegment(): Unable to locate PSLG point\n"); - printf(" (%.12g, %.12g) in triangulation.\n", - endpoint2[0], endpoint2[1]); - internalerror(); - } - } - /* Remember this triangle to improve subsequent point location. */ - triedgecopy(searchtri2, recenttri); - /* Scout the beginnings of a path from the second endpoint */ - /* toward the first. */ - if (scoutsegment(&searchtri2, endpoint1, newmark)) { - /* The segment was easily inserted. */ - return; - } - /* The second endpoint may have changed if a collision with an intervening */ - /* vertex on the segment occurred. */ - org(searchtri2, endpoint2); + struct triedge searchtri1, searchtri2; + triangle encodedtri; + point checkpoint; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( verbose > 1 ) { + printf( " Connecting (%.12g, %.12g) to (%.12g, %.12g).\n", + endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1] ); + } + + /* Find a triangle whose origin is the segment's first endpoint. */ + checkpoint = (point) NULL; + encodedtri = point2tri( endpoint1 ); + if ( encodedtri != (triangle) NULL ) { + decode( encodedtri, searchtri1 ); + org( searchtri1, checkpoint ); + } + if ( checkpoint != endpoint1 ) { + /* Find a boundary triangle to search from. */ + searchtri1.tri = dummytri; + searchtri1.orient = 0; + symself( searchtri1 ); + /* Search for the segment's first endpoint by point location. */ + if ( locate( endpoint1, &searchtri1 ) != ONVERTEX ) { + printf( + "Internal error in insertsegment(): Unable to locate PSLG point\n" ); + printf( " (%.12g, %.12g) in triangulation.\n", + endpoint1[0], endpoint1[1] ); + internalerror(); + } + } + /* Remember this triangle to improve subsequent point location. */ + triedgecopy( searchtri1, recenttri ); + /* Scout the beginnings of a path from the first endpoint */ + /* toward the second. */ + if ( scoutsegment( &searchtri1, endpoint2, newmark ) ) { + /* The segment was easily inserted. */ + return; + } + /* The first endpoint may have changed if a collision with an intervening */ + /* vertex on the segment occurred. */ + org( searchtri1, endpoint1 ); + + /* Find a triangle whose origin is the segment's second endpoint. */ + checkpoint = (point) NULL; + encodedtri = point2tri( endpoint2 ); + if ( encodedtri != (triangle) NULL ) { + decode( encodedtri, searchtri2 ); + org( searchtri2, checkpoint ); + } + if ( checkpoint != endpoint2 ) { + /* Find a boundary triangle to search from. */ + searchtri2.tri = dummytri; + searchtri2.orient = 0; + symself( searchtri2 ); + /* Search for the segment's second endpoint by point location. */ + if ( locate( endpoint2, &searchtri2 ) != ONVERTEX ) { + printf( + "Internal error in insertsegment(): Unable to locate PSLG point\n" ); + printf( " (%.12g, %.12g) in triangulation.\n", + endpoint2[0], endpoint2[1] ); + internalerror(); + } + } + /* Remember this triangle to improve subsequent point location. */ + triedgecopy( searchtri2, recenttri ); + /* Scout the beginnings of a path from the second endpoint */ + /* toward the first. */ + if ( scoutsegment( &searchtri2, endpoint1, newmark ) ) { + /* The segment was easily inserted. */ + return; + } + /* The second endpoint may have changed if a collision with an intervening */ + /* vertex on the segment occurred. */ + org( searchtri2, endpoint2 ); #ifndef REDUCED #ifndef CDT_ONLY - if (splitseg) { - /* Insert vertices to force the segment into the triangulation. */ - conformingedge(endpoint1, endpoint2, newmark); - } else { + if ( splitseg ) { + /* Insert vertices to force the segment into the triangulation. */ + conformingedge( endpoint1, endpoint2, newmark ); + } + else { #endif /* not CDT_ONLY */ #endif /* not REDUCED */ - /* Insert the segment directly into the triangulation. */ - constrainededge(&searchtri1, endpoint2, newmark); + /* Insert the segment directly into the triangulation. */ + constrainededge( &searchtri1, endpoint2, newmark ); #ifndef REDUCED #ifndef CDT_ONLY - } +} #endif /* not CDT_ONLY */ #endif /* not REDUCED */ } @@ -9865,31 +9975,30 @@ int newmark; /* */ /*****************************************************************************/ -void markhull() -{ - struct triedge hulltri; - struct triedge nexttri; - struct triedge starttri; - triangle ptr; /* Temporary variable used by sym() and oprev(). */ - - /* Find a triangle handle on the hull. */ - hulltri.tri = dummytri; - hulltri.orient = 0; - symself(hulltri); - /* Remember where we started so we know when to stop. */ - triedgecopy(hulltri, starttri); - /* Go once counterclockwise around the convex hull. */ - do { - /* Create a shell edge if there isn't already one here. */ - insertshelle(&hulltri, 1); - /* To find the next hull edge, go clockwise around the next vertex. */ - lnextself(hulltri); - oprev(hulltri, nexttri); - while (nexttri.tri != dummytri) { - triedgecopy(nexttri, hulltri); - oprev(hulltri, nexttri); - } - } while (!triedgeequal(hulltri, starttri)); +void markhull(){ + struct triedge hulltri; + struct triedge nexttri; + struct triedge starttri; + triangle ptr; /* Temporary variable used by sym() and oprev(). */ + + /* Find a triangle handle on the hull. */ + hulltri.tri = dummytri; + hulltri.orient = 0; + symself( hulltri ); + /* Remember where we started so we know when to stop. */ + triedgecopy( hulltri, starttri ); + /* Go once counterclockwise around the convex hull. */ + do { + /* Create a shell edge if there isn't already one here. */ + insertshelle( &hulltri, 1 ); + /* To find the next hull edge, go clockwise around the next vertex. */ + lnextself( hulltri ); + oprev( hulltri, nexttri ); + while ( nexttri.tri != dummytri ) { + triedgecopy( nexttri, hulltri ); + oprev( hulltri, nexttri ); + } + } while ( !triedgeequal( hulltri, starttri ) ); } /*****************************************************************************/ @@ -9904,134 +10013,142 @@ void markhull() #ifdef TRILIBRARY -int formskeleton(segmentlist, segmentmarkerlist, numberofsegments) +int formskeleton( segmentlist, segmentmarkerlist, numberofsegments ) int *segmentlist; int *segmentmarkerlist; int numberofsegments; #else /* not TRILIBRARY */ -int formskeleton(polyfile, polyfilename) -FILE *polyfile; +int formskeleton( polyfile, polyfilename ) +FILE * polyfile; char *polyfilename; #endif /* not TRILIBRARY */ { #ifdef TRILIBRARY - char polyfilename[6]; - int index; + char polyfilename[6]; + int index; #else /* not TRILIBRARY */ - char inputline[INPUTLINESIZE]; - char *stringptr; + char inputline[INPUTLINESIZE]; + char *stringptr; #endif /* not TRILIBRARY */ - point endpoint1, endpoint2; - int segments; - int segmentmarkers; - int end1, end2; - int boundmarker; - int i; - - if (poly) { - if (!quiet) { - printf("Inserting segments into Delaunay triangulation.\n"); - } + point endpoint1, endpoint2; + int segments; + int segmentmarkers; + int end1, end2; + int boundmarker; + int i; + + if ( poly ) { + if ( !quiet ) { + printf( "Inserting segments into Delaunay triangulation.\n" ); + } #ifdef TRILIBRARY - strcpy(polyfilename, "input"); - segments = numberofsegments; - segmentmarkers = segmentmarkerlist != (int *) NULL; - index = 0; + strcpy( polyfilename, "input" ); + segments = numberofsegments; + segmentmarkers = segmentmarkerlist != (int *) NULL; + index = 0; #else /* not TRILIBRARY */ - /* Read the segments from a .poly file. */ - /* Read number of segments and number of boundary markers. */ - stringptr = readline(inputline, polyfile, polyfilename); - segments = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - segmentmarkers = 0; - } else { - segmentmarkers = (int) strtol (stringptr, &stringptr, 0); - } + /* Read the segments from a .poly file. */ + /* Read number of segments and number of boundary markers. */ + stringptr = readline( inputline, polyfile, polyfilename ); + segments = (int) strtol( stringptr, &stringptr, 0 ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + segmentmarkers = 0; + } + else { + segmentmarkers = (int) strtol( stringptr, &stringptr, 0 ); + } #endif /* not TRILIBRARY */ - /* If segments are to be inserted, compute a mapping */ - /* from points to triangles. */ - if (segments > 0) { - if (verbose) { - printf(" Inserting PSLG segments.\n"); - } - makepointmap(); - } - - boundmarker = 0; - /* Read and insert the segments. */ - for (i = 1; i <= segments; i++) { + /* If segments are to be inserted, compute a mapping */ + /* from points to triangles. */ + if ( segments > 0 ) { + if ( verbose ) { + printf( " Inserting PSLG segments.\n" ); + } + makepointmap(); + } + + boundmarker = 0; + /* Read and insert the segments. */ + for ( i = 1; i <= segments; i++ ) { #ifdef TRILIBRARY - end1 = segmentlist[index++]; - end2 = segmentlist[index++]; - if (segmentmarkers) { - boundmarker = segmentmarkerlist[i - 1]; - } + end1 = segmentlist[index++]; + end2 = segmentlist[index++]; + if ( segmentmarkers ) { + boundmarker = segmentmarkerlist[i - 1]; + } #else /* not TRILIBRARY */ - stringptr = readline(inputline, polyfile, inpolyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d has no endpoints in %s.\n", i, - polyfilename); - exit(1); - } else { - end1 = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d is missing its second endpoint in %s.\n", i, - polyfilename); - exit(1); - } else { - end2 = (int) strtol (stringptr, &stringptr, 0); - } - if (segmentmarkers) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - boundmarker = 0; - } else { - boundmarker = (int) strtol (stringptr, &stringptr, 0); - } - } + stringptr = readline( inputline, polyfile, inpolyfilename ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Segment %d has no endpoints in %s.\n", i, + polyfilename ); + exit( 1 ); + } + else { + end1 = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Segment %d is missing its second endpoint in %s.\n", i, + polyfilename ); + exit( 1 ); + } + else { + end2 = (int) strtol( stringptr, &stringptr, 0 ); + } + if ( segmentmarkers ) { + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + boundmarker = 0; + } + else { + boundmarker = (int) strtol( stringptr, &stringptr, 0 ); + } + } #endif /* not TRILIBRARY */ - if ((end1 < firstnumber) || (end1 >= firstnumber + inpoints)) { - if (!quiet) { - printf("Warning: Invalid first endpoint of segment %d in %s.\n", i, - polyfilename); - } - } else if ((end2 < firstnumber) || (end2 >= firstnumber + inpoints)) { - if (!quiet) { - printf("Warning: Invalid second endpoint of segment %d in %s.\n", i, - polyfilename); - } - } else { - endpoint1 = getpoint(end1); - endpoint2 = getpoint(end2); - if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) { - if (!quiet) { - printf("Warning: Endpoints of segment %d are coincident in %s.\n", - i, polyfilename); - } - } else { - insertsegment(endpoint1, endpoint2, boundmarker); - } - } - } - } else { - segments = 0; - } - if (convex || !poly) { - /* Enclose the convex hull with shell edges. */ - if (verbose) { - printf(" Enclosing convex hull with segments.\n"); - } - markhull(); - } - return segments; + if ( ( end1 < firstnumber ) || ( end1 >= firstnumber + inpoints ) ) { + if ( !quiet ) { + printf( "Warning: Invalid first endpoint of segment %d in %s.\n", i, + polyfilename ); + } + } + else if ( ( end2 < firstnumber ) || ( end2 >= firstnumber + inpoints ) ) { + if ( !quiet ) { + printf( "Warning: Invalid second endpoint of segment %d in %s.\n", i, + polyfilename ); + } + } + else { + endpoint1 = getpoint( end1 ); + endpoint2 = getpoint( end2 ); + if ( ( endpoint1[0] == endpoint2[0] ) && ( endpoint1[1] == endpoint2[1] ) ) { + if ( !quiet ) { + printf( "Warning: Endpoints of segment %d are coincident in %s.\n", + i, polyfilename ); + } + } + else { + insertsegment( endpoint1, endpoint2, boundmarker ); + } + } + } + } + else { + segments = 0; + } + if ( convex || !poly ) { + /* Enclose the convex hull with shell edges. */ + if ( verbose ) { + printf( " Enclosing convex hull with segments.\n" ); + } + markhull(); + } + return segments; } /** **/ @@ -10050,60 +10167,60 @@ char *polyfilename; /* */ /*****************************************************************************/ -void infecthull() -{ - struct triedge hulltri; - struct triedge nexttri; - struct triedge starttri; - struct edge hulledge; - triangle **deadtri; - point horg, hdest; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose) { - printf(" Marking concavities (external triangles) for elimination.\n"); - } - /* Find a triangle handle on the hull. */ - hulltri.tri = dummytri; - hulltri.orient = 0; - symself(hulltri); - /* Remember where we started so we know when to stop. */ - triedgecopy(hulltri, starttri); - /* Go once counterclockwise around the convex hull. */ - do { - /* Ignore triangles that are already infected. */ - if (!infected(hulltri)) { - /* Is the triangle protected by a shell edge? */ - tspivot(hulltri, hulledge); - if (hulledge.sh == dummysh) { - /* The triangle is not protected; infect it. */ - infect(hulltri); - deadtri = (triangle **) poolalloc(&viri); - *deadtri = hulltri.tri; - } else { - /* The triangle is protected; set boundary markers if appropriate. */ - if (mark(hulledge) == 0) { - setmark(hulledge, 1); - org(hulltri, horg); - dest(hulltri, hdest); - if (pointmark(horg) == 0) { - setpointmark(horg, 1); - } - if (pointmark(hdest) == 0) { - setpointmark(hdest, 1); - } - } - } - } - /* To find the next hull edge, go clockwise around the next vertex. */ - lnextself(hulltri); - oprev(hulltri, nexttri); - while (nexttri.tri != dummytri) { - triedgecopy(nexttri, hulltri); - oprev(hulltri, nexttri); - } - } while (!triedgeequal(hulltri, starttri)); +void infecthull(){ + struct triedge hulltri; + struct triedge nexttri; + struct triedge starttri; + struct edge hulledge; + triangle **deadtri; + point horg, hdest; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + if ( verbose ) { + printf( " Marking concavities (external triangles) for elimination.\n" ); + } + /* Find a triangle handle on the hull. */ + hulltri.tri = dummytri; + hulltri.orient = 0; + symself( hulltri ); + /* Remember where we started so we know when to stop. */ + triedgecopy( hulltri, starttri ); + /* Go once counterclockwise around the convex hull. */ + do { + /* Ignore triangles that are already infected. */ + if ( !infected( hulltri ) ) { + /* Is the triangle protected by a shell edge? */ + tspivot( hulltri, hulledge ); + if ( hulledge.sh == dummysh ) { + /* The triangle is not protected; infect it. */ + infect( hulltri ); + deadtri = (triangle **) poolalloc( &viri ); + *deadtri = hulltri.tri; + } + else { + /* The triangle is protected; set boundary markers if appropriate. */ + if ( mark( hulledge ) == 0 ) { + setmark( hulledge, 1 ); + org( hulltri, horg ); + dest( hulltri, hdest ); + if ( pointmark( horg ) == 0 ) { + setpointmark( horg, 1 ); + } + if ( pointmark( hdest ) == 0 ) { + setpointmark( hdest, 1 ); + } + } + } + } + /* To find the next hull edge, go clockwise around the next vertex. */ + lnextself( hulltri ); + oprev( hulltri, nexttri ); + while ( nexttri.tri != dummytri ) { + triedgecopy( nexttri, hulltri ); + oprev( hulltri, nexttri ); + } + } while ( !triedgeequal( hulltri, starttri ) ); } /*****************************************************************************/ @@ -10123,190 +10240,194 @@ void infecthull() /* */ /*****************************************************************************/ -void plague() -{ - struct triedge testtri; - struct triedge neighbor; - triangle **virusloop; - triangle **deadtri; - struct edge neighborshelle; - point testpoint; - point norg, ndest; - point deadorg, deaddest, deadapex; - int killorg; - triangle ptr; /* Temporary variable used by sym() and onext(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose) { - printf(" Marking neighbors of marked triangles.\n"); - } - /* Loop through all the infected triangles, spreading the virus to */ - /* their neighbors, then to their neighbors' neighbors. */ - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - /* A triangle is marked as infected by messing with one of its shell */ - /* edges, setting it to an illegal value. Hence, we have to */ - /* temporarily uninfect this triangle so that we can examine its */ - /* adjacent shell edges. */ - uninfect(testtri); - if (verbose > 2) { - /* Assign the triangle an orientation for convenience in */ - /* checking its points. */ - testtri.orient = 0; - org(testtri, deadorg); - dest(testtri, deaddest); - apex(testtri, deadapex); - printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - deadorg[0], deadorg[1], deaddest[0], deaddest[1], - deadapex[0], deadapex[1]); - } - /* Check each of the triangle's three neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - /* Find the neighbor. */ - sym(testtri, neighbor); - /* Check for a shell between the triangle and its neighbor. */ - tspivot(testtri, neighborshelle); - /* Check if the neighbor is nonexistent or already infected. */ - if ((neighbor.tri == dummytri) || infected(neighbor)) { - if (neighborshelle.sh != dummysh) { - /* There is a shell edge separating the triangle from its */ - /* neighbor, but both triangles are dying, so the shell */ - /* edge dies too. */ - shelledealloc(neighborshelle.sh); - if (neighbor.tri != dummytri) { - /* Make sure the shell edge doesn't get deallocated again */ - /* later when the infected neighbor is visited. */ - uninfect(neighbor); - tsdissolve(neighbor); - infect(neighbor); - } - } - } else { /* The neighbor exists and is not infected. */ - if (neighborshelle.sh == dummysh) { - /* There is no shell edge protecting the neighbor, so */ - /* the neighbor becomes infected. */ - if (verbose > 2) { - org(neighbor, deadorg); - dest(neighbor, deaddest); - apex(neighbor, deadapex); - printf( - " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - deadorg[0], deadorg[1], deaddest[0], deaddest[1], - deadapex[0], deadapex[1]); - } - infect(neighbor); - /* Ensure that the neighbor's neighbors will be infected. */ - deadtri = (triangle **) poolalloc(&viri); - *deadtri = neighbor.tri; - } else { /* The neighbor is protected by a shell edge. */ - /* Remove this triangle from the shell edge. */ - stdissolve(neighborshelle); - /* The shell edge becomes a boundary. Set markers accordingly. */ - if (mark(neighborshelle) == 0) { - setmark(neighborshelle, 1); - } - org(neighbor, norg); - dest(neighbor, ndest); - if (pointmark(norg) == 0) { - setpointmark(norg, 1); - } - if (pointmark(ndest) == 0) { - setpointmark(ndest, 1); - } - } - } - } - /* Remark the triangle as infected, so it doesn't get added to the */ - /* virus pool again. */ - infect(testtri); - virusloop = (triangle **) traverse(&viri); - } - - if (verbose) { - printf(" Deleting marked triangles.\n"); - } - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - - /* Check each of the three corners of the triangle for elimination. */ - /* This is done by walking around each point, checking if it is */ - /* still connected to at least one live triangle. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - org(testtri, testpoint); - /* Check if the point has already been tested. */ - if (testpoint != (point) NULL) { - killorg = 1; - /* Mark the corner of the triangle as having been tested. */ - setorg(testtri, NULL); - /* Walk counterclockwise about the point. */ - onext(testtri, neighbor); - /* Stop upon reaching a boundary or the starting triangle. */ - while ((neighbor.tri != dummytri) - && (!triedgeequal(neighbor, testtri))) { - if (infected(neighbor)) { - /* Mark the corner of this triangle as having been tested. */ - setorg(neighbor, NULL); - } else { - /* A live triangle. The point survives. */ - killorg = 0; - } - /* Walk counterclockwise about the point. */ - onextself(neighbor); - } - /* If we reached a boundary, we must walk clockwise as well. */ - if (neighbor.tri == dummytri) { - /* Walk clockwise about the point. */ - oprev(testtri, neighbor); - /* Stop upon reaching a boundary. */ - while (neighbor.tri != dummytri) { - if (infected(neighbor)) { - /* Mark the corner of this triangle as having been tested. */ - setorg(neighbor, NULL); - } else { - /* A live triangle. The point survives. */ - killorg = 0; - } - /* Walk clockwise about the point. */ - oprevself(neighbor); - } - } - if (killorg) { - if (verbose > 1) { - printf(" Deleting point (%.12g, %.12g)\n", - testpoint[0], testpoint[1]); - } - pointdealloc(testpoint); - } - } - } - - /* Record changes in the number of boundary edges, and disconnect */ - /* dead triangles from their neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - sym(testtri, neighbor); - if (neighbor.tri == dummytri) { - /* There is no neighboring triangle on this edge, so this edge */ - /* is a boundary edge. This triangle is being deleted, so this */ - /* boundary edge is deleted. */ - hullsize--; - } else { - /* Disconnect the triangle from its neighbor. */ - dissolve(neighbor); - /* There is a neighboring triangle on this edge, so this edge */ - /* becomes a boundary edge when this triangle is deleted. */ - hullsize++; - } - } - /* Return the dead triangle to the pool of triangles. */ - triangledealloc(testtri.tri); - virusloop = (triangle **) traverse(&viri); - } - /* Empty the virus pool. */ - poolrestart(&viri); +void plague(){ + struct triedge testtri; + struct triedge neighbor; + triangle **virusloop; + triangle **deadtri; + struct edge neighborshelle; + point testpoint; + point norg, ndest; + point deadorg, deaddest, deadapex; + int killorg; + triangle ptr; /* Temporary variable used by sym() and onext(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + if ( verbose ) { + printf( " Marking neighbors of marked triangles.\n" ); + } + /* Loop through all the infected triangles, spreading the virus to */ + /* their neighbors, then to their neighbors' neighbors. */ + traversalinit( &viri ); + virusloop = (triangle **) traverse( &viri ); + while ( virusloop != (triangle **) NULL ) { + testtri.tri = *virusloop; + /* A triangle is marked as infected by messing with one of its shell */ + /* edges, setting it to an illegal value. Hence, we have to */ + /* temporarily uninfect this triangle so that we can examine its */ + /* adjacent shell edges. */ + uninfect( testtri ); + if ( verbose > 2 ) { + /* Assign the triangle an orientation for convenience in */ + /* checking its points. */ + testtri.orient = 0; + org( testtri, deadorg ); + dest( testtri, deaddest ); + apex( testtri, deadapex ); + printf( " Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + deadorg[0], deadorg[1], deaddest[0], deaddest[1], + deadapex[0], deadapex[1] ); + } + /* Check each of the triangle's three neighbors. */ + for ( testtri.orient = 0; testtri.orient < 3; testtri.orient++ ) { + /* Find the neighbor. */ + sym( testtri, neighbor ); + /* Check for a shell between the triangle and its neighbor. */ + tspivot( testtri, neighborshelle ); + /* Check if the neighbor is nonexistent or already infected. */ + if ( ( neighbor.tri == dummytri ) || infected( neighbor ) ) { + if ( neighborshelle.sh != dummysh ) { + /* There is a shell edge separating the triangle from its */ + /* neighbor, but both triangles are dying, so the shell */ + /* edge dies too. */ + shelledealloc( neighborshelle.sh ); + if ( neighbor.tri != dummytri ) { + /* Make sure the shell edge doesn't get deallocated again */ + /* later when the infected neighbor is visited. */ + uninfect( neighbor ); + tsdissolve( neighbor ); + infect( neighbor ); + } + } + } + else { /* The neighbor exists and is not infected. */ + if ( neighborshelle.sh == dummysh ) { + /* There is no shell edge protecting the neighbor, so */ + /* the neighbor becomes infected. */ + if ( verbose > 2 ) { + org( neighbor, deadorg ); + dest( neighbor, deaddest ); + apex( neighbor, deadapex ); + printf( + " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + deadorg[0], deadorg[1], deaddest[0], deaddest[1], + deadapex[0], deadapex[1] ); + } + infect( neighbor ); + /* Ensure that the neighbor's neighbors will be infected. */ + deadtri = (triangle **) poolalloc( &viri ); + *deadtri = neighbor.tri; + } + else { /* The neighbor is protected by a shell edge. */ + /* Remove this triangle from the shell edge. */ + stdissolve( neighborshelle ); + /* The shell edge becomes a boundary. Set markers accordingly. */ + if ( mark( neighborshelle ) == 0 ) { + setmark( neighborshelle, 1 ); + } + org( neighbor, norg ); + dest( neighbor, ndest ); + if ( pointmark( norg ) == 0 ) { + setpointmark( norg, 1 ); + } + if ( pointmark( ndest ) == 0 ) { + setpointmark( ndest, 1 ); + } + } + } + } + /* Remark the triangle as infected, so it doesn't get added to the */ + /* virus pool again. */ + infect( testtri ); + virusloop = (triangle **) traverse( &viri ); + } + + if ( verbose ) { + printf( " Deleting marked triangles.\n" ); + } + traversalinit( &viri ); + virusloop = (triangle **) traverse( &viri ); + while ( virusloop != (triangle **) NULL ) { + testtri.tri = *virusloop; + + /* Check each of the three corners of the triangle for elimination. */ + /* This is done by walking around each point, checking if it is */ + /* still connected to at least one live triangle. */ + for ( testtri.orient = 0; testtri.orient < 3; testtri.orient++ ) { + org( testtri, testpoint ); + /* Check if the point has already been tested. */ + if ( testpoint != (point) NULL ) { + killorg = 1; + /* Mark the corner of the triangle as having been tested. */ + setorg( testtri, NULL ); + /* Walk counterclockwise about the point. */ + onext( testtri, neighbor ); + /* Stop upon reaching a boundary or the starting triangle. */ + while ( ( neighbor.tri != dummytri ) + && ( !triedgeequal( neighbor, testtri ) ) ) { + if ( infected( neighbor ) ) { + /* Mark the corner of this triangle as having been tested. */ + setorg( neighbor, NULL ); + } + else { + /* A live triangle. The point survives. */ + killorg = 0; + } + /* Walk counterclockwise about the point. */ + onextself( neighbor ); + } + /* If we reached a boundary, we must walk clockwise as well. */ + if ( neighbor.tri == dummytri ) { + /* Walk clockwise about the point. */ + oprev( testtri, neighbor ); + /* Stop upon reaching a boundary. */ + while ( neighbor.tri != dummytri ) { + if ( infected( neighbor ) ) { + /* Mark the corner of this triangle as having been tested. */ + setorg( neighbor, NULL ); + } + else { + /* A live triangle. The point survives. */ + killorg = 0; + } + /* Walk clockwise about the point. */ + oprevself( neighbor ); + } + } + if ( killorg ) { + if ( verbose > 1 ) { + printf( " Deleting point (%.12g, %.12g)\n", + testpoint[0], testpoint[1] ); + } + pointdealloc( testpoint ); + } + } + } + + /* Record changes in the number of boundary edges, and disconnect */ + /* dead triangles from their neighbors. */ + for ( testtri.orient = 0; testtri.orient < 3; testtri.orient++ ) { + sym( testtri, neighbor ); + if ( neighbor.tri == dummytri ) { + /* There is no neighboring triangle on this edge, so this edge */ + /* is a boundary edge. This triangle is being deleted, so this */ + /* boundary edge is deleted. */ + hullsize--; + } + else { + /* Disconnect the triangle from its neighbor. */ + dissolve( neighbor ); + /* There is a neighboring triangle on this edge, so this edge */ + /* becomes a boundary edge when this triangle is deleted. */ + hullsize++; + } + } + /* Return the dead triangle to the pool of triangles. */ + triangledealloc( testtri.tri ); + virusloop = (triangle **) traverse( &viri ); + } + /* Empty the virus pool. */ + poolrestart( &viri ); } /*****************************************************************************/ @@ -10324,97 +10445,97 @@ void plague() /* */ /*****************************************************************************/ -void regionplague(attribute, area) +void regionplague( attribute, area ) REAL attribute; REAL area; { - struct triedge testtri; - struct triedge neighbor; - triangle **virusloop; - triangle **regiontri; - struct edge neighborshelle; - point regionorg, regiondest, regionapex; - triangle ptr; /* Temporary variable used by sym() and onext(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose > 1) { - printf(" Marking neighbors of marked triangles.\n"); - } - /* Loop through all the infected triangles, spreading the attribute */ - /* and/or area constraint to their neighbors, then to their neighbors' */ - /* neighbors. */ - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - /* A triangle is marked as infected by messing with one of its shell */ - /* edges, setting it to an illegal value. Hence, we have to */ - /* temporarily uninfect this triangle so that we can examine its */ - /* adjacent shell edges. */ - uninfect(testtri); - if (regionattrib) { - /* Set an attribute. */ - setelemattribute(testtri, eextras, attribute); - } - if (vararea) { - /* Set an area constraint. */ - setareabound(testtri, area); - } - if (verbose > 2) { - /* Assign the triangle an orientation for convenience in */ - /* checking its points. */ - testtri.orient = 0; - org(testtri, regionorg); - dest(testtri, regiondest); - apex(testtri, regionapex); - printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - regionorg[0], regionorg[1], regiondest[0], regiondest[1], - regionapex[0], regionapex[1]); - } - /* Check each of the triangle's three neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - /* Find the neighbor. */ - sym(testtri, neighbor); - /* Check for a shell between the triangle and its neighbor. */ - tspivot(testtri, neighborshelle); - /* Make sure the neighbor exists, is not already infected, and */ - /* isn't protected by a shell edge. */ - if ((neighbor.tri != dummytri) && !infected(neighbor) - && (neighborshelle.sh == dummysh)) { - if (verbose > 2) { - org(neighbor, regionorg); - dest(neighbor, regiondest); - apex(neighbor, regionapex); - printf(" Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - regionorg[0], regionorg[1], regiondest[0], regiondest[1], - regionapex[0], regionapex[1]); - } - /* Infect the neighbor. */ - infect(neighbor); - /* Ensure that the neighbor's neighbors will be infected. */ - regiontri = (triangle **) poolalloc(&viri); - *regiontri = neighbor.tri; - } - } - /* Remark the triangle as infected, so it doesn't get added to the */ - /* virus pool again. */ - infect(testtri); - virusloop = (triangle **) traverse(&viri); - } - - /* Uninfect all triangles. */ - if (verbose > 1) { - printf(" Unmarking marked triangles.\n"); - } - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - uninfect(testtri); - virusloop = (triangle **) traverse(&viri); - } - /* Empty the virus pool. */ - poolrestart(&viri); + struct triedge testtri; + struct triedge neighbor; + triangle **virusloop; + triangle **regiontri; + struct edge neighborshelle; + point regionorg, regiondest, regionapex; + triangle ptr; /* Temporary variable used by sym() and onext(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + if ( verbose > 1 ) { + printf( " Marking neighbors of marked triangles.\n" ); + } + /* Loop through all the infected triangles, spreading the attribute */ + /* and/or area constraint to their neighbors, then to their neighbors' */ + /* neighbors. */ + traversalinit( &viri ); + virusloop = (triangle **) traverse( &viri ); + while ( virusloop != (triangle **) NULL ) { + testtri.tri = *virusloop; + /* A triangle is marked as infected by messing with one of its shell */ + /* edges, setting it to an illegal value. Hence, we have to */ + /* temporarily uninfect this triangle so that we can examine its */ + /* adjacent shell edges. */ + uninfect( testtri ); + if ( regionattrib ) { + /* Set an attribute. */ + setelemattribute( testtri, eextras, attribute ); + } + if ( vararea ) { + /* Set an area constraint. */ + setareabound( testtri, area ); + } + if ( verbose > 2 ) { + /* Assign the triangle an orientation for convenience in */ + /* checking its points. */ + testtri.orient = 0; + org( testtri, regionorg ); + dest( testtri, regiondest ); + apex( testtri, regionapex ); + printf( " Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + regionorg[0], regionorg[1], regiondest[0], regiondest[1], + regionapex[0], regionapex[1] ); + } + /* Check each of the triangle's three neighbors. */ + for ( testtri.orient = 0; testtri.orient < 3; testtri.orient++ ) { + /* Find the neighbor. */ + sym( testtri, neighbor ); + /* Check for a shell between the triangle and its neighbor. */ + tspivot( testtri, neighborshelle ); + /* Make sure the neighbor exists, is not already infected, and */ + /* isn't protected by a shell edge. */ + if ( ( neighbor.tri != dummytri ) && !infected( neighbor ) + && ( neighborshelle.sh == dummysh ) ) { + if ( verbose > 2 ) { + org( neighbor, regionorg ); + dest( neighbor, regiondest ); + apex( neighbor, regionapex ); + printf( " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + regionorg[0], regionorg[1], regiondest[0], regiondest[1], + regionapex[0], regionapex[1] ); + } + /* Infect the neighbor. */ + infect( neighbor ); + /* Ensure that the neighbor's neighbors will be infected. */ + regiontri = (triangle **) poolalloc( &viri ); + *regiontri = neighbor.tri; + } + } + /* Remark the triangle as infected, so it doesn't get added to the */ + /* virus pool again. */ + infect( testtri ); + virusloop = (triangle **) traverse( &viri ); + } + + /* Uninfect all triangles. */ + if ( verbose > 1 ) { + printf( " Unmarking marked triangles.\n" ); + } + traversalinit( &viri ); + virusloop = (triangle **) traverse( &viri ); + while ( virusloop != (triangle **) NULL ) { + testtri.tri = *virusloop; + uninfect( testtri ); + virusloop = (triangle **) traverse( &viri ); + } + /* Empty the virus pool. */ + poolrestart( &viri ); } /*****************************************************************************/ @@ -10429,172 +10550,174 @@ REAL area; /* */ /*****************************************************************************/ -void carveholes(holelist, holes, regionlist, regions) -REAL *holelist; +void carveholes( holelist, holes, regionlist, regions ) +REAL * holelist; int holes; REAL *regionlist; int regions; { - struct triedge searchtri; - struct triedge triangleloop; - struct triedge *regiontris; - triangle **holetri; - triangle **regiontri; - point searchorg, searchdest; - enum locateresult intersect; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - - if (!(quiet || (noholes && convex))) { - printf("Removing unwanted triangles.\n"); - if (verbose && (holes > 0)) { - printf(" Marking holes for elimination.\n"); - } - } - - if (regions > 0) { - /* Allocate storage for the triangles in which region points fall. */ - regiontris = (struct triedge *) malloc(regions * sizeof(struct triedge)); - if (regiontris == (struct triedge *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - - if (((holes > 0) && !noholes) || !convex || (regions > 0)) { - /* Initialize a pool of viri to be used for holes, concavities, */ - /* regional attributes, and/or regional area constraints. */ - poolinit(&viri, sizeof(triangle *), VIRUSPERBLOCK, POINTER, 0); - } - - if (!convex) { - /* Mark as infected any unprotected triangles on the boundary. */ - /* This is one way by which concavities are created. */ - infecthull(); - } - - if ((holes > 0) && !noholes) { - /* Infect each triangle in which a hole lies. */ - for (i = 0; i < 2 * holes; i += 2) { - /* Ignore holes that aren't within the bounds of the mesh. */ - if ((holelist[i] >= xmin) && (holelist[i] <= xmax) - && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)) { - /* Start searching from some triangle on the outer boundary. */ - searchtri.tri = dummytri; - searchtri.orient = 0; - symself(searchtri); - /* Ensure that the hole is to the left of this boundary edge; */ - /* otherwise, locate() will falsely report that the hole */ - /* falls within the starting triangle. */ - org(searchtri, searchorg); - dest(searchtri, searchdest); - if (counterclockwise(searchorg, searchdest, &holelist[i]) > 0.0) { - /* Find a triangle that contains the hole. */ - intersect = locate(&holelist[i], &searchtri); - if ((intersect != OUTSIDE) && (!infected(searchtri))) { - /* Infect the triangle. This is done by marking the triangle */ - /* as infect and including the triangle in the virus pool. */ - infect(searchtri); - holetri = (triangle **) poolalloc(&viri); - *holetri = searchtri.tri; - } - } - } - } - } - - /* Now, we have to find all the regions BEFORE we carve the holes, because */ - /* locate() won't work when the triangulation is no longer convex. */ - /* (Incidentally, this is the reason why regional attributes and area */ - /* constraints can't be used when refining a preexisting mesh, which */ - /* might not be convex; they can only be used with a freshly */ - /* triangulated PSLG.) */ - if (regions > 0) { - /* Find the starting triangle for each region. */ - for (i = 0; i < regions; i++) { - regiontris[i].tri = dummytri; - /* Ignore region points that aren't within the bounds of the mesh. */ - if ((regionlist[4 * i] >= xmin) && (regionlist[4 * i] <= xmax) && - (regionlist[4 * i + 1] >= ymin) && (regionlist[4 * i + 1] <= ymax)) { - /* Start searching from some triangle on the outer boundary. */ - searchtri.tri = dummytri; - searchtri.orient = 0; - symself(searchtri); - /* Ensure that the region point is to the left of this boundary */ - /* edge; otherwise, locate() will falsely report that the */ - /* region point falls within the starting triangle. */ - org(searchtri, searchorg); - dest(searchtri, searchdest); - if (counterclockwise(searchorg, searchdest, ®ionlist[4 * i]) > - 0.0) { - /* Find a triangle that contains the region point. */ - intersect = locate(®ionlist[4 * i], &searchtri); - if ((intersect != OUTSIDE) && (!infected(searchtri))) { - /* Record the triangle for processing after the */ - /* holes have been carved. */ - triedgecopy(searchtri, regiontris[i]); - } - } - } - } - } - - if (viri.items > 0) { - /* Carve the holes and concavities. */ - plague(); - } - /* The virus pool should be empty now. */ - - if (regions > 0) { - if (!quiet) { - if (regionattrib) { - if (vararea) { - printf("Spreading regional attributes and area constraints.\n"); - } else { - printf("Spreading regional attributes.\n"); - } - } else { - printf("Spreading regional area constraints.\n"); - } - } - if (regionattrib && !refine) { - /* Assign every triangle a regional attribute of zero. */ - traversalinit(&triangles); - triangleloop.orient = 0; - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - setelemattribute(triangleloop, eextras, 0.0); - triangleloop.tri = triangletraverse(); - } - } - for (i = 0; i < regions; i++) { - if (regiontris[i].tri != dummytri) { - /* Make sure the triangle under consideration still exists. */ - /* It may have been eaten by the virus. */ - if (regiontris[i].tri[3] != (triangle) NULL) { - /* Put one triangle in the virus pool. */ - infect(regiontris[i]); - regiontri = (triangle **) poolalloc(&viri); - *regiontri = regiontris[i].tri; - /* Apply one region's attribute and/or area constraint. */ - regionplague(regionlist[4 * i + 2], regionlist[4 * i + 3]); - /* The virus pool should be empty now. */ - } - } - } - if (regionattrib && !refine) { - /* Note the fact that each triangle has an additional attribute. */ - eextras++; - } - } - - /* Free up memory. */ - if (((holes > 0) && !noholes) || !convex || (regions > 0)) { - pooldeinit(&viri); - } - if (regions > 0) { - free(regiontris); - } + struct triedge searchtri; + struct triedge triangleloop; + struct triedge *regiontris; + triangle **holetri; + triangle **regiontri; + point searchorg, searchdest; + enum locateresult intersect; + int i; + triangle ptr; /* Temporary variable used by sym(). */ + + if ( !( quiet || ( noholes && convex ) ) ) { + printf( "Removing unwanted triangles.\n" ); + if ( verbose && ( holes > 0 ) ) { + printf( " Marking holes for elimination.\n" ); + } + } + + if ( regions > 0 ) { + /* Allocate storage for the triangles in which region points fall. */ + regiontris = (struct triedge *) malloc( regions * sizeof( struct triedge ) ); + if ( regiontris == (struct triedge *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + + if ( ( ( holes > 0 ) && !noholes ) || !convex || ( regions > 0 ) ) { + /* Initialize a pool of viri to be used for holes, concavities, */ + /* regional attributes, and/or regional area constraints. */ + poolinit( &viri, sizeof( triangle * ), VIRUSPERBLOCK, POINTER, 0 ); + } + + if ( !convex ) { + /* Mark as infected any unprotected triangles on the boundary. */ + /* This is one way by which concavities are created. */ + infecthull(); + } + + if ( ( holes > 0 ) && !noholes ) { + /* Infect each triangle in which a hole lies. */ + for ( i = 0; i < 2 * holes; i += 2 ) { + /* Ignore holes that aren't within the bounds of the mesh. */ + if ( ( holelist[i] >= xmin ) && ( holelist[i] <= xmax ) + && ( holelist[i + 1] >= ymin ) && ( holelist[i + 1] <= ymax ) ) { + /* Start searching from some triangle on the outer boundary. */ + searchtri.tri = dummytri; + searchtri.orient = 0; + symself( searchtri ); + /* Ensure that the hole is to the left of this boundary edge; */ + /* otherwise, locate() will falsely report that the hole */ + /* falls within the starting triangle. */ + org( searchtri, searchorg ); + dest( searchtri, searchdest ); + if ( counterclockwise( searchorg, searchdest, &holelist[i] ) > 0.0 ) { + /* Find a triangle that contains the hole. */ + intersect = locate( &holelist[i], &searchtri ); + if ( ( intersect != OUTSIDE ) && ( !infected( searchtri ) ) ) { + /* Infect the triangle. This is done by marking the triangle */ + /* as infect and including the triangle in the virus pool. */ + infect( searchtri ); + holetri = (triangle **) poolalloc( &viri ); + *holetri = searchtri.tri; + } + } + } + } + } + + /* Now, we have to find all the regions BEFORE we carve the holes, because */ + /* locate() won't work when the triangulation is no longer convex. */ + /* (Incidentally, this is the reason why regional attributes and area */ + /* constraints can't be used when refining a preexisting mesh, which */ + /* might not be convex; they can only be used with a freshly */ + /* triangulated PSLG.) */ + if ( regions > 0 ) { + /* Find the starting triangle for each region. */ + for ( i = 0; i < regions; i++ ) { + regiontris[i].tri = dummytri; + /* Ignore region points that aren't within the bounds of the mesh. */ + if ( ( regionlist[4 * i] >= xmin ) && ( regionlist[4 * i] <= xmax ) && + ( regionlist[4 * i + 1] >= ymin ) && ( regionlist[4 * i + 1] <= ymax ) ) { + /* Start searching from some triangle on the outer boundary. */ + searchtri.tri = dummytri; + searchtri.orient = 0; + symself( searchtri ); + /* Ensure that the region point is to the left of this boundary */ + /* edge; otherwise, locate() will falsely report that the */ + /* region point falls within the starting triangle. */ + org( searchtri, searchorg ); + dest( searchtri, searchdest ); + if ( counterclockwise( searchorg, searchdest, ®ionlist[4 * i] ) > + 0.0 ) { + /* Find a triangle that contains the region point. */ + intersect = locate( ®ionlist[4 * i], &searchtri ); + if ( ( intersect != OUTSIDE ) && ( !infected( searchtri ) ) ) { + /* Record the triangle for processing after the */ + /* holes have been carved. */ + triedgecopy( searchtri, regiontris[i] ); + } + } + } + } + } + + if ( viri.items > 0 ) { + /* Carve the holes and concavities. */ + plague(); + } + /* The virus pool should be empty now. */ + + if ( regions > 0 ) { + if ( !quiet ) { + if ( regionattrib ) { + if ( vararea ) { + printf( "Spreading regional attributes and area constraints.\n" ); + } + else { + printf( "Spreading regional attributes.\n" ); + } + } + else { + printf( "Spreading regional area constraints.\n" ); + } + } + if ( regionattrib && !refine ) { + /* Assign every triangle a regional attribute of zero. */ + traversalinit( &triangles ); + triangleloop.orient = 0; + triangleloop.tri = triangletraverse(); + while ( triangleloop.tri != (triangle *) NULL ) { + setelemattribute( triangleloop, eextras, 0.0 ); + triangleloop.tri = triangletraverse(); + } + } + for ( i = 0; i < regions; i++ ) { + if ( regiontris[i].tri != dummytri ) { + /* Make sure the triangle under consideration still exists. */ + /* It may have been eaten by the virus. */ + if ( regiontris[i].tri[3] != (triangle) NULL ) { + /* Put one triangle in the virus pool. */ + infect( regiontris[i] ); + regiontri = (triangle **) poolalloc( &viri ); + *regiontri = regiontris[i].tri; + /* Apply one region's attribute and/or area constraint. */ + regionplague( regionlist[4 * i + 2], regionlist[4 * i + 3] ); + /* The virus pool should be empty now. */ + } + } + } + if ( regionattrib && !refine ) { + /* Note the fact that each triangle has an additional attribute. */ + eextras++; + } + } + + /* Free up memory. */ + if ( ( ( holes > 0 ) && !noholes ) || !convex || ( regions > 0 ) ) { + pooldeinit( &viri ); + } + if ( regions > 0 ) { + free( regiontris ); + } } /** **/ @@ -10614,19 +10737,18 @@ int regions; #ifndef CDT_ONLY -void tallyencs() -{ - struct edge edgeloop; - int dummy; - - traversalinit(&shelles); - edgeloop.shorient = 0; - edgeloop.sh = shelletraverse(); - while (edgeloop.sh != (shelle *) NULL) { - /* If the segment is encroached, add it to the list. */ - dummy = checkedge4encroach(&edgeloop); - edgeloop.sh = shelletraverse(); - } +void tallyencs(){ + struct edge edgeloop; + int dummy; + + traversalinit( &shelles ); + edgeloop.shorient = 0; + edgeloop.sh = shelletraverse(); + while ( edgeloop.sh != (shelle *) NULL ) { + /* If the segment is encroached, add it to the list. */ + dummy = checkedge4encroach( &edgeloop ); + edgeloop.sh = shelletraverse(); + } } #endif /* not CDT_ONLY */ @@ -10639,14 +10761,13 @@ void tallyencs() #ifndef CDT_ONLY -void precisionerror() -{ - printf("Try increasing the area criterion and/or reducing the minimum\n"); - printf(" allowable angle so that tiny triangles are not created.\n"); +void precisionerror(){ + printf( "Try increasing the area criterion and/or reducing the minimum\n" ); + printf( " allowable angle so that tiny triangles are not created.\n" ); #ifdef SINGLE - printf("Alternatively, try recompiling me with double precision\n"); - printf(" arithmetic (by removing \"#define SINGLE\" from the\n"); - printf(" source file or \"-DSINGLE\" from the makefile).\n"); + printf( "Alternatively, try recompiling me with double precision\n" ); + printf( " arithmetic (by removing \"#define SINGLE\" from the\n" ); + printf( " source file or \"-DSINGLE\" from the makefile).\n" ); #endif /* SINGLE */ } @@ -10671,135 +10792,136 @@ void precisionerror() #ifndef CDT_ONLY -void repairencs(flaws) +void repairencs( flaws ) int flaws; { - struct triedge enctri; - struct triedge testtri; - struct edge *encloop; - struct edge testsh; - point eorg, edest; - point newpoint; - enum insertsiteresult success; - REAL segmentlength, nearestpoweroftwo; - REAL split; - int acuteorg, acutedest; - int dummy; - int i; - triangle ptr; /* Temporary variable used by stpivot(). */ - shelle sptr; /* Temporary variable used by snext(). */ - - while ((badsegments.items > 0) && (steinerleft != 0)) { - traversalinit(&badsegments); - encloop = badsegmenttraverse(); - while ((encloop != (struct edge *) NULL) && (steinerleft != 0)) { - /* To decide where to split a segment, we need to know if the */ - /* segment shares an endpoint with an adjacent segment. */ - /* The concern is that, if we simply split every encroached */ - /* segment in its center, two adjacent segments with a small */ - /* angle between them might lead to an infinite loop; each */ - /* point added to split one segment will encroach upon the */ - /* other segment, which must then be split with a point that */ - /* will encroach upon the first segment, and so on forever. */ - /* To avoid this, imagine a set of concentric circles, whose */ - /* radii are powers of two, about each segment endpoint. */ - /* These concentric circles determine where the segment is */ - /* split. (If both endpoints are shared with adjacent */ - /* segments, split the segment in the middle, and apply the */ - /* concentric shells for later splittings.) */ - - /* Is the origin shared with another segment? */ - stpivot(*encloop, enctri); - lnext(enctri, testtri); - tspivot(testtri, testsh); - acuteorg = testsh.sh != dummysh; - /* Is the destination shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acutedest = testsh.sh != dummysh; - /* Now, check the other side of the segment, if there's a triangle */ - /* there. */ - sym(enctri, testtri); - if (testtri.tri != dummytri) { - /* Is the destination shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acutedest = acutedest || (testsh.sh != dummysh); - /* Is the origin shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acuteorg = acuteorg || (testsh.sh != dummysh); - } - - sorg(*encloop, eorg); - sdest(*encloop, edest); - /* Use the concentric circles if exactly one endpoint is shared */ - /* with another adjacent segment. */ - if (acuteorg ^ acutedest) { - segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) - + (edest[1] - eorg[1]) * (edest[1] - eorg[1])); - /* Find the power of two nearest the segment's length. */ - nearestpoweroftwo = 1.0; - while (segmentlength > SQUAREROOTTWO * nearestpoweroftwo) { - nearestpoweroftwo *= 2.0; - } - while (segmentlength < (0.5 * SQUAREROOTTWO) * nearestpoweroftwo) { - nearestpoweroftwo *= 0.5; - } - /* Where do we split the segment? */ - split = 0.5 * nearestpoweroftwo / segmentlength; - if (acutedest) { - split = 1.0 - split; - } - } else { - /* If we're not worried about adjacent segments, split */ - /* this segment in the middle. */ - split = 0.5; - } - - /* Create the new point. */ - newpoint = (point) poolalloc(&points); - /* Interpolate its coordinate and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = (1.0 - split) * eorg[i] + split * edest[i]; - } - setpointmark(newpoint, mark(*encloop)); - if (verbose > 1) { - printf( - " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", - eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1]); - } - /* Check whether the new point lies on an endpoint. */ - if (((newpoint[0] == eorg[0]) && (newpoint[1] == eorg[1])) - || ((newpoint[0] == edest[0]) && (newpoint[1] == edest[1]))) { - printf("Error: Ran out of precision at (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - printf("I attempted to split a segment to a smaller size than can\n"); - printf(" be accommodated by the finite precision of floating point\n" - ); - printf(" arithmetic.\n"); - precisionerror(); - exit(1); - } - /* Insert the splitting point. This should always succeed. */ - success = insertsite(newpoint, &enctri, encloop, flaws, flaws); - if ((success != SUCCESSFULPOINT) && (success != ENCROACHINGPOINT)) { - printf("Internal error in repairencs():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - if (steinerleft > 0) { - steinerleft--; - } - /* Check the two new subsegments to see if they're encroached. */ - dummy = checkedge4encroach(encloop); - snextself(*encloop); - dummy = checkedge4encroach(encloop); - - badsegmentdealloc(encloop); - encloop = badsegmenttraverse(); - } - } + struct triedge enctri; + struct triedge testtri; + struct edge *encloop; + struct edge testsh; + point eorg, edest; + point newpoint; + enum insertsiteresult success; + REAL segmentlength, nearestpoweroftwo; + REAL split; + int acuteorg, acutedest; + int dummy; + int i; + triangle ptr; /* Temporary variable used by stpivot(). */ + shelle sptr; /* Temporary variable used by snext(). */ + + while ( ( badsegments.items > 0 ) && ( steinerleft != 0 ) ) { + traversalinit( &badsegments ); + encloop = badsegmenttraverse(); + while ( ( encloop != (struct edge *) NULL ) && ( steinerleft != 0 ) ) { + /* To decide where to split a segment, we need to know if the */ + /* segment shares an endpoint with an adjacent segment. */ + /* The concern is that, if we simply split every encroached */ + /* segment in its center, two adjacent segments with a small */ + /* angle between them might lead to an infinite loop; each */ + /* point added to split one segment will encroach upon the */ + /* other segment, which must then be split with a point that */ + /* will encroach upon the first segment, and so on forever. */ + /* To avoid this, imagine a set of concentric circles, whose */ + /* radii are powers of two, about each segment endpoint. */ + /* These concentric circles determine where the segment is */ + /* split. (If both endpoints are shared with adjacent */ + /* segments, split the segment in the middle, and apply the */ + /* concentric shells for later splittings.) */ + + /* Is the origin shared with another segment? */ + stpivot( *encloop, enctri ); + lnext( enctri, testtri ); + tspivot( testtri, testsh ); + acuteorg = testsh.sh != dummysh; + /* Is the destination shared with another segment? */ + lnextself( testtri ); + tspivot( testtri, testsh ); + acutedest = testsh.sh != dummysh; + /* Now, check the other side of the segment, if there's a triangle */ + /* there. */ + sym( enctri, testtri ); + if ( testtri.tri != dummytri ) { + /* Is the destination shared with another segment? */ + lnextself( testtri ); + tspivot( testtri, testsh ); + acutedest = acutedest || ( testsh.sh != dummysh ); + /* Is the origin shared with another segment? */ + lnextself( testtri ); + tspivot( testtri, testsh ); + acuteorg = acuteorg || ( testsh.sh != dummysh ); + } + + sorg( *encloop, eorg ); + sdest( *encloop, edest ); + /* Use the concentric circles if exactly one endpoint is shared */ + /* with another adjacent segment. */ + if ( acuteorg ^ acutedest ) { + segmentlength = sqrt( ( edest[0] - eorg[0] ) * ( edest[0] - eorg[0] ) + + ( edest[1] - eorg[1] ) * ( edest[1] - eorg[1] ) ); + /* Find the power of two nearest the segment's length. */ + nearestpoweroftwo = 1.0; + while ( segmentlength > SQUAREROOTTWO * nearestpoweroftwo ) { + nearestpoweroftwo *= 2.0; + } + while ( segmentlength < ( 0.5 * SQUAREROOTTWO ) * nearestpoweroftwo ) { + nearestpoweroftwo *= 0.5; + } + /* Where do we split the segment? */ + split = 0.5 * nearestpoweroftwo / segmentlength; + if ( acutedest ) { + split = 1.0 - split; + } + } + else { + /* If we're not worried about adjacent segments, split */ + /* this segment in the middle. */ + split = 0.5; + } + + /* Create the new point. */ + newpoint = (point) poolalloc( &points ); + /* Interpolate its coordinate and attributes. */ + for ( i = 0; i < 2 + nextras; i++ ) { + newpoint[i] = ( 1.0 - split ) * eorg[i] + split * edest[i]; + } + setpointmark( newpoint, mark( *encloop ) ); + if ( verbose > 1 ) { + printf( + " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", + eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1] ); + } + /* Check whether the new point lies on an endpoint. */ + if ( ( ( newpoint[0] == eorg[0] ) && ( newpoint[1] == eorg[1] ) ) + || ( ( newpoint[0] == edest[0] ) && ( newpoint[1] == edest[1] ) ) ) { + printf( "Error: Ran out of precision at (%.12g, %.12g).\n", + newpoint[0], newpoint[1] ); + printf( "I attempted to split a segment to a smaller size than can\n" ); + printf( " be accommodated by the finite precision of floating point\n" + ); + printf( " arithmetic.\n" ); + precisionerror(); + exit( 1 ); + } + /* Insert the splitting point. This should always succeed. */ + success = insertsite( newpoint, &enctri, encloop, flaws, flaws ); + if ( ( success != SUCCESSFULPOINT ) && ( success != ENCROACHINGPOINT ) ) { + printf( "Internal error in repairencs():\n" ); + printf( " Failure to split a segment.\n" ); + internalerror(); + } + if ( steinerleft > 0 ) { + steinerleft--; + } + /* Check the two new subsegments to see if they're encroached. */ + dummy = checkedge4encroach( encloop ); + snextself( *encloop ); + dummy = checkedge4encroach( encloop ); + + badsegmentdealloc( encloop ); + encloop = badsegmenttraverse(); + } + } } #endif /* not CDT_ONLY */ @@ -10812,21 +10934,20 @@ int flaws; #ifndef CDT_ONLY -void tallyfaces() -{ - struct triedge triangleloop; - - if (verbose) { - printf(" Making a list of bad triangles.\n"); - } - traversalinit(&triangles); - triangleloop.orient = 0; - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* If the triangle is bad, enqueue it. */ - testtriangle(&triangleloop); - triangleloop.tri = triangletraverse(); - } +void tallyfaces(){ + struct triedge triangleloop; + + if ( verbose ) { + printf( " Making a list of bad triangles.\n" ); + } + traversalinit( &triangles ); + triangleloop.orient = 0; + triangleloop.tri = triangletraverse(); + while ( triangleloop.tri != (triangle *) NULL ) { + /* If the triangle is bad, enqueue it. */ + testtriangle( &triangleloop ); + triangleloop.tri = triangletraverse(); + } } #endif /* not CDT_ONLY */ @@ -10845,8 +10966,8 @@ void tallyfaces() /* */ /*****************************************************************************/ -enum circumcenterresult findcircumcenter(torg, tdest, tapex, circumcenter, - xi, eta) +enum circumcenterresult findcircumcenter( torg, tdest, tapex, circumcenter, + xi, eta ) point torg; point tdest; point tapex; @@ -10854,53 +10975,56 @@ point circumcenter; REAL *xi; REAL *eta; { - REAL xdo, ydo, xao, yao, xad, yad; - REAL dodist, aodist, addist; - REAL denominator; - REAL dx, dy; - - circumcentercount++; - - /* Compute the circumcenter of the triangle. */ - xdo = tdest[0] - torg[0]; - ydo = tdest[1] - torg[1]; - xao = tapex[0] - torg[0]; - yao = tapex[1] - torg[1]; - dodist = xdo * xdo + ydo * ydo; - aodist = xao * xao + yao * yao; - if (noexact) { - denominator = (REAL)(0.5 / (xdo * yao - xao * ydo)); - } else { - /* Use the counterclockwise() routine to ensure a positive (and */ - /* reasonably accurate) result, avoiding any possibility of */ - /* division by zero. */ - denominator = (REAL)(0.5 / counterclockwise(tdest, tapex, torg)); - /* Don't count the above as an orientation test. */ - counterclockcount--; - } - circumcenter[0] = torg[0] - (ydo * aodist - yao * dodist) * denominator; - circumcenter[1] = torg[1] + (xdo * aodist - xao * dodist) * denominator; - - /* To interpolate point attributes for the new point inserted at */ - /* the circumcenter, define a coordinate system with a xi-axis, */ - /* directed from the triangle's origin to its destination, and */ - /* an eta-axis, directed from its origin to its apex. */ - /* Calculate the xi and eta coordinates of the circumcenter. */ - dx = circumcenter[0] - torg[0]; - dy = circumcenter[1] - torg[1]; - *xi = (REAL)((dx * yao - xao * dy) * (2.0 * denominator)); - *eta = (REAL)((xdo * dy - dx * ydo) * (2.0 * denominator)); - - xad = tapex[0] - tdest[0]; - yad = tapex[1] - tdest[1]; - addist = xad * xad + yad * yad; - if ((addist < dodist) && (addist < aodist)) { - return OPPOSITEORG; - } else if (dodist < aodist) { - return OPPOSITEAPEX; - } else { - return OPPOSITEDEST; - } + REAL xdo, ydo, xao, yao, xad, yad; + REAL dodist, aodist, addist; + REAL denominator; + REAL dx, dy; + + circumcentercount++; + + /* Compute the circumcenter of the triangle. */ + xdo = tdest[0] - torg[0]; + ydo = tdest[1] - torg[1]; + xao = tapex[0] - torg[0]; + yao = tapex[1] - torg[1]; + dodist = xdo * xdo + ydo * ydo; + aodist = xao * xao + yao * yao; + if ( noexact ) { + denominator = (REAL)( 0.5 / ( xdo * yao - xao * ydo ) ); + } + else { + /* Use the counterclockwise() routine to ensure a positive (and */ + /* reasonably accurate) result, avoiding any possibility of */ + /* division by zero. */ + denominator = (REAL)( 0.5 / counterclockwise( tdest, tapex, torg ) ); + /* Don't count the above as an orientation test. */ + counterclockcount--; + } + circumcenter[0] = torg[0] - ( ydo * aodist - yao * dodist ) * denominator; + circumcenter[1] = torg[1] + ( xdo * aodist - xao * dodist ) * denominator; + + /* To interpolate point attributes for the new point inserted at */ + /* the circumcenter, define a coordinate system with a xi-axis, */ + /* directed from the triangle's origin to its destination, and */ + /* an eta-axis, directed from its origin to its apex. */ + /* Calculate the xi and eta coordinates of the circumcenter. */ + dx = circumcenter[0] - torg[0]; + dy = circumcenter[1] - torg[1]; + *xi = (REAL)( ( dx * yao - xao * dy ) * ( 2.0 * denominator ) ); + *eta = (REAL)( ( xdo * dy - dx * ydo ) * ( 2.0 * denominator ) ); + + xad = tapex[0] - tdest[0]; + yad = tapex[1] - tdest[1]; + addist = xad * xad + yad * yad; + if ( ( addist < dodist ) && ( addist < aodist ) ) { + return OPPOSITEORG; + } + else if ( dodist < aodist ) { + return OPPOSITEAPEX; + } + else { + return OPPOSITEDEST; + } } /*****************************************************************************/ @@ -10913,101 +11037,106 @@ REAL *eta; #ifndef CDT_ONLY -void splittriangle(badtri) +void splittriangle( badtri ) struct badface *badtri; { - point borg, bdest, bapex; - point newpoint; - REAL xi, eta; - enum insertsiteresult success; - enum circumcenterresult shortedge; - int errorflag; - int i; - - org(badtri->badfacetri, borg); - dest(badtri->badfacetri, bdest); - apex(badtri->badfacetri, bapex); - /* Make sure that this triangle is still the same triangle it was */ - /* when it was tested and determined to be of bad quality. */ - /* Subsequent transformations may have made it a different triangle. */ - if ((borg == badtri->faceorg) && (bdest == badtri->facedest) && - (bapex == badtri->faceapex)) { - if (verbose > 1) { - printf(" Splitting this triangle at its circumcenter:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0], - borg[1], bdest[0], bdest[1], bapex[0], bapex[1]); - } - errorflag = 0; - /* Create a new point at the triangle's circumcenter. */ - newpoint = (point) poolalloc(&points); - shortedge = findcircumcenter(borg, bdest, bapex, newpoint, &xi, &eta); - /* Check whether the new point lies on a triangle vertex. */ - if (((newpoint[0] == borg[0]) && (newpoint[1] == borg[1])) - || ((newpoint[0] == bdest[0]) && (newpoint[1] == bdest[1])) - || ((newpoint[0] == bapex[0]) && (newpoint[1] == bapex[1]))) { - if (!quiet) { - printf("Warning: New point (%.12g, %.12g) falls on existing vertex.\n" - , newpoint[0], newpoint[1]); - errorflag = 1; - } - pointdealloc(newpoint); - } else { - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - newpoint[i] = borg[i] + xi * (bdest[i] - borg[i]) - + eta * (bapex[i] - borg[i]); - } - /* The new point must be in the interior, and have a marker of zero. */ - setpointmark(newpoint, 0); - /* Ensure that the handle `badtri->badfacetri' represents the shortest */ - /* edge of the triangle. This ensures that the circumcenter must */ - /* fall to the left of this edge, so point location will work. */ - if (shortedge == OPPOSITEORG) { - lnextself(badtri->badfacetri); - } else if (shortedge == OPPOSITEDEST) { - lprevself(badtri->badfacetri); - } - /* Insert the circumcenter, searching from the edge of the triangle, */ - /* and maintain the Delaunay property of the triangulation. */ - success = insertsite(newpoint, &(badtri->badfacetri), - (struct edge *) NULL, 1, 1); - if (success == SUCCESSFULPOINT) { - if (steinerleft > 0) { - steinerleft--; - } - } else if (success == ENCROACHINGPOINT) { - /* If the newly inserted point encroaches upon a segment, delete it. */ - deletesite(&(badtri->badfacetri)); - } else if (success == VIOLATINGPOINT) { - /* Failed to insert the new point, but some segment was */ - /* marked as being encroached. */ - pointdealloc(newpoint); - } else { /* success == DUPLICATEPOINT */ - /* Failed to insert the new point because a vertex is already there. */ - if (!quiet) { - printf( - "Warning: New point (%.12g, %.12g) falls on existing vertex.\n" - , newpoint[0], newpoint[1]); - errorflag = 1; - } - pointdealloc(newpoint); - } - } - if (errorflag) { - if (verbose) { - printf(" The new point is at the circumcenter of triangle\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]); - } - printf("This probably means that I am trying to refine triangles\n"); - printf(" to a smaller size than can be accommodated by the finite\n"); - printf(" precision of floating point arithmetic. (You can be\n"); - printf(" sure of this if I fail to terminate.)\n"); - precisionerror(); - } - } - /* Return the bad triangle to the pool. */ - pooldealloc(&badtriangles, (VOID *) badtri); + point borg, bdest, bapex; + point newpoint; + REAL xi, eta; + enum insertsiteresult success; + enum circumcenterresult shortedge; + int errorflag; + int i; + + org( badtri->badfacetri, borg ); + dest( badtri->badfacetri, bdest ); + apex( badtri->badfacetri, bapex ); + /* Make sure that this triangle is still the same triangle it was */ + /* when it was tested and determined to be of bad quality. */ + /* Subsequent transformations may have made it a different triangle. */ + if ( ( borg == badtri->faceorg ) && ( bdest == badtri->facedest ) && + ( bapex == badtri->faceapex ) ) { + if ( verbose > 1 ) { + printf( " Splitting this triangle at its circumcenter:\n" ); + printf( " (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0], + borg[1], bdest[0], bdest[1], bapex[0], bapex[1] ); + } + errorflag = 0; + /* Create a new point at the triangle's circumcenter. */ + newpoint = (point) poolalloc( &points ); + shortedge = findcircumcenter( borg, bdest, bapex, newpoint, &xi, &eta ); + /* Check whether the new point lies on a triangle vertex. */ + if ( ( ( newpoint[0] == borg[0] ) && ( newpoint[1] == borg[1] ) ) + || ( ( newpoint[0] == bdest[0] ) && ( newpoint[1] == bdest[1] ) ) + || ( ( newpoint[0] == bapex[0] ) && ( newpoint[1] == bapex[1] ) ) ) { + if ( !quiet ) { + printf( "Warning: New point (%.12g, %.12g) falls on existing vertex.\n" + , newpoint[0], newpoint[1] ); + errorflag = 1; + } + pointdealloc( newpoint ); + } + else { + for ( i = 2; i < 2 + nextras; i++ ) { + /* Interpolate the point attributes at the circumcenter. */ + newpoint[i] = borg[i] + xi * ( bdest[i] - borg[i] ) + + eta * ( bapex[i] - borg[i] ); + } + /* The new point must be in the interior, and have a marker of zero. */ + setpointmark( newpoint, 0 ); + /* Ensure that the handle `badtri->badfacetri' represents the shortest */ + /* edge of the triangle. This ensures that the circumcenter must */ + /* fall to the left of this edge, so point location will work. */ + if ( shortedge == OPPOSITEORG ) { + lnextself( badtri->badfacetri ); + } + else if ( shortedge == OPPOSITEDEST ) { + lprevself( badtri->badfacetri ); + } + /* Insert the circumcenter, searching from the edge of the triangle, */ + /* and maintain the Delaunay property of the triangulation. */ + success = insertsite( newpoint, &( badtri->badfacetri ), + (struct edge *) NULL, 1, 1 ); + if ( success == SUCCESSFULPOINT ) { + if ( steinerleft > 0 ) { + steinerleft--; + } + } + else if ( success == ENCROACHINGPOINT ) { + /* If the newly inserted point encroaches upon a segment, delete it. */ + deletesite( &( badtri->badfacetri ) ); + } + else if ( success == VIOLATINGPOINT ) { + /* Failed to insert the new point, but some segment was */ + /* marked as being encroached. */ + pointdealloc( newpoint ); + } + else { /* success == DUPLICATEPOINT */ + /* Failed to insert the new point because a vertex is already there. */ + if ( !quiet ) { + printf( + "Warning: New point (%.12g, %.12g) falls on existing vertex.\n" + , newpoint[0], newpoint[1] ); + errorflag = 1; + } + pointdealloc( newpoint ); + } + } + if ( errorflag ) { + if ( verbose ) { + printf( " The new point is at the circumcenter of triangle\n" ); + printf( " (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", + borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1] ); + } + printf( "This probably means that I am trying to refine triangles\n" ); + printf( " to a smaller size than can be accommodated by the finite\n" ); + printf( " precision of floating point arithmetic. (You can be\n" ); + printf( " sure of this if I fail to terminate.)\n" ); + precisionerror(); + } + } + /* Return the bad triangle to the pool. */ + pooldealloc( &badtriangles, (VOID *) badtri ); } #endif /* not CDT_ONLY */ @@ -11021,81 +11150,81 @@ struct badface *badtri; #ifndef CDT_ONLY -void enforcequality() -{ - int i; - - if (!quiet) { - printf("Adding Steiner points to enforce quality.\n"); - } - /* Initialize the pool of encroached segments. */ - poolinit(&badsegments, sizeof(struct edge), BADSEGMENTPERBLOCK, POINTER, 0); - if (verbose) { - printf(" Looking for encroached segments.\n"); - } - /* Test all segments to see if they're encroached. */ - tallyencs(); - if (verbose && (badsegments.items > 0)) { - printf(" Splitting encroached segments.\n"); - } - /* Note that steinerleft == -1 if an unlimited number */ - /* of Steiner points is allowed. */ - while ((badsegments.items > 0) && (steinerleft != 0)) { - /* Fix the segments without noting newly encroached segments or */ - /* bad triangles. The reason we don't want to note newly */ - /* encroached segments is because some encroached segments are */ - /* likely to be noted multiple times, and would then be blindly */ - /* split multiple times. I should fix that some time. */ - repairencs(0); - /* Now, find all the segments that became encroached while adding */ - /* points to split encroached segments. */ - tallyencs(); - } - /* At this point, if we haven't run out of Steiner points, the */ - /* triangulation should be (conforming) Delaunay. */ - - /* Next, we worry about enforcing triangle quality. */ - if ((minangle > 0.0) || vararea || fixedarea) { - /* Initialize the pool of bad triangles. */ - poolinit(&badtriangles, sizeof(struct badface), BADTRIPERBLOCK, POINTER, - 0); - /* Initialize the queues of bad triangles. */ - for (i = 0; i < 64; i++) { - queuefront[i] = (struct badface *) NULL; - queuetail[i] = &queuefront[i]; - } - /* Test all triangles to see if they're bad. */ - tallyfaces(); - if (verbose) { - printf(" Splitting bad triangles.\n"); - } - while ((badtriangles.items > 0) && (steinerleft != 0)) { - /* Fix one bad triangle by inserting a point at its circumcenter. */ - splittriangle(dequeuebadtri()); - /* Fix any encroached segments that may have resulted. Record */ - /* any new bad triangles or encroached segments that result. */ - if (badsegments.items > 0) { - repairencs(1); - } - } - } - /* At this point, if we haven't run out of Steiner points, the */ - /* triangulation should be (conforming) Delaunay and have no */ - /* low-quality triangles. */ - - /* Might we have run out of Steiner points too soon? */ - if (!quiet && (badsegments.items > 0) && (steinerleft == 0)) { - printf("\nWarning: I ran out of Steiner points, but the mesh has\n"); - if (badsegments.items == 1) { - printf(" an encroached segment, and therefore might not be truly\n"); - } else { - printf(" %ld encroached segments, and therefore might not be truly\n", - badsegments.items); - } - printf(" Delaunay. If the Delaunay property is important to you,\n"); - printf(" try increasing the number of Steiner points (controlled by\n"); - printf(" the -S switch) slightly and try again.\n\n"); - } +void enforcequality(){ + int i; + + if ( !quiet ) { + printf( "Adding Steiner points to enforce quality.\n" ); + } + /* Initialize the pool of encroached segments. */ + poolinit( &badsegments, sizeof( struct edge ), BADSEGMENTPERBLOCK, POINTER, 0 ); + if ( verbose ) { + printf( " Looking for encroached segments.\n" ); + } + /* Test all segments to see if they're encroached. */ + tallyencs(); + if ( verbose && ( badsegments.items > 0 ) ) { + printf( " Splitting encroached segments.\n" ); + } + /* Note that steinerleft == -1 if an unlimited number */ + /* of Steiner points is allowed. */ + while ( ( badsegments.items > 0 ) && ( steinerleft != 0 ) ) { + /* Fix the segments without noting newly encroached segments or */ + /* bad triangles. The reason we don't want to note newly */ + /* encroached segments is because some encroached segments are */ + /* likely to be noted multiple times, and would then be blindly */ + /* split multiple times. I should fix that some time. */ + repairencs( 0 ); + /* Now, find all the segments that became encroached while adding */ + /* points to split encroached segments. */ + tallyencs(); + } + /* At this point, if we haven't run out of Steiner points, the */ + /* triangulation should be (conforming) Delaunay. */ + + /* Next, we worry about enforcing triangle quality. */ + if ( ( minangle > 0.0 ) || vararea || fixedarea ) { + /* Initialize the pool of bad triangles. */ + poolinit( &badtriangles, sizeof( struct badface ), BADTRIPERBLOCK, POINTER, + 0 ); + /* Initialize the queues of bad triangles. */ + for ( i = 0; i < 64; i++ ) { + queuefront[i] = (struct badface *) NULL; + queuetail[i] = &queuefront[i]; + } + /* Test all triangles to see if they're bad. */ + tallyfaces(); + if ( verbose ) { + printf( " Splitting bad triangles.\n" ); + } + while ( ( badtriangles.items > 0 ) && ( steinerleft != 0 ) ) { + /* Fix one bad triangle by inserting a point at its circumcenter. */ + splittriangle( dequeuebadtri() ); + /* Fix any encroached segments that may have resulted. Record */ + /* any new bad triangles or encroached segments that result. */ + if ( badsegments.items > 0 ) { + repairencs( 1 ); + } + } + } + /* At this point, if we haven't run out of Steiner points, the */ + /* triangulation should be (conforming) Delaunay and have no */ + /* low-quality triangles. */ + + /* Might we have run out of Steiner points too soon? */ + if ( !quiet && ( badsegments.items > 0 ) && ( steinerleft == 0 ) ) { + printf( "\nWarning: I ran out of Steiner points, but the mesh has\n" ); + if ( badsegments.items == 1 ) { + printf( " an encroached segment, and therefore might not be truly\n" ); + } + else { + printf( " %ld encroached segments, and therefore might not be truly\n", + badsegments.items ); + } + printf( " Delaunay. If the Delaunay property is important to you,\n" ); + printf( " try increasing the number of Steiner points (controlled by\n" ); + printf( " the -S switch) slightly and try again.\n\n" ); + } } #endif /* not CDT_ONLY */ @@ -11110,70 +11239,69 @@ void enforcequality() /* */ /*****************************************************************************/ -void highorder() -{ - struct triedge triangleloop, trisym; - struct edge checkmark; - point newpoint; - point torg, tdest; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (!quiet) { - printf("Adding vertices for second-order triangles.\n"); - } - /* The following line ensures that dead items in the pool of nodes */ - /* cannot be allocated for the extra nodes associated with high */ - /* order elements. This ensures that the primary nodes (at the */ - /* corners of elements) will occur earlier in the output files, and */ - /* have lower indices, than the extra nodes. */ - points.deaditemstack = (VOID *) NULL; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - org(triangleloop, torg); - dest(triangleloop, tdest); - /* Create a new node in the middle of the edge. Interpolate */ - /* its attributes. */ - newpoint = (point) poolalloc(&points); - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = (REAL)(0.5 * (torg[i] + tdest[i])); - } - /* Set the new node's marker to zero or one, depending on */ - /* whether it lies on a boundary. */ - setpointmark(newpoint, trisym.tri == dummytri); - if (useshelles) { - tspivot(triangleloop, checkmark); - /* If this edge is a segment, transfer the marker to the new node. */ - if (checkmark.sh != dummysh) { - setpointmark(newpoint, mark(checkmark)); - } - } - if (verbose > 1) { - printf(" Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1]); - } - /* Record the new node in the (one or two) adjacent elements. */ - triangleloop.tri[highorderindex + triangleloop.orient] = - (triangle) newpoint; - if (trisym.tri != dummytri) { - trisym.tri[highorderindex + trisym.orient] = (triangle) newpoint; - } - } - } - triangleloop.tri = triangletraverse(); - } +void highorder(){ + struct triedge triangleloop, trisym; + struct edge checkmark; + point newpoint; + point torg, tdest; + int i; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ + + if ( !quiet ) { + printf( "Adding vertices for second-order triangles.\n" ); + } + /* The following line ensures that dead items in the pool of nodes */ + /* cannot be allocated for the extra nodes associated with high */ + /* order elements. This ensures that the primary nodes (at the */ + /* corners of elements) will occur earlier in the output files, and */ + /* have lower indices, than the extra nodes. */ + points.deaditemstack = (VOID *) NULL; + + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + /* To loop over the set of edges, loop over all triangles, and look at */ + /* the three edges of each triangle. If there isn't another triangle */ + /* adjacent to the edge, operate on the edge. If there is another */ + /* adjacent triangle, operate on the edge only if the current triangle */ + /* has a smaller pointer than its neighbor. This way, each edge is */ + /* considered only once. */ + while ( triangleloop.tri != (triangle *) NULL ) { + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + sym( triangleloop, trisym ); + if ( ( triangleloop.tri < trisym.tri ) || ( trisym.tri == dummytri ) ) { + org( triangleloop, torg ); + dest( triangleloop, tdest ); + /* Create a new node in the middle of the edge. Interpolate */ + /* its attributes. */ + newpoint = (point) poolalloc( &points ); + for ( i = 0; i < 2 + nextras; i++ ) { + newpoint[i] = (REAL)( 0.5 * ( torg[i] + tdest[i] ) ); + } + /* Set the new node's marker to zero or one, depending on */ + /* whether it lies on a boundary. */ + setpointmark( newpoint, trisym.tri == dummytri ); + if ( useshelles ) { + tspivot( triangleloop, checkmark ); + /* If this edge is a segment, transfer the marker to the new node. */ + if ( checkmark.sh != dummysh ) { + setpointmark( newpoint, mark( checkmark ) ); + } + } + if ( verbose > 1 ) { + printf( " Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1] ); + } + /* Record the new node in the (one or two) adjacent elements. */ + triangleloop.tri[highorderindex + triangleloop.orient] = + (triangle) newpoint; + if ( trisym.tri != dummytri ) { + trisym.tri[highorderindex + trisym.orient] = (triangle) newpoint; + } + } + } + triangleloop.tri = triangletraverse(); + } } /********* File I/O routines begin here *********/ @@ -11191,30 +11319,30 @@ void highorder() #ifndef TRILIBRARY -char *readline(string, infile, infilename) +char *readline( string, infile, infilename ) char *string; FILE *infile; char *infilename; { - char *result; - - /* Search for something that looks like a number. */ - do { - result = fgets(string, INPUTLINESIZE, infile); - if (result == (char *) NULL) { - printf(" Error: Unexpected end of file in %s.\n", infilename); - exit(1); - } - /* Skip anything that doesn't look like a number, a comment, */ - /* or the end of a line. */ - while ((*result != '\0') && (*result != '#') - && (*result != '.') && (*result != '+') && (*result != '-') - && ((*result < '0') || (*result > '9'))) { - result++; - } - /* If it's a comment or end of line, read another line and try again. */ - } while ((*result == '#') || (*result == '\0')); - return result; + char *result; + + /* Search for something that looks like a number. */ + do { + result = fgets( string, INPUTLINESIZE, infile ); + if ( result == (char *) NULL ) { + printf( " Error: Unexpected end of file in %s.\n", infilename ); + exit( 1 ); + } + /* Skip anything that doesn't look like a number, a comment, */ + /* or the end of a line. */ + while ( ( *result != '\0' ) && ( *result != '#' ) + && ( *result != '.' ) && ( *result != '+' ) && ( *result != '-' ) + && ( ( *result < '0' ) || ( *result > '9' ) ) ) { + result++; + } + /* If it's a comment or end of line, read another line and try again. */ + } while ( ( *result == '#' ) || ( *result == '\0' ) ); + return result; } #endif /* not TRILIBRARY */ @@ -11230,29 +11358,29 @@ char *infilename; #ifndef TRILIBRARY -char *findfield(string) +char *findfield( string ) char *string; { - char *result; - - result = string; - /* Skip the current field. Stop upon reaching whitespace. */ - while ((*result != '\0') && (*result != '#') - && (*result != ' ') && (*result != '\t')) { - result++; - } - /* Now skip the whitespace and anything else that doesn't look like a */ - /* number, a comment, or the end of a line. */ - while ((*result != '\0') && (*result != '#') - && (*result != '.') && (*result != '+') && (*result != '-') - && ((*result < '0') || (*result > '9'))) { - result++; - } - /* Check for a comment (prefixed with `#'). */ - if (*result == '#') { - *result = '\0'; - } - return result; + char *result; + + result = string; + /* Skip the current field. Stop upon reaching whitespace. */ + while ( ( *result != '\0' ) && ( *result != '#' ) + && ( *result != ' ' ) && ( *result != '\t' ) ) { + result++; + } + /* Now skip the whitespace and anything else that doesn't look like a */ + /* number, a comment, or the end of a line. */ + while ( ( *result != '\0' ) && ( *result != '#' ) + && ( *result != '.' ) && ( *result != '+' ) && ( *result != '-' ) + && ( ( *result < '0' ) || ( *result > '9' ) ) ) { + result++; + } + /* Check for a comment (prefixed with `#'). */ + if ( *result == '#' ) { + *result = '\0'; + } + return result; } #endif /* not TRILIBRARY */ @@ -11266,179 +11394,191 @@ char *string; #ifndef TRILIBRARY -void readnodes(nodefilename, polyfilename, polyfile) +void readnodes( nodefilename, polyfilename, polyfile ) char *nodefilename; char *polyfilename; FILE **polyfile; { - FILE *infile; - point pointloop; - char inputline[INPUTLINESIZE]; - char *stringptr; - char *infilename; - REAL x, y; - int firstnode; - int nodemarkers; - int currentmarker; - int i, j; - - if (poly) { - /* Read the points from a .poly file. */ - if (!quiet) { - printf("Opening %s.\n", polyfilename); - } - *polyfile = fopen(polyfilename, "r"); - if (*polyfile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", polyfilename); - exit(1); - } - /* Read number of points, number of dimensions, number of point */ - /* attributes, and number of boundary markers. */ - stringptr = readline(inputline, *polyfile, polyfilename); - inpoints = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - mesh_dim = 2; - } else { - mesh_dim = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nextras = 0; - } else { - nextras = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nodemarkers = 0; - } else { - nodemarkers = (int) strtol (stringptr, &stringptr, 0); - } - if (inpoints > 0) { - infile = *polyfile; - infilename = polyfilename; - readnodefile = 0; - } else { - /* If the .poly file claims there are zero points, that means that */ - /* the points should be read from a separate .node file. */ - readnodefile = 1; - infilename = innodefilename; - } - } else { - readnodefile = 1; - infilename = innodefilename; - *polyfile = (FILE *) NULL; - } - - if (readnodefile) { - /* Read the points from a .node file. */ - if (!quiet) { - printf("Opening %s.\n", innodefilename); - } - infile = fopen(innodefilename, "r"); - if (infile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", innodefilename); - exit(1); - } - /* Read number of points, number of dimensions, number of point */ - /* attributes, and number of boundary markers. */ - stringptr = readline(inputline, infile, innodefilename); - inpoints = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - mesh_dim = 2; - } else { - mesh_dim = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nextras = 0; - } else { - nextras = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nodemarkers = 0; - } else { - nodemarkers = (int) strtol (stringptr, &stringptr, 0); - } - } - - if (inpoints < 3) { - printf("Error: Input must have at least three input points.\n"); - exit(1); - } - if (mesh_dim != 2) { - printf("Error: Triangle only works with two-dimensional meshes.\n"); - exit(1); - } - - initializepointpool(); - - /* Read the points. */ - for (i = 0; i < inpoints; i++) { - pointloop = (point) poolalloc(&points); - stringptr = readline(inputline, infile, infilename); - if (i == 0) { - firstnode = (int) strtol (stringptr, &stringptr, 0); - if ((firstnode == 0) || (firstnode == 1)) { - firstnumber = firstnode; - } - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Point %d has no x coordinate.\n", firstnumber + i); - exit(1); - } - x = (REAL) strtod(stringptr, &stringptr); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Point %d has no y coordinate.\n", firstnumber + i); - exit(1); - } - y = (REAL) strtod(stringptr, &stringptr); - pointloop[0] = x; - pointloop[1] = y; - /* Read the point attributes. */ - for (j = 2; j < 2 + nextras; j++) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - pointloop[j] = 0.0; - } else { - pointloop[j] = (REAL) strtod(stringptr, &stringptr); - } - } - if (nodemarkers) { - /* Read a point marker. */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - setpointmark(pointloop, 0); - } else { - currentmarker = (int) strtol (stringptr, &stringptr, 0); - setpointmark(pointloop, currentmarker); - } - } else { - /* If no markers are specified in the file, they default to zero. */ - setpointmark(pointloop, 0); - } - /* Determine the smallest and largest x and y coordinates. */ - if (i == 0) { - xmin = xmax = x; - ymin = ymax = y; - } else { - xmin = (x < xmin) ? x : xmin; - xmax = (x > xmax) ? x : xmax; - ymin = (y < ymin) ? y : ymin; - ymax = (y > ymax) ? y : ymax; - } - } - if (readnodefile) { - fclose(infile); - } - - /* Nonexistent x value used as a flag to mark circle events in sweepline */ - /* Delaunay algorithm. */ - xminextreme = 10 * xmin - 9 * xmax; + FILE *infile; + point pointloop; + char inputline[INPUTLINESIZE]; + char *stringptr; + char *infilename; + REAL x, y; + int firstnode; + int nodemarkers; + int currentmarker; + int i, j; + + if ( poly ) { + /* Read the points from a .poly file. */ + if ( !quiet ) { + printf( "Opening %s.\n", polyfilename ); + } + *polyfile = fopen( polyfilename, "r" ); + if ( *polyfile == (FILE *) NULL ) { + printf( " Error: Cannot access file %s.\n", polyfilename ); + exit( 1 ); + } + /* Read number of points, number of dimensions, number of point */ + /* attributes, and number of boundary markers. */ + stringptr = readline( inputline, *polyfile, polyfilename ); + inpoints = (int) strtol( stringptr, &stringptr, 0 ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + mesh_dim = 2; + } + else { + mesh_dim = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + nextras = 0; + } + else { + nextras = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + nodemarkers = 0; + } + else { + nodemarkers = (int) strtol( stringptr, &stringptr, 0 ); + } + if ( inpoints > 0 ) { + infile = *polyfile; + infilename = polyfilename; + readnodefile = 0; + } + else { + /* If the .poly file claims there are zero points, that means that */ + /* the points should be read from a separate .node file. */ + readnodefile = 1; + infilename = innodefilename; + } + } + else { + readnodefile = 1; + infilename = innodefilename; + *polyfile = (FILE *) NULL; + } + + if ( readnodefile ) { + /* Read the points from a .node file. */ + if ( !quiet ) { + printf( "Opening %s.\n", innodefilename ); + } + infile = fopen( innodefilename, "r" ); + if ( infile == (FILE *) NULL ) { + printf( " Error: Cannot access file %s.\n", innodefilename ); + exit( 1 ); + } + /* Read number of points, number of dimensions, number of point */ + /* attributes, and number of boundary markers. */ + stringptr = readline( inputline, infile, innodefilename ); + inpoints = (int) strtol( stringptr, &stringptr, 0 ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + mesh_dim = 2; + } + else { + mesh_dim = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + nextras = 0; + } + else { + nextras = (int) strtol( stringptr, &stringptr, 0 ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + nodemarkers = 0; + } + else { + nodemarkers = (int) strtol( stringptr, &stringptr, 0 ); + } + } + + if ( inpoints < 3 ) { + printf( "Error: Input must have at least three input points.\n" ); + exit( 1 ); + } + if ( mesh_dim != 2 ) { + printf( "Error: Triangle only works with two-dimensional meshes.\n" ); + exit( 1 ); + } + + initializepointpool(); + + /* Read the points. */ + for ( i = 0; i < inpoints; i++ ) { + pointloop = (point) poolalloc( &points ); + stringptr = readline( inputline, infile, infilename ); + if ( i == 0 ) { + firstnode = (int) strtol( stringptr, &stringptr, 0 ); + if ( ( firstnode == 0 ) || ( firstnode == 1 ) ) { + firstnumber = firstnode; + } + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Point %d has no x coordinate.\n", firstnumber + i ); + exit( 1 ); + } + x = (REAL) strtod( stringptr, &stringptr ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Point %d has no y coordinate.\n", firstnumber + i ); + exit( 1 ); + } + y = (REAL) strtod( stringptr, &stringptr ); + pointloop[0] = x; + pointloop[1] = y; + /* Read the point attributes. */ + for ( j = 2; j < 2 + nextras; j++ ) { + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + pointloop[j] = 0.0; + } + else { + pointloop[j] = (REAL) strtod( stringptr, &stringptr ); + } + } + if ( nodemarkers ) { + /* Read a point marker. */ + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + setpointmark( pointloop, 0 ); + } + else { + currentmarker = (int) strtol( stringptr, &stringptr, 0 ); + setpointmark( pointloop, currentmarker ); + } + } + else { + /* If no markers are specified in the file, they default to zero. */ + setpointmark( pointloop, 0 ); + } + /* Determine the smallest and largest x and y coordinates. */ + if ( i == 0 ) { + xmin = xmax = x; + ymin = ymax = y; + } + else { + xmin = ( x < xmin ) ? x : xmin; + xmax = ( x > xmax ) ? x : xmax; + ymin = ( y < ymin ) ? y : ymin; + ymax = ( y > ymax ) ? y : ymax; + } + } + if ( readnodefile ) { + fclose( infile ); + } + + /* Nonexistent x value used as a flag to mark circle events in sweepline */ + /* Delaunay algorithm. */ + xminextreme = 10 * xmin - 9 * xmax; } #endif /* not TRILIBRARY */ @@ -11451,67 +11591,69 @@ FILE **polyfile; #ifdef TRILIBRARY -void transfernodes(pointlist, pointattriblist, pointmarkerlist, numberofpoints, - numberofpointattribs) -REAL *pointlist; +void transfernodes( pointlist, pointattriblist, pointmarkerlist, numberofpoints, + numberofpointattribs ) +REAL * pointlist; REAL *pointattriblist; int *pointmarkerlist; int numberofpoints; int numberofpointattribs; { - point pointloop; - REAL x, y; - int i, j; - int coordindex; - int attribindex; - - inpoints = numberofpoints; - mesh_dim = 2; - nextras = numberofpointattribs; - readnodefile = 0; - if (inpoints < 3) { - printf("Error: Input must have at least three input points.\n"); - exit(1); - } - - initializepointpool(); - - /* Read the points. */ - coordindex = 0; - attribindex = 0; - for (i = 0; i < inpoints; i++) { - pointloop = (point) poolalloc(&points); - /* Read the point coordinates. */ - x = pointloop[0] = pointlist[coordindex++]; - y = pointloop[1] = pointlist[coordindex++]; - /* Read the point attributes. */ - for (j = 0; j < numberofpointattribs; j++) { - pointloop[2 + j] = pointattriblist[attribindex++]; - } - if (pointmarkerlist != (int *) NULL) { - /* Read a point marker. */ - setpointmark(pointloop, pointmarkerlist[i]); - } else { - /* If no markers are specified, they default to zero. */ - setpointmark(pointloop, 0); - } - x = pointloop[0]; - y = pointloop[1]; - /* Determine the smallest and largest x and y coordinates. */ - if (i == 0) { - xmin = xmax = x; - ymin = ymax = y; - } else { - xmin = (x < xmin) ? x : xmin; - xmax = (x > xmax) ? x : xmax; - ymin = (y < ymin) ? y : ymin; - ymax = (y > ymax) ? y : ymax; - } - } - - /* Nonexistent x value used as a flag to mark circle events in sweepline */ - /* Delaunay algorithm. */ - xminextreme = 10 * xmin - 9 * xmax; + point pointloop; + REAL x, y; + int i, j; + int coordindex; + int attribindex; + + inpoints = numberofpoints; + mesh_dim = 2; + nextras = numberofpointattribs; + readnodefile = 0; + if ( inpoints < 3 ) { + printf( "Error: Input must have at least three input points.\n" ); + exit( 1 ); + } + + initializepointpool(); + + /* Read the points. */ + coordindex = 0; + attribindex = 0; + for ( i = 0; i < inpoints; i++ ) { + pointloop = (point) poolalloc( &points ); + /* Read the point coordinates. */ + x = pointloop[0] = pointlist[coordindex++]; + y = pointloop[1] = pointlist[coordindex++]; + /* Read the point attributes. */ + for ( j = 0; j < numberofpointattribs; j++ ) { + pointloop[2 + j] = pointattriblist[attribindex++]; + } + if ( pointmarkerlist != (int *) NULL ) { + /* Read a point marker. */ + setpointmark( pointloop, pointmarkerlist[i] ); + } + else { + /* If no markers are specified, they default to zero. */ + setpointmark( pointloop, 0 ); + } + x = pointloop[0]; + y = pointloop[1]; + /* Determine the smallest and largest x and y coordinates. */ + if ( i == 0 ) { + xmin = xmax = x; + ymin = ymax = y; + } + else { + xmin = ( x < xmin ) ? x : xmin; + xmax = ( x > xmax ) ? x : xmax; + ymin = ( y < ymin ) ? y : ymin; + ymax = ( y > ymax ) ? y : ymax; + } + } + + /* Nonexistent x value used as a flag to mark circle events in sweepline */ + /* Delaunay algorithm. */ + xminextreme = 10 * xmin - 9 * xmax; } #endif /* TRILIBRARY */ @@ -11525,111 +11667,119 @@ int numberofpointattribs; #ifndef TRILIBRARY -void readholes(polyfile, polyfilename, hlist, holes, rlist, regions) -FILE *polyfile; +void readholes( polyfile, polyfilename, hlist, holes, rlist, regions ) +FILE * polyfile; char *polyfilename; REAL **hlist; int *holes; REAL **rlist; int *regions; { - REAL *holelist; - REAL *regionlist; - char inputline[INPUTLINESIZE]; - char *stringptr; - int index; - int i; - - /* Read the holes. */ - stringptr = readline(inputline, polyfile, polyfilename); - *holes = (int) strtol (stringptr, &stringptr, 0); - if (*holes > 0) { - holelist = (REAL *) malloc(2 * *holes * sizeof(REAL)); - *hlist = holelist; - if (holelist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - for (i = 0; i < 2 * *holes; i += 2) { - stringptr = readline(inputline, polyfile, polyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Hole %d has no x coordinate.\n", - firstnumber + (i >> 1)); - exit(1); - } else { - holelist[i] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Hole %d has no y coordinate.\n", - firstnumber + (i >> 1)); - exit(1); - } else { - holelist[i + 1] = (REAL) strtod(stringptr, &stringptr); - } - } - } else { - *hlist = (REAL *) NULL; - } + REAL *holelist; + REAL *regionlist; + char inputline[INPUTLINESIZE]; + char *stringptr; + int index; + int i; + + /* Read the holes. */ + stringptr = readline( inputline, polyfile, polyfilename ); + *holes = (int) strtol( stringptr, &stringptr, 0 ); + if ( *holes > 0 ) { + holelist = (REAL *) malloc( 2 * *holes * sizeof( REAL ) ); + *hlist = holelist; + if ( holelist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + for ( i = 0; i < 2 * *holes; i += 2 ) { + stringptr = readline( inputline, polyfile, polyfilename ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Hole %d has no x coordinate.\n", + firstnumber + ( i >> 1 ) ); + exit( 1 ); + } + else { + holelist[i] = (REAL) strtod( stringptr, &stringptr ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Hole %d has no y coordinate.\n", + firstnumber + ( i >> 1 ) ); + exit( 1 ); + } + else { + holelist[i + 1] = (REAL) strtod( stringptr, &stringptr ); + } + } + } + else { + *hlist = (REAL *) NULL; + } #ifndef CDT_ONLY - if ((regionattrib || vararea) && !refine) { - /* Read the area constraints. */ - stringptr = readline(inputline, polyfile, polyfilename); - *regions = (int) strtol (stringptr, &stringptr, 0); - if (*regions > 0) { - regionlist = (REAL *) malloc(4 * *regions * sizeof(REAL)); - *rlist = regionlist; - if (regionlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - index = 0; - for (i = 0; i < *regions; i++) { - stringptr = readline(inputline, polyfile, polyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Region %d has no x coordinate.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Region %d has no y coordinate.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf( - "Error: Region %d has no region attribute or area constraint.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - regionlist[index] = regionlist[index - 1]; - } else { - regionlist[index] = (REAL) strtod(stringptr, &stringptr); - } - index++; - } - } - } else { - /* Set `*regions' to zero to avoid an accidental free() later. */ - *regions = 0; - *rlist = (REAL *) NULL; - } + if ( ( regionattrib || vararea ) && !refine ) { + /* Read the area constraints. */ + stringptr = readline( inputline, polyfile, polyfilename ); + *regions = (int) strtol( stringptr, &stringptr, 0 ); + if ( *regions > 0 ) { + regionlist = (REAL *) malloc( 4 * *regions * sizeof( REAL ) ); + *rlist = regionlist; + if ( regionlist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + index = 0; + for ( i = 0; i < *regions; i++ ) { + stringptr = readline( inputline, polyfile, polyfilename ); + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Region %d has no x coordinate.\n", + firstnumber + i ); + exit( 1 ); + } + else { + regionlist[index++] = (REAL) strtod( stringptr, &stringptr ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( "Error: Region %d has no y coordinate.\n", + firstnumber + i ); + exit( 1 ); + } + else { + regionlist[index++] = (REAL) strtod( stringptr, &stringptr ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + printf( + "Error: Region %d has no region attribute or area constraint.\n", + firstnumber + i ); + exit( 1 ); + } + else { + regionlist[index++] = (REAL) strtod( stringptr, &stringptr ); + } + stringptr = findfield( stringptr ); + if ( *stringptr == '\0' ) { + regionlist[index] = regionlist[index - 1]; + } + else { + regionlist[index] = (REAL) strtod( stringptr, &stringptr ); + } + index++; + } + } + } + else { + /* Set `*regions' to zero to avoid an accidental free() later. */ + *regions = 0; + *rlist = (REAL *) NULL; + } #endif /* not CDT_ONLY */ - fclose(polyfile); + fclose( polyfile ); } #endif /* not TRILIBRARY */ @@ -11643,20 +11793,20 @@ int *regions; #ifndef TRILIBRARY -void finishfile(outfile, argc, argv) -FILE *outfile; +void finishfile( outfile, argc, argv ) +FILE * outfile; int argc; char **argv; { - int i; - - fprintf(outfile, "# Generated by"); - for (i = 0; i < argc; i++) { - fprintf(outfile, " "); - fputs(argv[i], outfile); - } - fprintf(outfile, "\n"); - fclose(outfile); + int i; + + fprintf( outfile, "# Generated by" ); + for ( i = 0; i < argc; i++ ) { + fprintf( outfile, " " ); + fputs( argv[i], outfile ); + } + fprintf( outfile, "\n" ); + fclose( outfile ); } #endif /* not TRILIBRARY */ @@ -11672,14 +11822,14 @@ char **argv; #ifdef TRILIBRARY -void writenodes(pointlist, pointattriblist, pointmarkerlist) -REAL **pointlist; +void writenodes( pointlist, pointattriblist, pointmarkerlist ) +REAL * *pointlist; REAL **pointattriblist; int **pointmarkerlist; #else /* not TRILIBRARY */ -void writenodes(nodefilename, argc, argv) +void writenodes( nodefilename, argc, argv ) char *nodefilename; int argc; char **argv; @@ -11688,105 +11838,106 @@ char **argv; { #ifdef TRILIBRARY - REAL *plist; - REAL *palist; - int *pmlist; - int coordindex; - int attribindex; + REAL *plist; + REAL *palist; + int *pmlist; + int coordindex; + int attribindex; #else /* not TRILIBRARY */ - FILE *outfile; + FILE *outfile; #endif /* not TRILIBRARY */ - point pointloop; - int pointnumber; - int i; + point pointloop; + int pointnumber; + int i; #ifdef TRILIBRARY - if (!quiet) { - printf("Writing points.\n"); - } - /* Allocate memory for output points if necessary. */ - if (*pointlist == (REAL *) NULL) { - *pointlist = (REAL *) malloc(points.items * 2 * sizeof(REAL)); - if (*pointlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output point attributes if necessary. */ - if ((nextras > 0) && (*pointattriblist == (REAL *) NULL)) { - *pointattriblist = (REAL *) malloc(points.items * nextras * sizeof(REAL)); - if (*pointattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output point markers if necessary. */ - if (!nobound && (*pointmarkerlist == (int *) NULL)) { - *pointmarkerlist = (int *) malloc(points.items * sizeof(int)); - if (*pointmarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - plist = *pointlist; - palist = *pointattriblist; - pmlist = *pointmarkerlist; - coordindex = 0; - attribindex = 0; + if ( !quiet ) { + printf( "Writing points.\n" ); + } + /* Allocate memory for output points if necessary. */ + if ( *pointlist == (REAL *) NULL ) { + *pointlist = (REAL *) malloc( points.items * 2 * sizeof( REAL ) ); + if ( *pointlist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for output point attributes if necessary. */ + if ( ( nextras > 0 ) && ( *pointattriblist == (REAL *) NULL ) ) { + *pointattriblist = (REAL *) malloc( points.items * nextras * sizeof( REAL ) ); + if ( *pointattriblist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for output point markers if necessary. */ + if ( !nobound && ( *pointmarkerlist == (int *) NULL ) ) { + *pointmarkerlist = (int *) malloc( points.items * sizeof( int ) ); + if ( *pointmarkerlist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + plist = *pointlist; + palist = *pointattriblist; + pmlist = *pointmarkerlist; + coordindex = 0; + attribindex = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", nodefilename); - } - outfile = fopen(nodefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", nodefilename); - exit(1); - } - /* Number of points, number of dimensions, number of point attributes, */ - /* and number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d %d %d\n", points.items, mesh_dim, nextras, - 1 - nobound); + if ( !quiet ) { + printf( "Writing %s.\n", nodefilename ); + } + outfile = fopen( nodefilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", nodefilename ); + exit( 1 ); + } + /* Number of points, number of dimensions, number of point attributes, */ + /* and number of boundary markers (zero or one). */ + fprintf( outfile, "%ld %d %d %d\n", points.items, mesh_dim, nextras, + 1 - nobound ); #endif /* not TRILIBRARY */ - traversalinit(&points); - pointloop = pointtraverse(); - pointnumber = firstnumber; - while (pointloop != (point) NULL) { + traversalinit( &points ); + pointloop = pointtraverse(); + pointnumber = firstnumber; + while ( pointloop != (point) NULL ) { #ifdef TRILIBRARY - /* X and y coordinates. */ - plist[coordindex++] = pointloop[0]; - plist[coordindex++] = pointloop[1]; - /* Point attributes. */ - for (i = 0; i < nextras; i++) { - palist[attribindex++] = pointloop[2 + i]; - } - if (!nobound) { - /* Copy the boundary marker. */ - pmlist[pointnumber - firstnumber] = pointmark(pointloop); - } + /* X and y coordinates. */ + plist[coordindex++] = pointloop[0]; + plist[coordindex++] = pointloop[1]; + /* Point attributes. */ + for ( i = 0; i < nextras; i++ ) { + palist[attribindex++] = pointloop[2 + i]; + } + if ( !nobound ) { + /* Copy the boundary marker. */ + pmlist[pointnumber - firstnumber] = pointmark( pointloop ); + } #else /* not TRILIBRARY */ - /* Point number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g", pointnumber, pointloop[0], - pointloop[1]); - for (i = 0; i < nextras; i++) { - /* Write an attribute. */ - fprintf(outfile, " %.17g", pointloop[i + 2]); - } - if (nobound) { - fprintf(outfile, "\n"); - } else { - /* Write the boundary marker. */ - fprintf(outfile, " %d\n", pointmark(pointloop)); - } + /* Point number, x and y coordinates. */ + fprintf( outfile, "%4d %.17g %.17g", pointnumber, pointloop[0], + pointloop[1] ); + for ( i = 0; i < nextras; i++ ) { + /* Write an attribute. */ + fprintf( outfile, " %.17g", pointloop[i + 2] ); + } + if ( nobound ) { + fprintf( outfile, "\n" ); + } + else { + /* Write the boundary marker. */ + fprintf( outfile, " %d\n", pointmark( pointloop ) ); + } #endif /* not TRILIBRARY */ - setpointmark(pointloop, pointnumber); - pointloop = pointtraverse(); - pointnumber++; - } + setpointmark( pointloop, pointnumber ); + pointloop = pointtraverse(); + pointnumber++; + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ } @@ -11800,19 +11951,18 @@ char **argv; /* */ /*****************************************************************************/ -void numbernodes() -{ - point pointloop; - int pointnumber; - - traversalinit(&points); - pointloop = pointtraverse(); - pointnumber = firstnumber; - while (pointloop != (point) NULL) { - setpointmark(pointloop, pointnumber); - pointloop = pointtraverse(); - pointnumber++; - } +void numbernodes(){ + point pointloop; + int pointnumber; + + traversalinit( &points ); + pointloop = pointtraverse(); + pointnumber = firstnumber; + while ( pointloop != (point) NULL ) { + setpointmark( pointloop, pointnumber ); + pointloop = pointtraverse(); + pointnumber++; + } } /*****************************************************************************/ @@ -11823,13 +11973,13 @@ void numbernodes() #ifdef TRILIBRARY -void writeelements(trianglelist, triangleattriblist) +void writeelements( trianglelist, triangleattriblist ) int **trianglelist; REAL **triangleattriblist; #else /* not TRILIBRARY */ -void writeelements(elefilename, argc, argv) +void writeelements( elefilename, argc, argv ) char *elefilename; int argc; char **argv; @@ -11838,113 +11988,114 @@ char **argv; { #ifdef TRILIBRARY - int *tlist; - REAL *talist; - int pointindex; - int attribindex; + int *tlist; + REAL *talist; + int pointindex; + int attribindex; #else /* not TRILIBRARY */ - FILE *outfile; + FILE *outfile; #endif /* not TRILIBRARY */ - struct triedge triangleloop; - point p1, p2, p3; - point mid1, mid2, mid3; - int elementnumber; - int i; + struct triedge triangleloop; + point p1, p2, p3; + point mid1, mid2, mid3; + int elementnumber; + int i; #ifdef TRILIBRARY - if (!quiet) { - printf("Writing triangles.\n"); - } - /* Allocate memory for output triangles if necessary. */ - if (*trianglelist == (int *) NULL) { - *trianglelist = (int *) malloc(triangles.items * - ((order + 1) * (order + 2) / 2) * sizeof(int)); - if (*trianglelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output triangle attributes if necessary. */ - if ((eextras > 0) && (*triangleattriblist == (REAL *) NULL)) { - *triangleattriblist = (REAL *) malloc(triangles.items * eextras * - sizeof(REAL)); - if (*triangleattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - tlist = *trianglelist; - talist = *triangleattriblist; - pointindex = 0; - attribindex = 0; + if ( !quiet ) { + printf( "Writing triangles.\n" ); + } + /* Allocate memory for output triangles if necessary. */ + if ( *trianglelist == (int *) NULL ) { + *trianglelist = (int *) malloc( triangles.items * + ( ( order + 1 ) * ( order + 2 ) / 2 ) * sizeof( int ) ); + if ( *trianglelist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for output triangle attributes if necessary. */ + if ( ( eextras > 0 ) && ( *triangleattriblist == (REAL *) NULL ) ) { + *triangleattriblist = (REAL *) malloc( triangles.items * eextras * + sizeof( REAL ) ); + if ( *triangleattriblist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + tlist = *trianglelist; + talist = *triangleattriblist; + pointindex = 0; + attribindex = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", elefilename); - } - outfile = fopen(elefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", elefilename); - exit(1); - } - /* Number of triangles, points per triangle, attributes per triangle. */ - fprintf(outfile, "%ld %d %d\n", triangles.items, - (order + 1) * (order + 2) / 2, eextras); + if ( !quiet ) { + printf( "Writing %s.\n", elefilename ); + } + outfile = fopen( elefilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", elefilename ); + exit( 1 ); + } + /* Number of triangles, points per triangle, attributes per triangle. */ + fprintf( outfile, "%ld %d %d\n", triangles.items, + ( order + 1 ) * ( order + 2 ) / 2, eextras ); #endif /* not TRILIBRARY */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p1); - dest(triangleloop, p2); - apex(triangleloop, p3); - if (order == 1) { + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + triangleloop.orient = 0; + elementnumber = firstnumber; + while ( triangleloop.tri != (triangle *) NULL ) { + org( triangleloop, p1 ); + dest( triangleloop, p2 ); + apex( triangleloop, p3 ); + if ( order == 1 ) { #ifdef TRILIBRARY - tlist[pointindex++] = pointmark(p1); - tlist[pointindex++] = pointmark(p2); - tlist[pointindex++] = pointmark(p3); + tlist[pointindex++] = pointmark( p1 ); + tlist[pointindex++] = pointmark( p2 ); + tlist[pointindex++] = pointmark( p3 ); #else /* not TRILIBRARY */ - /* Triangle number, indices for three points. */ - fprintf(outfile, "%4d %4d %4d %4d", elementnumber, - pointmark(p1), pointmark(p2), pointmark(p3)); + /* Triangle number, indices for three points. */ + fprintf( outfile, "%4d %4d %4d %4d", elementnumber, + pointmark( p1 ), pointmark( p2 ), pointmark( p3 ) ); #endif /* not TRILIBRARY */ - } else { - mid1 = (point) triangleloop.tri[highorderindex + 1]; - mid2 = (point) triangleloop.tri[highorderindex + 2]; - mid3 = (point) triangleloop.tri[highorderindex]; + } + else { + mid1 = (point) triangleloop.tri[highorderindex + 1]; + mid2 = (point) triangleloop.tri[highorderindex + 2]; + mid3 = (point) triangleloop.tri[highorderindex]; #ifdef TRILIBRARY - tlist[pointindex++] = pointmark(p1); - tlist[pointindex++] = pointmark(p2); - tlist[pointindex++] = pointmark(p3); - tlist[pointindex++] = pointmark(mid1); - tlist[pointindex++] = pointmark(mid2); - tlist[pointindex++] = pointmark(mid3); + tlist[pointindex++] = pointmark( p1 ); + tlist[pointindex++] = pointmark( p2 ); + tlist[pointindex++] = pointmark( p3 ); + tlist[pointindex++] = pointmark( mid1 ); + tlist[pointindex++] = pointmark( mid2 ); + tlist[pointindex++] = pointmark( mid3 ); #else /* not TRILIBRARY */ - /* Triangle number, indices for six points. */ - fprintf(outfile, "%4d %4d %4d %4d %4d %4d %4d", elementnumber, - pointmark(p1), pointmark(p2), pointmark(p3), pointmark(mid1), - pointmark(mid2), pointmark(mid3)); + /* Triangle number, indices for six points. */ + fprintf( outfile, "%4d %4d %4d %4d %4d %4d %4d", elementnumber, + pointmark( p1 ), pointmark( p2 ), pointmark( p3 ), pointmark( mid1 ), + pointmark( mid2 ), pointmark( mid3 ) ); #endif /* not TRILIBRARY */ - } + } #ifdef TRILIBRARY - for (i = 0; i < eextras; i++) { - talist[attribindex++] = elemattribute(triangleloop, i); - } + for ( i = 0; i < eextras; i++ ) { + talist[attribindex++] = elemattribute( triangleloop, i ); + } #else /* not TRILIBRARY */ - for (i = 0; i < eextras; i++) { - fprintf(outfile, " %.17g", elemattribute(triangleloop, i)); - } - fprintf(outfile, "\n"); + for ( i = 0; i < eextras; i++ ) { + fprintf( outfile, " %.17g", elemattribute( triangleloop, i ) ); + } + fprintf( outfile, "\n" ); #endif /* not TRILIBRARY */ - triangleloop.tri = triangletraverse(); - elementnumber++; - } + triangleloop.tri = triangletraverse(); + elementnumber++; + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ } @@ -11956,13 +12107,13 @@ char **argv; #ifdef TRILIBRARY -void writepoly(segmentlist, segmentmarkerlist) +void writepoly( segmentlist, segmentmarkerlist ) int **segmentlist; int **segmentmarkerlist; #else /* not TRILIBRARY */ -void writepoly(polyfilename, holelist, holes, regionlist, regions, argc, argv) +void writepoly( polyfilename, holelist, holes, regionlist, regions, argc, argv ) char *polyfilename; REAL *holelist; int holes; @@ -11975,109 +12126,110 @@ char **argv; { #ifdef TRILIBRARY - int *slist; - int *smlist; - int index; + int *slist; + int *smlist; + int index; #else /* not TRILIBRARY */ - FILE *outfile; - int i; + FILE *outfile; + int i; #endif /* not TRILIBRARY */ - struct edge shelleloop; - point endpoint1, endpoint2; - int shellenumber; + struct edge shelleloop; + point endpoint1, endpoint2; + int shellenumber; #ifdef TRILIBRARY - if (!quiet) { - printf("Writing segments.\n"); - } - /* Allocate memory for output segments if necessary. */ - if (*segmentlist == (int *) NULL) { - *segmentlist = (int *) malloc(shelles.items * 2 * sizeof(int)); - if (*segmentlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output segment markers if necessary. */ - if (!nobound && (*segmentmarkerlist == (int *) NULL)) { - *segmentmarkerlist = (int *) malloc(shelles.items * sizeof(int)); - if (*segmentmarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - slist = *segmentlist; - smlist = *segmentmarkerlist; - index = 0; + if ( !quiet ) { + printf( "Writing segments.\n" ); + } + /* Allocate memory for output segments if necessary. */ + if ( *segmentlist == (int *) NULL ) { + *segmentlist = (int *) malloc( shelles.items * 2 * sizeof( int ) ); + if ( *segmentlist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for output segment markers if necessary. */ + if ( !nobound && ( *segmentmarkerlist == (int *) NULL ) ) { + *segmentmarkerlist = (int *) malloc( shelles.items * sizeof( int ) ); + if ( *segmentmarkerlist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + slist = *segmentlist; + smlist = *segmentmarkerlist; + index = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", polyfilename); - } - outfile = fopen(polyfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", polyfilename); - exit(1); - } - /* The zero indicates that the points are in a separate .node file. */ - /* Followed by number of dimensions, number of point attributes, */ - /* and number of boundary markers (zero or one). */ - fprintf(outfile, "%d %d %d %d\n", 0, mesh_dim, nextras, 1 - nobound); - /* Number of segments, number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d\n", shelles.items, 1 - nobound); + if ( !quiet ) { + printf( "Writing %s.\n", polyfilename ); + } + outfile = fopen( polyfilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", polyfilename ); + exit( 1 ); + } + /* The zero indicates that the points are in a separate .node file. */ + /* Followed by number of dimensions, number of point attributes, */ + /* and number of boundary markers (zero or one). */ + fprintf( outfile, "%d %d %d %d\n", 0, mesh_dim, nextras, 1 - nobound ); + /* Number of segments, number of boundary markers (zero or one). */ + fprintf( outfile, "%ld %d\n", shelles.items, 1 - nobound ); #endif /* not TRILIBRARY */ - traversalinit(&shelles); - shelleloop.sh = shelletraverse(); - shelleloop.shorient = 0; - shellenumber = firstnumber; - while (shelleloop.sh != (shelle *) NULL) { - sorg(shelleloop, endpoint1); - sdest(shelleloop, endpoint2); + traversalinit( &shelles ); + shelleloop.sh = shelletraverse(); + shelleloop.shorient = 0; + shellenumber = firstnumber; + while ( shelleloop.sh != (shelle *) NULL ) { + sorg( shelleloop, endpoint1 ); + sdest( shelleloop, endpoint2 ); #ifdef TRILIBRARY - /* Copy indices of the segment's two endpoints. */ - slist[index++] = pointmark(endpoint1); - slist[index++] = pointmark(endpoint2); - if (!nobound) { - /* Copy the boundary marker. */ - smlist[shellenumber - firstnumber] = mark(shelleloop); - } + /* Copy indices of the segment's two endpoints. */ + slist[index++] = pointmark( endpoint1 ); + slist[index++] = pointmark( endpoint2 ); + if ( !nobound ) { + /* Copy the boundary marker. */ + smlist[shellenumber - firstnumber] = mark( shelleloop ); + } #else /* not TRILIBRARY */ - /* Segment number, indices of its two endpoints, and possibly a marker. */ - if (nobound) { - fprintf(outfile, "%4d %4d %4d\n", shellenumber, - pointmark(endpoint1), pointmark(endpoint2)); - } else { - fprintf(outfile, "%4d %4d %4d %4d\n", shellenumber, - pointmark(endpoint1), pointmark(endpoint2), mark(shelleloop)); - } + /* Segment number, indices of its two endpoints, and possibly a marker. */ + if ( nobound ) { + fprintf( outfile, "%4d %4d %4d\n", shellenumber, + pointmark( endpoint1 ), pointmark( endpoint2 ) ); + } + else { + fprintf( outfile, "%4d %4d %4d %4d\n", shellenumber, + pointmark( endpoint1 ), pointmark( endpoint2 ), mark( shelleloop ) ); + } #endif /* not TRILIBRARY */ - shelleloop.sh = shelletraverse(); - shellenumber++; - } + shelleloop.sh = shelletraverse(); + shellenumber++; + } #ifndef TRILIBRARY #ifndef CDT_ONLY - fprintf(outfile, "%d\n", holes); - if (holes > 0) { - for (i = 0; i < holes; i++) { - /* Hole number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g\n", firstnumber + i, - holelist[2 * i], holelist[2 * i + 1]); - } - } - if (regions > 0) { - fprintf(outfile, "%d\n", regions); - for (i = 0; i < regions; i++) { - /* Region number, x and y coordinates, attribute, maximum area. */ - fprintf(outfile, "%4d %.17g %.17g %.17g %.17g\n", firstnumber + i, - regionlist[4 * i], regionlist[4 * i + 1], - regionlist[4 * i + 2], regionlist[4 * i + 3]); - } - } + fprintf( outfile, "%d\n", holes ); + if ( holes > 0 ) { + for ( i = 0; i < holes; i++ ) { + /* Hole number, x and y coordinates. */ + fprintf( outfile, "%4d %.17g %.17g\n", firstnumber + i, + holelist[2 * i], holelist[2 * i + 1] ); + } + } + if ( regions > 0 ) { + fprintf( outfile, "%d\n", regions ); + for ( i = 0; i < regions; i++ ) { + /* Region number, x and y coordinates, attribute, maximum area. */ + fprintf( outfile, "%4d %.17g %.17g %.17g %.17g\n", firstnumber + i, + regionlist[4 * i], regionlist[4 * i + 1], + regionlist[4 * i + 2], regionlist[4 * i + 3] ); + } + } #endif /* not CDT_ONLY */ - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ } @@ -12089,13 +12241,13 @@ char **argv; #ifdef TRILIBRARY -void writeedges(edgelist, edgemarkerlist) +void writeedges( edgelist, edgemarkerlist ) int **edgelist; int **edgemarkerlist; #else /* not TRILIBRARY */ -void writeedges(edgefilename, argc, argv) +void writeedges( edgefilename, argc, argv ) char *edgefilename; int argc; char **argv; @@ -12104,118 +12256,121 @@ char **argv; { #ifdef TRILIBRARY - int *elist; - int *emlist; - int index; + int *elist; + int *emlist; + int index; #else /* not TRILIBRARY */ - FILE *outfile; + FILE *outfile; #endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - struct edge checkmark; - point p1, p2; - int edgenumber; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ + struct triedge triangleloop, trisym; + struct edge checkmark; + point p1, p2; + int edgenumber; + triangle ptr; /* Temporary variable used by sym(). */ + shelle sptr; /* Temporary variable used by tspivot(). */ #ifdef TRILIBRARY - if (!quiet) { - printf("Writing edges.\n"); - } - /* Allocate memory for edges if necessary. */ - if (*edgelist == (int *) NULL) { - *edgelist = (int *) malloc(edges * 2 * sizeof(int)); - if (*edgelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for edge markers if necessary. */ - if (!nobound && (*edgemarkerlist == (int *) NULL)) { - *edgemarkerlist = (int *) malloc(edges * sizeof(int)); - if (*edgemarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - elist = *edgelist; - emlist = *edgemarkerlist; - index = 0; + if ( !quiet ) { + printf( "Writing edges.\n" ); + } + /* Allocate memory for edges if necessary. */ + if ( *edgelist == (int *) NULL ) { + *edgelist = (int *) malloc( edges * 2 * sizeof( int ) ); + if ( *edgelist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for edge markers if necessary. */ + if ( !nobound && ( *edgemarkerlist == (int *) NULL ) ) { + *edgemarkerlist = (int *) malloc( edges * sizeof( int ) ); + if ( *edgemarkerlist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + elist = *edgelist; + emlist = *edgemarkerlist; + index = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", edgefilename); - } - outfile = fopen(edgefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", edgefilename); - exit(1); - } - /* Number of edges, number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d\n", edges, 1 - nobound); + if ( !quiet ) { + printf( "Writing %s.\n", edgefilename ); + } + outfile = fopen( edgefilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", edgefilename ); + exit( 1 ); + } + /* Number of edges, number of boundary markers (zero or one). */ + fprintf( outfile, "%ld %d\n", edges, 1 - nobound ); #endif /* not TRILIBRARY */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - edgenumber = firstnumber; - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - org(triangleloop, p1); - dest(triangleloop, p2); + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + edgenumber = firstnumber; + /* To loop over the set of edges, loop over all triangles, and look at */ + /* the three edges of each triangle. If there isn't another triangle */ + /* adjacent to the edge, operate on the edge. If there is another */ + /* adjacent triangle, operate on the edge only if the current triangle */ + /* has a smaller pointer than its neighbor. This way, each edge is */ + /* considered only once. */ + while ( triangleloop.tri != (triangle *) NULL ) { + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + sym( triangleloop, trisym ); + if ( ( triangleloop.tri < trisym.tri ) || ( trisym.tri == dummytri ) ) { + org( triangleloop, p1 ); + dest( triangleloop, p2 ); #ifdef TRILIBRARY - elist[index++] = pointmark(p1); - elist[index++] = pointmark(p2); + elist[index++] = pointmark( p1 ); + elist[index++] = pointmark( p2 ); #endif /* TRILIBRARY */ - if (nobound) { + if ( nobound ) { #ifndef TRILIBRARY - /* Edge number, indices of two endpoints. */ - fprintf(outfile, "%4d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2)); + /* Edge number, indices of two endpoints. */ + fprintf( outfile, "%4d %d %d\n", edgenumber, + pointmark( p1 ), pointmark( p2 ) ); #endif /* not TRILIBRARY */ - } else { - /* Edge number, indices of two endpoints, and a boundary marker. */ - /* If there's no shell edge, the boundary marker is zero. */ - if (useshelles) { - tspivot(triangleloop, checkmark); - if (checkmark.sh == dummysh) { + } + else { + /* Edge number, indices of two endpoints, and a boundary marker. */ + /* If there's no shell edge, the boundary marker is zero. */ + if ( useshelles ) { + tspivot( triangleloop, checkmark ); + if ( checkmark.sh == dummysh ) { #ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = 0; + emlist[edgenumber - firstnumber] = 0; #else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), 0); + fprintf( outfile, "%4d %d %d %d\n", edgenumber, + pointmark( p1 ), pointmark( p2 ), 0 ); #endif /* not TRILIBRARY */ - } else { + } + else { #ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = mark(checkmark); + emlist[edgenumber - firstnumber] = mark( checkmark ); #else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), mark(checkmark)); + fprintf( outfile, "%4d %d %d %d\n", edgenumber, + pointmark( p1 ), pointmark( p2 ), mark( checkmark ) ); #endif /* not TRILIBRARY */ - } - } else { + } + } + else { #ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = trisym.tri == dummytri; + emlist[edgenumber - firstnumber] = trisym.tri == dummytri; #else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), trisym.tri == dummytri); + fprintf( outfile, "%4d %d %d %d\n", edgenumber, + pointmark( p1 ), pointmark( p2 ), trisym.tri == dummytri ); #endif /* not TRILIBRARY */ - } - } - edgenumber++; - } - } - triangleloop.tri = triangletraverse(); - } + } + } + edgenumber++; + } + } + triangleloop.tri = triangletraverse(); + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ } @@ -12237,9 +12392,9 @@ char **argv; #ifdef TRILIBRARY -void writevoronoi(vpointlist, vpointattriblist, vpointmarkerlist, vedgelist, - vedgemarkerlist, vnormlist) -REAL **vpointlist; +void writevoronoi( vpointlist, vpointattriblist, vpointmarkerlist, vedgelist, + vedgemarkerlist, vnormlist ) +REAL * *vpointlist; REAL **vpointattriblist; int **vpointmarkerlist; int **vedgelist; @@ -12248,7 +12403,7 @@ REAL **vnormlist; #else /* not TRILIBRARY */ -void writevoronoi(vnodefilename, vedgefilename, argc, argv) +void writevoronoi( vnodefilename, vedgefilename, argc, argv ) char *vnodefilename; char *vedgefilename; int argc; @@ -12258,204 +12413,205 @@ char **argv; { #ifdef TRILIBRARY - REAL *plist; - REAL *palist; - int *elist; - REAL *normlist; - int coordindex; - int attribindex; + REAL *plist; + REAL *palist; + int *elist; + REAL *normlist; + int coordindex; + int attribindex; #else /* not TRILIBRARY */ - FILE *outfile; + FILE *outfile; #endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - point torg, tdest, tapex; - REAL circumcenter[2]; - REAL xi, eta; - int vnodenumber, vedgenumber; - int p1, p2; - int i; - triangle ptr; /* Temporary variable used by sym(). */ + struct triedge triangleloop, trisym; + point torg, tdest, tapex; + REAL circumcenter[2]; + REAL xi, eta; + int vnodenumber, vedgenumber; + int p1, p2; + int i; + triangle ptr; /* Temporary variable used by sym(). */ #ifdef TRILIBRARY - if (!quiet) { - printf("Writing Voronoi vertices.\n"); - } - /* Allocate memory for Voronoi vertices if necessary. */ - if (*vpointlist == (REAL *) NULL) { - *vpointlist = (REAL *) malloc(triangles.items * 2 * sizeof(REAL)); - if (*vpointlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for Voronoi vertex attributes if necessary. */ - if (*vpointattriblist == (REAL *) NULL) { - *vpointattriblist = (REAL *) malloc(triangles.items * nextras * - sizeof(REAL)); - if (*vpointattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - *vpointmarkerlist = (int *) NULL; - plist = *vpointlist; - palist = *vpointattriblist; - coordindex = 0; - attribindex = 0; + if ( !quiet ) { + printf( "Writing Voronoi vertices.\n" ); + } + /* Allocate memory for Voronoi vertices if necessary. */ + if ( *vpointlist == (REAL *) NULL ) { + *vpointlist = (REAL *) malloc( triangles.items * 2 * sizeof( REAL ) ); + if ( *vpointlist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + /* Allocate memory for Voronoi vertex attributes if necessary. */ + if ( *vpointattriblist == (REAL *) NULL ) { + *vpointattriblist = (REAL *) malloc( triangles.items * nextras * + sizeof( REAL ) ); + if ( *vpointattriblist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + *vpointmarkerlist = (int *) NULL; + plist = *vpointlist; + palist = *vpointattriblist; + coordindex = 0; + attribindex = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", vnodefilename); - } - outfile = fopen(vnodefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", vnodefilename); - exit(1); - } - /* Number of triangles, two dimensions, number of point attributes, */ - /* zero markers. */ - fprintf(outfile, "%ld %d %d %d\n", triangles.items, 2, nextras, 0); + if ( !quiet ) { + printf( "Writing %s.\n", vnodefilename ); + } + outfile = fopen( vnodefilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", vnodefilename ); + exit( 1 ); + } + /* Number of triangles, two dimensions, number of point attributes, */ + /* zero markers. */ + fprintf( outfile, "%ld %d %d %d\n", triangles.items, 2, nextras, 0 ); #endif /* not TRILIBRARY */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - vnodenumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, torg); - dest(triangleloop, tdest); - apex(triangleloop, tapex); - findcircumcenter(torg, tdest, tapex, circumcenter, &xi, &eta); + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + triangleloop.orient = 0; + vnodenumber = firstnumber; + while ( triangleloop.tri != (triangle *) NULL ) { + org( triangleloop, torg ); + dest( triangleloop, tdest ); + apex( triangleloop, tapex ); + findcircumcenter( torg, tdest, tapex, circumcenter, &xi, &eta ); #ifdef TRILIBRARY - /* X and y coordinates. */ - plist[coordindex++] = circumcenter[0]; - plist[coordindex++] = circumcenter[1]; - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i]) - + eta * (tapex[i] - torg[i]); - } + /* X and y coordinates. */ + plist[coordindex++] = circumcenter[0]; + plist[coordindex++] = circumcenter[1]; + for ( i = 2; i < 2 + nextras; i++ ) { + /* Interpolate the point attributes at the circumcenter. */ + palist[attribindex++] = torg[i] + xi * ( tdest[i] - torg[i] ) + + eta * ( tapex[i] - torg[i] ); + } #else /* not TRILIBRARY */ - /* Voronoi vertex number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g", vnodenumber, circumcenter[0], - circumcenter[1]); - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - fprintf(outfile, " %.17g", torg[i] + xi * (tdest[i] - torg[i]) - + eta * (tapex[i] - torg[i])); - } - fprintf(outfile, "\n"); + /* Voronoi vertex number, x and y coordinates. */ + fprintf( outfile, "%4d %.17g %.17g", vnodenumber, circumcenter[0], + circumcenter[1] ); + for ( i = 2; i < 2 + nextras; i++ ) { + /* Interpolate the point attributes at the circumcenter. */ + fprintf( outfile, " %.17g", torg[i] + xi * ( tdest[i] - torg[i] ) + + eta * ( tapex[i] - torg[i] ) ); + } + fprintf( outfile, "\n" ); #endif /* not TRILIBRARY */ - * (int *) (triangleloop.tri + 6) = vnodenumber; - triangleloop.tri = triangletraverse(); - vnodenumber++; - } + *(int *) ( triangleloop.tri + 6 ) = vnodenumber; + triangleloop.tri = triangletraverse(); + vnodenumber++; + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ #ifdef TRILIBRARY - if (!quiet) { - printf("Writing Voronoi edges.\n"); - } - /* Allocate memory for output Voronoi edges if necessary. */ - if (*vedgelist == (int *) NULL) { - *vedgelist = (int *) malloc(edges * 2 * sizeof(int)); - if (*vedgelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - *vedgemarkerlist = (int *) NULL; - /* Allocate memory for output Voronoi norms if necessary. */ - if (*vnormlist == (REAL *) NULL) { - *vnormlist = (REAL *) malloc(edges * 2 * sizeof(REAL)); - if (*vnormlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - elist = *vedgelist; - normlist = *vnormlist; - coordindex = 0; + if ( !quiet ) { + printf( "Writing Voronoi edges.\n" ); + } + /* Allocate memory for output Voronoi edges if necessary. */ + if ( *vedgelist == (int *) NULL ) { + *vedgelist = (int *) malloc( edges * 2 * sizeof( int ) ); + if ( *vedgelist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + *vedgemarkerlist = (int *) NULL; + /* Allocate memory for output Voronoi norms if necessary. */ + if ( *vnormlist == (REAL *) NULL ) { + *vnormlist = (REAL *) malloc( edges * 2 * sizeof( REAL ) ); + if ( *vnormlist == (REAL *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + elist = *vedgelist; + normlist = *vnormlist; + coordindex = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", vedgefilename); - } - outfile = fopen(vedgefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", vedgefilename); - exit(1); - } - /* Number of edges, zero boundary markers. */ - fprintf(outfile, "%ld %d\n", edges, 0); + if ( !quiet ) { + printf( "Writing %s.\n", vedgefilename ); + } + outfile = fopen( vedgefilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", vedgefilename ); + exit( 1 ); + } + /* Number of edges, zero boundary markers. */ + fprintf( outfile, "%ld %d\n", edges, 0 ); #endif /* not TRILIBRARY */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - vedgenumber = firstnumber; - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - /* Find the number of this triangle (and Voronoi vertex). */ - p1 = * (int *) (triangleloop.tri + 6); - if (trisym.tri == dummytri) { - org(triangleloop, torg); - dest(triangleloop, tdest); + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + vedgenumber = firstnumber; + /* To loop over the set of edges, loop over all triangles, and look at */ + /* the three edges of each triangle. If there isn't another triangle */ + /* adjacent to the edge, operate on the edge. If there is another */ + /* adjacent triangle, operate on the edge only if the current triangle */ + /* has a smaller pointer than its neighbor. This way, each edge is */ + /* considered only once. */ + while ( triangleloop.tri != (triangle *) NULL ) { + for ( triangleloop.orient = 0; triangleloop.orient < 3; + triangleloop.orient++ ) { + sym( triangleloop, trisym ); + if ( ( triangleloop.tri < trisym.tri ) || ( trisym.tri == dummytri ) ) { + /* Find the number of this triangle (and Voronoi vertex). */ + p1 = *(int *) ( triangleloop.tri + 6 ); + if ( trisym.tri == dummytri ) { + org( triangleloop, torg ); + dest( triangleloop, tdest ); #ifdef TRILIBRARY - /* Copy an infinite ray. Index of one endpoint, and -1. */ - elist[coordindex] = p1; - normlist[coordindex++] = tdest[1] - torg[1]; - elist[coordindex] = -1; - normlist[coordindex++] = torg[0] - tdest[0]; + /* Copy an infinite ray. Index of one endpoint, and -1. */ + elist[coordindex] = p1; + normlist[coordindex++] = tdest[1] - torg[1]; + elist[coordindex] = -1; + normlist[coordindex++] = torg[0] - tdest[0]; #else /* not TRILIBRARY */ - /* Write an infinite ray. Edge number, index of one endpoint, -1, */ - /* and x and y coordinates of a vector representing the */ - /* direction of the ray. */ - fprintf(outfile, "%4d %d %d %.17g %.17g\n", vedgenumber, - p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]); + /* Write an infinite ray. Edge number, index of one endpoint, -1, */ + /* and x and y coordinates of a vector representing the */ + /* direction of the ray. */ + fprintf( outfile, "%4d %d %d %.17g %.17g\n", vedgenumber, + p1, -1, tdest[1] - torg[1], torg[0] - tdest[0] ); #endif /* not TRILIBRARY */ - } else { - /* Find the number of the adjacent triangle (and Voronoi vertex). */ - p2 = * (int *) (trisym.tri + 6); - /* Finite edge. Write indices of two endpoints. */ + } + else { + /* Find the number of the adjacent triangle (and Voronoi vertex). */ + p2 = *(int *) ( trisym.tri + 6 ); + /* Finite edge. Write indices of two endpoints. */ #ifdef TRILIBRARY - elist[coordindex] = p1; - normlist[coordindex++] = 0.0; - elist[coordindex] = p2; - normlist[coordindex++] = 0.0; + elist[coordindex] = p1; + normlist[coordindex++] = 0.0; + elist[coordindex] = p2; + normlist[coordindex++] = 0.0; #else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d\n", vedgenumber, p1, p2); + fprintf( outfile, "%4d %d %d\n", vedgenumber, p1, p2 ); #endif /* not TRILIBRARY */ - } - vedgenumber++; - } - } - triangleloop.tri = triangletraverse(); - } + } + vedgenumber++; + } + } + triangleloop.tri = triangletraverse(); + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* not TRILIBRARY */ } #ifdef TRILIBRARY -void writeneighbors(neighborlist) +void writeneighbors( neighborlist ) int **neighborlist; #else /* not TRILIBRARY */ -void writeneighbors(neighborfilename, argc, argv) +void writeneighbors( neighborfilename, argc, argv ) char *neighborfilename; int argc; char **argv; @@ -12464,83 +12620,83 @@ char **argv; { #ifdef TRILIBRARY - int *nlist; - int index; + int *nlist; + int index; #else /* not TRILIBRARY */ - FILE *outfile; + FILE *outfile; #endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - int elementnumber; - int neighbor1, neighbor2, neighbor3; - triangle ptr; /* Temporary variable used by sym(). */ + struct triedge triangleloop, trisym; + int elementnumber; + int neighbor1, neighbor2, neighbor3; + triangle ptr; /* Temporary variable used by sym(). */ #ifdef TRILIBRARY - if (!quiet) { - printf("Writing neighbors.\n"); - } - /* Allocate memory for neighbors if necessary. */ - if (*neighborlist == (int *) NULL) { - *neighborlist = (int *) malloc(triangles.items * 3 * sizeof(int)); - if (*neighborlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - nlist = *neighborlist; - index = 0; + if ( !quiet ) { + printf( "Writing neighbors.\n" ); + } + /* Allocate memory for neighbors if necessary. */ + if ( *neighborlist == (int *) NULL ) { + *neighborlist = (int *) malloc( triangles.items * 3 * sizeof( int ) ); + if ( *neighborlist == (int *) NULL ) { + printf( "Error: Out of memory.\n" ); + exit( 1 ); + } + } + nlist = *neighborlist; + index = 0; #else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", neighborfilename); - } - outfile = fopen(neighborfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", neighborfilename); - exit(1); - } - /* Number of triangles, three edges per triangle. */ - fprintf(outfile, "%ld %d\n", triangles.items, 3); + if ( !quiet ) { + printf( "Writing %s.\n", neighborfilename ); + } + outfile = fopen( neighborfilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", neighborfilename ); + exit( 1 ); + } + /* Number of triangles, three edges per triangle. */ + fprintf( outfile, "%ld %d\n", triangles.items, 3 ); #endif /* not TRILIBRARY */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - * (int *) (triangleloop.tri + 6) = elementnumber; - triangleloop.tri = triangletraverse(); - elementnumber++; - } - * (int *) (dummytri + 6) = -1; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - triangleloop.orient = 1; - sym(triangleloop, trisym); - neighbor1 = * (int *) (trisym.tri + 6); - triangleloop.orient = 2; - sym(triangleloop, trisym); - neighbor2 = * (int *) (trisym.tri + 6); - triangleloop.orient = 0; - sym(triangleloop, trisym); - neighbor3 = * (int *) (trisym.tri + 6); + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + triangleloop.orient = 0; + elementnumber = firstnumber; + while ( triangleloop.tri != (triangle *) NULL ) { + *(int *) ( triangleloop.tri + 6 ) = elementnumber; + triangleloop.tri = triangletraverse(); + elementnumber++; + } + *(int *) ( dummytri + 6 ) = -1; + + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + elementnumber = firstnumber; + while ( triangleloop.tri != (triangle *) NULL ) { + triangleloop.orient = 1; + sym( triangleloop, trisym ); + neighbor1 = *(int *) ( trisym.tri + 6 ); + triangleloop.orient = 2; + sym( triangleloop, trisym ); + neighbor2 = *(int *) ( trisym.tri + 6 ); + triangleloop.orient = 0; + sym( triangleloop, trisym ); + neighbor3 = *(int *) ( trisym.tri + 6 ); #ifdef TRILIBRARY - nlist[index++] = neighbor1; - nlist[index++] = neighbor2; - nlist[index++] = neighbor3; + nlist[index++] = neighbor1; + nlist[index++] = neighbor2; + nlist[index++] = neighbor3; #else /* not TRILIBRARY */ - /* Triangle number, neighboring triangle numbers. */ - fprintf(outfile, "%4d %d %d %d\n", elementnumber, - neighbor1, neighbor2, neighbor3); + /* Triangle number, neighboring triangle numbers. */ + fprintf( outfile, "%4d %d %d %d\n", elementnumber, + neighbor1, neighbor2, neighbor3 ); #endif /* not TRILIBRARY */ - triangleloop.tri = triangletraverse(); - elementnumber++; - } + triangleloop.tri = triangletraverse(); + elementnumber++; + } #ifndef TRILIBRARY - finishfile(outfile, argc, argv); + finishfile( outfile, argc, argv ); #endif /* TRILIBRARY */ } @@ -12555,52 +12711,52 @@ char **argv; #ifndef TRILIBRARY -void writeoff(offfilename, argc, argv) +void writeoff( offfilename, argc, argv ) char *offfilename; int argc; char **argv; { - FILE *outfile; - struct triedge triangleloop; - point pointloop; - point p1, p2, p3; - - if (!quiet) { - printf("Writing %s.\n", offfilename); - } - outfile = fopen(offfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", offfilename); - exit(1); - } - /* Number of points, triangles, and edges. */ - fprintf(outfile, "OFF\n%ld %ld %ld\n", points.items, triangles.items, - edges); - - /* Write the points. */ - traversalinit(&points); - pointloop = pointtraverse(); - while (pointloop != (point) NULL) { - /* The "0.0" is here because the OFF format uses 3D coordinates. */ - fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0], - pointloop[1], 0.0); - pointloop = pointtraverse(); - } - - /* Write the triangles. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p1); - dest(triangleloop, p2); - apex(triangleloop, p3); - /* The "3" means a three-vertex polygon. */ - fprintf(outfile, " 3 %4d %4d %4d\n", pointmark(p1) - 1, - pointmark(p2) - 1, pointmark(p3) - 1); - triangleloop.tri = triangletraverse(); - } - finishfile(outfile, argc, argv); + FILE *outfile; + struct triedge triangleloop; + point pointloop; + point p1, p2, p3; + + if ( !quiet ) { + printf( "Writing %s.\n", offfilename ); + } + outfile = fopen( offfilename, "w" ); + if ( outfile == (FILE *) NULL ) { + printf( " Error: Cannot create file %s.\n", offfilename ); + exit( 1 ); + } + /* Number of points, triangles, and edges. */ + fprintf( outfile, "OFF\n%ld %ld %ld\n", points.items, triangles.items, + edges ); + + /* Write the points. */ + traversalinit( &points ); + pointloop = pointtraverse(); + while ( pointloop != (point) NULL ) { + /* The "0.0" is here because the OFF format uses 3D coordinates. */ + fprintf( outfile, " %.17g %.17g %.17g\n", pointloop[0], + pointloop[1], 0.0 ); + pointloop = pointtraverse(); + } + + /* Write the triangles. */ + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + triangleloop.orient = 0; + while ( triangleloop.tri != (triangle *) NULL ) { + org( triangleloop, p1 ); + dest( triangleloop, p2 ); + apex( triangleloop, p3 ); + /* The "3" means a three-vertex polygon. */ + fprintf( outfile, " 3 %4d %4d %4d\n", pointmark( p1 ) - 1, + pointmark( p2 ) - 1, pointmark( p3 ) - 1 ); + triangleloop.tri = triangletraverse(); + } + finishfile( outfile, argc, argv ); } #endif /* not TRILIBRARY */ @@ -12615,196 +12771,199 @@ char **argv; /* */ /*****************************************************************************/ -void quality_statistics() -{ - struct triedge triangleloop; - point p[3]; - REAL cossquaretable[8]; - REAL ratiotable[16]; - REAL dx[3], dy[3]; - REAL edgelength[3]; - REAL dotproduct; - REAL cossquare; - REAL triarea; - REAL shortest, longest; - REAL trilongest2; - REAL smallestarea, biggestarea; - REAL triminaltitude2; - REAL minaltitude; - REAL triaspect2; - REAL worstaspect; - REAL smallestangle, biggestangle; - REAL radconst, degconst; - int angletable[18]; - int aspecttable[16]; - int aspectindex; - int tendegree; - int acutebiggest; - int i, ii, j, k; - - printf("Mesh quality statistics:\n\n"); - radconst = (REAL)(PI / 18.0); - degconst = (REAL)(180.0 / PI); - for (i = 0; i < 8; i++) { - cossquaretable[i] = (REAL)(cos(radconst * (REAL) (i + 1))); - cossquaretable[i] = cossquaretable[i] * cossquaretable[i]; - } - for (i = 0; i < 18; i++) { - angletable[i] = 0; - } - - ratiotable[0] = 1.5; ratiotable[1] = 2.0; - ratiotable[2] = 2.5; ratiotable[3] = 3.0; - ratiotable[4] = 4.0; ratiotable[5] = 6.0; - ratiotable[6] = 10.0; ratiotable[7] = 15.0; - ratiotable[8] = 25.0; ratiotable[9] = 50.0; - ratiotable[10] = 100.0; ratiotable[11] = 300.0; - ratiotable[12] = 1000.0; ratiotable[13] = 10000.0; - ratiotable[14] = 100000.0; ratiotable[15] = 0.0; - for (i = 0; i < 16; i++) { - aspecttable[i] = 0; - } - - worstaspect = 0.0; - minaltitude = xmax - xmin + ymax - ymin; - minaltitude = minaltitude * minaltitude; - shortest = minaltitude; - longest = 0.0; - smallestarea = minaltitude; - biggestarea = 0.0; - worstaspect = 0.0; - smallestangle = 0.0; - biggestangle = 2.0; - acutebiggest = 1; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p[0]); - dest(triangleloop, p[1]); - apex(triangleloop, p[2]); - trilongest2 = 0.0; - - for (i = 0; i < 3; i++) { - j = plus1mod3[i]; - k = minus1mod3[i]; - dx[i] = p[j][0] - p[k][0]; - dy[i] = p[j][1] - p[k][1]; - edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i]; - if (edgelength[i] > trilongest2) { - trilongest2 = edgelength[i]; - } - if (edgelength[i] > longest) { - longest = edgelength[i]; - } - if (edgelength[i] < shortest) { - shortest = edgelength[i]; - } - } - - triarea = counterclockwise(p[0], p[1], p[2]); - if (triarea < smallestarea) { - smallestarea = triarea; - } - if (triarea > biggestarea) { - biggestarea = triarea; - } - triminaltitude2 = triarea * triarea / trilongest2; - if (triminaltitude2 < minaltitude) { - minaltitude = triminaltitude2; - } - triaspect2 = trilongest2 / triminaltitude2; - if (triaspect2 > worstaspect) { - worstaspect = triaspect2; - } - aspectindex = 0; - while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex]) - && (aspectindex < 15)) { - aspectindex++; - } - aspecttable[aspectindex]++; - - for (i = 0; i < 3; i++) { - j = plus1mod3[i]; - k = minus1mod3[i]; - dotproduct = dx[j] * dx[k] + dy[j] * dy[k]; - cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]); - tendegree = 8; - for (ii = 7; ii >= 0; ii--) { - if (cossquare > cossquaretable[ii]) { - tendegree = ii; - } - } - if (dotproduct <= 0.0) { - angletable[tendegree]++; - if (cossquare > smallestangle) { - smallestangle = cossquare; - } - if (acutebiggest && (cossquare < biggestangle)) { - biggestangle = cossquare; - } - } else { - angletable[17 - tendegree]++; - if (acutebiggest || (cossquare > biggestangle)) { - biggestangle = cossquare; - acutebiggest = 0; - } - } - } - triangleloop.tri = triangletraverse(); - } - - shortest = (REAL)sqrt(shortest); - longest = (REAL)sqrt(longest); - minaltitude = (REAL)sqrt(minaltitude); - worstaspect = (REAL)sqrt(worstaspect); - smallestarea *= 2.0; - biggestarea *= 2.0; - if (smallestangle >= 1.0) { - smallestangle = 0.0; - } else { - smallestangle = (REAL)(degconst * acos(sqrt(smallestangle))); - } - if (biggestangle >= 1.0) { - biggestangle = 180.0; - } else { - if (acutebiggest) { - biggestangle = (REAL)(degconst * acos(sqrt(biggestangle))); - } else { - biggestangle = (REAL)(180.0 - degconst * acos(sqrt(biggestangle))); - } - } - - printf(" Smallest area: %16.5g | Largest area: %16.5g\n", - smallestarea, biggestarea); - printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n", - shortest, longest); - printf(" Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n", - minaltitude, worstaspect); - printf(" Aspect ratio histogram:\n"); - printf(" 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", - ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8], - aspecttable[8]); - for (i = 1; i < 7; i++) { - printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", - ratiotable[i - 1], ratiotable[i], aspecttable[i], - ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]); - } - printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n", - ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14], - aspecttable[15]); - printf( -" (Triangle aspect ratio is longest edge divided by shortest altitude)\n\n"); - printf(" Smallest angle: %15.5g | Largest angle: %15.5g\n\n", - smallestangle, biggestangle); - printf(" Angle histogram:\n"); - for (i = 0; i < 9; i++) { - printf(" %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n", - i * 10, i * 10 + 10, angletable[i], - i * 10 + 90, i * 10 + 100, angletable[i + 9]); - } - printf("\n"); +void quality_statistics(){ + struct triedge triangleloop; + point p[3]; + REAL cossquaretable[8]; + REAL ratiotable[16]; + REAL dx[3], dy[3]; + REAL edgelength[3]; + REAL dotproduct; + REAL cossquare; + REAL triarea; + REAL shortest, longest; + REAL trilongest2; + REAL smallestarea, biggestarea; + REAL triminaltitude2; + REAL minaltitude; + REAL triaspect2; + REAL worstaspect; + REAL smallestangle, biggestangle; + REAL radconst, degconst; + int angletable[18]; + int aspecttable[16]; + int aspectindex; + int tendegree; + int acutebiggest; + int i, ii, j, k; + + printf( "Mesh quality statistics:\n\n" ); + radconst = (REAL)( PI / 18.0 ); + degconst = (REAL)( 180.0 / PI ); + for ( i = 0; i < 8; i++ ) { + cossquaretable[i] = (REAL)( cos( radconst * (REAL) ( i + 1 ) ) ); + cossquaretable[i] = cossquaretable[i] * cossquaretable[i]; + } + for ( i = 0; i < 18; i++ ) { + angletable[i] = 0; + } + + ratiotable[0] = 1.5; ratiotable[1] = 2.0; + ratiotable[2] = 2.5; ratiotable[3] = 3.0; + ratiotable[4] = 4.0; ratiotable[5] = 6.0; + ratiotable[6] = 10.0; ratiotable[7] = 15.0; + ratiotable[8] = 25.0; ratiotable[9] = 50.0; + ratiotable[10] = 100.0; ratiotable[11] = 300.0; + ratiotable[12] = 1000.0; ratiotable[13] = 10000.0; + ratiotable[14] = 100000.0; ratiotable[15] = 0.0; + for ( i = 0; i < 16; i++ ) { + aspecttable[i] = 0; + } + + worstaspect = 0.0; + minaltitude = xmax - xmin + ymax - ymin; + minaltitude = minaltitude * minaltitude; + shortest = minaltitude; + longest = 0.0; + smallestarea = minaltitude; + biggestarea = 0.0; + worstaspect = 0.0; + smallestangle = 0.0; + biggestangle = 2.0; + acutebiggest = 1; + + traversalinit( &triangles ); + triangleloop.tri = triangletraverse(); + triangleloop.orient = 0; + while ( triangleloop.tri != (triangle *) NULL ) { + org( triangleloop, p[0] ); + dest( triangleloop, p[1] ); + apex( triangleloop, p[2] ); + trilongest2 = 0.0; + + for ( i = 0; i < 3; i++ ) { + j = plus1mod3[i]; + k = minus1mod3[i]; + dx[i] = p[j][0] - p[k][0]; + dy[i] = p[j][1] - p[k][1]; + edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i]; + if ( edgelength[i] > trilongest2 ) { + trilongest2 = edgelength[i]; + } + if ( edgelength[i] > longest ) { + longest = edgelength[i]; + } + if ( edgelength[i] < shortest ) { + shortest = edgelength[i]; + } + } + + triarea = counterclockwise( p[0], p[1], p[2] ); + if ( triarea < smallestarea ) { + smallestarea = triarea; + } + if ( triarea > biggestarea ) { + biggestarea = triarea; + } + triminaltitude2 = triarea * triarea / trilongest2; + if ( triminaltitude2 < minaltitude ) { + minaltitude = triminaltitude2; + } + triaspect2 = trilongest2 / triminaltitude2; + if ( triaspect2 > worstaspect ) { + worstaspect = triaspect2; + } + aspectindex = 0; + while ( ( triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex] ) + && ( aspectindex < 15 ) ) { + aspectindex++; + } + aspecttable[aspectindex]++; + + for ( i = 0; i < 3; i++ ) { + j = plus1mod3[i]; + k = minus1mod3[i]; + dotproduct = dx[j] * dx[k] + dy[j] * dy[k]; + cossquare = dotproduct * dotproduct / ( edgelength[j] * edgelength[k] ); + tendegree = 8; + for ( ii = 7; ii >= 0; ii-- ) { + if ( cossquare > cossquaretable[ii] ) { + tendegree = ii; + } + } + if ( dotproduct <= 0.0 ) { + angletable[tendegree]++; + if ( cossquare > smallestangle ) { + smallestangle = cossquare; + } + if ( acutebiggest && ( cossquare < biggestangle ) ) { + biggestangle = cossquare; + } + } + else { + angletable[17 - tendegree]++; + if ( acutebiggest || ( cossquare > biggestangle ) ) { + biggestangle = cossquare; + acutebiggest = 0; + } + } + } + triangleloop.tri = triangletraverse(); + } + + shortest = (REAL)sqrt( shortest ); + longest = (REAL)sqrt( longest ); + minaltitude = (REAL)sqrt( minaltitude ); + worstaspect = (REAL)sqrt( worstaspect ); + smallestarea *= 2.0; + biggestarea *= 2.0; + if ( smallestangle >= 1.0 ) { + smallestangle = 0.0; + } + else { + smallestangle = (REAL)( degconst * acos( sqrt( smallestangle ) ) ); + } + if ( biggestangle >= 1.0 ) { + biggestangle = 180.0; + } + else { + if ( acutebiggest ) { + biggestangle = (REAL)( degconst * acos( sqrt( biggestangle ) ) ); + } + else { + biggestangle = (REAL)( 180.0 - degconst * acos( sqrt( biggestangle ) ) ); + } + } + + printf( " Smallest area: %16.5g | Largest area: %16.5g\n", + smallestarea, biggestarea ); + printf( " Shortest edge: %16.5g | Longest edge: %16.5g\n", + shortest, longest ); + printf( " Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n", + minaltitude, worstaspect ); + printf( " Aspect ratio histogram:\n" ); + printf( " 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", + ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8], + aspecttable[8] ); + for ( i = 1; i < 7; i++ ) { + printf( " %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", + ratiotable[i - 1], ratiotable[i], aspecttable[i], + ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8] ); + } + printf( " %6.6g - %-6.6g : %8d | %6.6g - : %8d\n", + ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14], + aspecttable[15] ); + printf( + " (Triangle aspect ratio is longest edge divided by shortest altitude)\n\n" ); + printf( " Smallest angle: %15.5g | Largest angle: %15.5g\n\n", + smallestangle, biggestangle ); + printf( " Angle histogram:\n" ); + for ( i = 0; i < 9; i++ ) { + printf( " %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n", + i * 10, i * 10 + 10, angletable[i], + i * 10 + 90, i * 10 + 100, angletable[i + 9] ); + } + printf( "\n" ); } /*****************************************************************************/ @@ -12813,78 +12972,78 @@ void quality_statistics() /* */ /*****************************************************************************/ -void statistics() -{ - printf("\nStatistics:\n\n"); - printf(" Input points: %d\n", inpoints); - if (refine) { - printf(" Input triangles: %d\n", inelements); - } - if (poly) { - printf(" Input segments: %d\n", insegments); - if (!refine) { - printf(" Input holes: %d\n", holes); - } - } - - printf("\n Mesh points: %ld\n", points.items); - printf(" Mesh triangles: %ld\n", triangles.items); - printf(" Mesh edges: %ld\n", edges); - if (poly || refine) { - printf(" Mesh boundary edges: %ld\n", hullsize); - printf(" Mesh segments: %ld\n\n", shelles.items); - } else { - printf(" Mesh convex hull edges: %ld\n\n", hullsize); - } - if (verbose) { - quality_statistics(); - printf("Memory allocation statistics:\n\n"); - printf(" Maximum number of points: %ld\n", points.maxitems); - printf(" Maximum number of triangles: %ld\n", triangles.maxitems); - if (shelles.maxitems > 0) { - printf(" Maximum number of segments: %ld\n", shelles.maxitems); - } - if (viri.maxitems > 0) { - printf(" Maximum number of viri: %ld\n", viri.maxitems); - } - if (badsegments.maxitems > 0) { - printf(" Maximum number of encroached segments: %ld\n", - badsegments.maxitems); - } - if (badtriangles.maxitems > 0) { - printf(" Maximum number of bad triangles: %ld\n", - badtriangles.maxitems); - } - if (splaynodes.maxitems > 0) { - printf(" Maximum number of splay tree nodes: %ld\n", - splaynodes.maxitems); - } - printf(" Approximate heap memory use (bytes): %ld\n\n", - points.maxitems * points.itembytes - + triangles.maxitems * triangles.itembytes - + shelles.maxitems * shelles.itembytes - + viri.maxitems * viri.itembytes - + badsegments.maxitems * badsegments.itembytes - + badtriangles.maxitems * badtriangles.itembytes - + splaynodes.maxitems * splaynodes.itembytes); - - printf("Algorithmic statistics:\n\n"); - printf(" Number of incircle tests: %ld\n", incirclecount); - printf(" Number of orientation tests: %ld\n", counterclockcount); - if (hyperbolacount > 0) { - printf(" Number of right-of-hyperbola tests: %ld\n", - hyperbolacount); - } - if (circumcentercount > 0) { - printf(" Number of circumcenter computations: %ld\n", - circumcentercount); - } - if (circletopcount > 0) { - printf(" Number of circle top computations: %ld\n", - circletopcount); - } - printf("\n"); - } +void statistics(){ + printf( "\nStatistics:\n\n" ); + printf( " Input points: %d\n", inpoints ); + if ( refine ) { + printf( " Input triangles: %d\n", inelements ); + } + if ( poly ) { + printf( " Input segments: %d\n", insegments ); + if ( !refine ) { + printf( " Input holes: %d\n", holes ); + } + } + + printf( "\n Mesh points: %ld\n", points.items ); + printf( " Mesh triangles: %ld\n", triangles.items ); + printf( " Mesh edges: %ld\n", edges ); + if ( poly || refine ) { + printf( " Mesh boundary edges: %ld\n", hullsize ); + printf( " Mesh segments: %ld\n\n", shelles.items ); + } + else { + printf( " Mesh convex hull edges: %ld\n\n", hullsize ); + } + if ( verbose ) { + quality_statistics(); + printf( "Memory allocation statistics:\n\n" ); + printf( " Maximum number of points: %ld\n", points.maxitems ); + printf( " Maximum number of triangles: %ld\n", triangles.maxitems ); + if ( shelles.maxitems > 0 ) { + printf( " Maximum number of segments: %ld\n", shelles.maxitems ); + } + if ( viri.maxitems > 0 ) { + printf( " Maximum number of viri: %ld\n", viri.maxitems ); + } + if ( badsegments.maxitems > 0 ) { + printf( " Maximum number of encroached segments: %ld\n", + badsegments.maxitems ); + } + if ( badtriangles.maxitems > 0 ) { + printf( " Maximum number of bad triangles: %ld\n", + badtriangles.maxitems ); + } + if ( splaynodes.maxitems > 0 ) { + printf( " Maximum number of splay tree nodes: %ld\n", + splaynodes.maxitems ); + } + printf( " Approximate heap memory use (bytes): %ld\n\n", + points.maxitems * points.itembytes + + triangles.maxitems * triangles.itembytes + + shelles.maxitems * shelles.itembytes + + viri.maxitems * viri.itembytes + + badsegments.maxitems * badsegments.itembytes + + badtriangles.maxitems * badtriangles.itembytes + + splaynodes.maxitems * splaynodes.itembytes ); + + printf( "Algorithmic statistics:\n\n" ); + printf( " Number of incircle tests: %ld\n", incirclecount ); + printf( " Number of orientation tests: %ld\n", counterclockcount ); + if ( hyperbolacount > 0 ) { + printf( " Number of right-of-hyperbola tests: %ld\n", + hyperbolacount ); + } + if ( circumcentercount > 0 ) { + printf( " Number of circumcenter computations: %ld\n", + circumcentercount ); + } + if ( circletopcount > 0 ) { + printf( " Number of circle top computations: %ld\n", + circletopcount ); + } + printf( "\n" ); + } } /*****************************************************************************/ @@ -12914,7 +13073,7 @@ void statistics() #ifdef TRILIBRARY -void triangulate(triswitches, in, out, vorout) +void triangulate( triswitches, in, out, vorout ) char *triswitches; struct triangulateio *in; struct triangulateio *out; @@ -12922,315 +13081,323 @@ struct triangulateio *vorout; #else /* not TRILIBRARY */ -int main(argc, argv) +int main( argc, argv ) int argc; char **argv; #endif /* not TRILIBRARY */ { - REAL *holearray; /* Array of holes. */ - REAL *regionarray; /* Array of regional attributes and area constraints. */ + REAL *holearray; /* Array of holes. */ + REAL *regionarray; /* Array of regional attributes and area constraints. */ #ifndef TRILIBRARY - FILE *polyfile; + FILE *polyfile; #endif /* not TRILIBRARY */ #ifndef NO_TIMER - /* Variables for timing the performance of Triangle. The types are */ - /* defined in sys/time.h. */ - struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6; - struct timezone tz; + /* Variables for timing the performance of Triangle. The types are */ + /* defined in sys/time.h. */ + struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6; + struct timezone tz; #endif /* NO_TIMER */ #ifndef NO_TIMER - gettimeofday(&tv0, &tz); + gettimeofday( &tv0, &tz ); #endif /* NO_TIMER */ - triangleinit(); + triangleinit(); #ifdef TRILIBRARY - parsecommandline(1, &triswitches); + parsecommandline( 1, &triswitches ); #else /* not TRILIBRARY */ - parsecommandline(argc, argv); + parsecommandline( argc, argv ); #endif /* not TRILIBRARY */ #ifdef TRILIBRARY - transfernodes(in->pointlist, in->pointattributelist, in->pointmarkerlist, - in->numberofpoints, in->numberofpointattributes); + transfernodes( in->pointlist, in->pointattributelist, in->pointmarkerlist, + in->numberofpoints, in->numberofpointattributes ); #else /* not TRILIBRARY */ - readnodes(innodefilename, inpolyfilename, &polyfile); + readnodes( innodefilename, inpolyfilename, &polyfile ); #endif /* not TRILIBRARY */ #ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv1, &tz); - } + if ( !quiet ) { + gettimeofday( &tv1, &tz ); + } #endif /* NO_TIMER */ #ifdef CDT_ONLY - hullsize = delaunay(); /* Triangulate the points. */ + hullsize = delaunay(); /* Triangulate the points. */ #else /* not CDT_ONLY */ - if (refine) { - /* Read and reconstruct a mesh. */ + if ( refine ) { + /* Read and reconstruct a mesh. */ #ifdef TRILIBRARY - hullsize = reconstruct(in->trianglelist, in->triangleattributelist, - in->trianglearealist, in->numberoftriangles, - in->numberofcorners, in->numberoftriangleattributes, - in->segmentlist, in->segmentmarkerlist, - in->numberofsegments); + hullsize = reconstruct( in->trianglelist, in->triangleattributelist, + in->trianglearealist, in->numberoftriangles, + in->numberofcorners, in->numberoftriangleattributes, + in->segmentlist, in->segmentmarkerlist, + in->numberofsegments ); #else /* not TRILIBRARY */ - hullsize = reconstruct(inelefilename, areafilename, inpolyfilename, - polyfile); + hullsize = reconstruct( inelefilename, areafilename, inpolyfilename, + polyfile ); #endif /* not TRILIBRARY */ - } else { - hullsize = delaunay(); /* Triangulate the points. */ - } + } + else { + hullsize = delaunay(); /* Triangulate the points. */ + } #endif /* not CDT_ONLY */ #ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv2, &tz); - if (refine) { - printf("Mesh reconstruction"); - } else { - printf("Delaunay"); - } - printf(" milliseconds: %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) - + (tv2.tv_usec - tv1.tv_usec) / 1000l); - } + if ( !quiet ) { + gettimeofday( &tv2, &tz ); + if ( refine ) { + printf( "Mesh reconstruction" ); + } + else { + printf( "Delaunay" ); + } + printf( " milliseconds: %ld\n", 1000l * ( tv2.tv_sec - tv1.tv_sec ) + + ( tv2.tv_usec - tv1.tv_usec ) / 1000l ); + } #endif /* NO_TIMER */ - /* Ensure that no point can be mistaken for a triangular bounding */ - /* box point in insertsite(). */ - infpoint1 = (point) NULL; - infpoint2 = (point) NULL; - infpoint3 = (point) NULL; + /* Ensure that no point can be mistaken for a triangular bounding */ + /* box point in insertsite(). */ + infpoint1 = (point) NULL; + infpoint2 = (point) NULL; + infpoint3 = (point) NULL; - if (useshelles) { - checksegments = 1; /* Segments will be introduced next. */ - if (!refine) { - /* Insert PSLG segments and/or convex hull segments. */ + if ( useshelles ) { + checksegments = 1; /* Segments will be introduced next. */ + if ( !refine ) { + /* Insert PSLG segments and/or convex hull segments. */ #ifdef TRILIBRARY - insegments = formskeleton(in->segmentlist, in->segmentmarkerlist, - in->numberofsegments); + insegments = formskeleton( in->segmentlist, in->segmentmarkerlist, + in->numberofsegments ); #else /* not TRILIBRARY */ - insegments = formskeleton(polyfile, inpolyfilename); + insegments = formskeleton( polyfile, inpolyfilename ); #endif /* not TRILIBRARY */ - } - } + } + } #ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv3, &tz); - if (useshelles && !refine) { - printf("Segment milliseconds: %ld\n", - 1000l * (tv3.tv_sec - tv2.tv_sec) - + (tv3.tv_usec - tv2.tv_usec) / 1000l); - } - } + if ( !quiet ) { + gettimeofday( &tv3, &tz ); + if ( useshelles && !refine ) { + printf( "Segment milliseconds: %ld\n", + 1000l * ( tv3.tv_sec - tv2.tv_sec ) + + ( tv3.tv_usec - tv2.tv_usec ) / 1000l ); + } + } #endif /* NO_TIMER */ - if (poly) { + if ( poly ) { #ifdef TRILIBRARY - holearray = in->holelist; - holes = in->numberofholes; - regionarray = in->regionlist; - regions = in->numberofregions; + holearray = in->holelist; + holes = in->numberofholes; + regionarray = in->regionlist; + regions = in->numberofregions; #else /* not TRILIBRARY */ - readholes(polyfile, inpolyfilename, &holearray, &holes, - ®ionarray, ®ions); + readholes( polyfile, inpolyfilename, &holearray, &holes, + ®ionarray, ®ions ); #endif /* not TRILIBRARY */ - if (!refine) { - /* Carve out holes and concavities. */ - carveholes(holearray, holes, regionarray, regions); - } - } else { - /* Without a PSLG, there can be no holes or regional attributes */ - /* or area constraints. The following are set to zero to avoid */ - /* an accidental free() later. */ - holes = 0; - regions = 0; - } + if ( !refine ) { + /* Carve out holes and concavities. */ + carveholes( holearray, holes, regionarray, regions ); + } + } + else { + /* Without a PSLG, there can be no holes or regional attributes */ + /* or area constraints. The following are set to zero to avoid */ + /* an accidental free() later. */ + holes = 0; + regions = 0; + } #ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv4, &tz); - if (poly && !refine) { - printf("Hole milliseconds: %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) - + (tv4.tv_usec - tv3.tv_usec) / 1000l); - } - } + if ( !quiet ) { + gettimeofday( &tv4, &tz ); + if ( poly && !refine ) { + printf( "Hole milliseconds: %ld\n", 1000l * ( tv4.tv_sec - tv3.tv_sec ) + + ( tv4.tv_usec - tv3.tv_usec ) / 1000l ); + } + } #endif /* NO_TIMER */ #ifndef CDT_ONLY - if (quality) { - enforcequality(); /* Enforce angle and area constraints. */ - } + if ( quality ) { + enforcequality(); /* Enforce angle and area constraints. */ + } #endif /* not CDT_ONLY */ #ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv5, &tz); + if ( !quiet ) { + gettimeofday( &tv5, &tz ); #ifndef CDT_ONLY - if (quality) { - printf("Quality milliseconds: %ld\n", - 1000l * (tv5.tv_sec - tv4.tv_sec) - + (tv5.tv_usec - tv4.tv_usec) / 1000l); - } + if ( quality ) { + printf( "Quality milliseconds: %ld\n", + 1000l * ( tv5.tv_sec - tv4.tv_sec ) + + ( tv5.tv_usec - tv4.tv_usec ) / 1000l ); + } #endif /* not CDT_ONLY */ - } + } #endif /* NO_TIMER */ - /* Compute the number of edges. */ - edges = (3l * triangles.items + hullsize) / 2l; + /* Compute the number of edges. */ + edges = ( 3l * triangles.items + hullsize ) / 2l; - if (order > 1) { - highorder(); /* Promote elements to higher polynomial order. */ - } - if (!quiet) { - printf("\n"); - } + if ( order > 1 ) { + highorder(); /* Promote elements to higher polynomial order. */ + } + if ( !quiet ) { + printf( "\n" ); + } #ifdef TRILIBRARY - out->numberofpoints = points.items; - out->numberofpointattributes = nextras; - out->numberoftriangles = triangles.items; - out->numberofcorners = (order + 1) * (order + 2) / 2; - out->numberoftriangleattributes = eextras; - out->numberofedges = edges; - if (useshelles) { - out->numberofsegments = shelles.items; - } else { - out->numberofsegments = hullsize; - } - if (vorout != (struct triangulateio *) NULL) { - vorout->numberofpoints = triangles.items; - vorout->numberofpointattributes = nextras; - vorout->numberofedges = edges; - } + out->numberofpoints = points.items; + out->numberofpointattributes = nextras; + out->numberoftriangles = triangles.items; + out->numberofcorners = ( order + 1 ) * ( order + 2 ) / 2; + out->numberoftriangleattributes = eextras; + out->numberofedges = edges; + if ( useshelles ) { + out->numberofsegments = shelles.items; + } + else { + out->numberofsegments = hullsize; + } + if ( vorout != (struct triangulateio *) NULL ) { + vorout->numberofpoints = triangles.items; + vorout->numberofpointattributes = nextras; + vorout->numberofedges = edges; + } #endif /* TRILIBRARY */ - /* If not using iteration numbers, don't write a .node file if one was */ - /* read, because the original one would be overwritten! */ - if (nonodewritten || (noiterationnum && readnodefile)) { - if (!quiet) { + /* If not using iteration numbers, don't write a .node file if one was */ + /* read, because the original one would be overwritten! */ + if ( nonodewritten || ( noiterationnum && readnodefile ) ) { + if ( !quiet ) { #ifdef TRILIBRARY - printf("NOT writing points.\n"); + printf( "NOT writing points.\n" ); #else /* not TRILIBRARY */ - printf("NOT writing a .node file.\n"); + printf( "NOT writing a .node file.\n" ); #endif /* not TRILIBRARY */ - } - numbernodes(); /* We must remember to number the points. */ - } else { + } + numbernodes(); /* We must remember to number the points. */ + } + else { #ifdef TRILIBRARY - writenodes(&out->pointlist, &out->pointattributelist, - &out->pointmarkerlist); + writenodes( &out->pointlist, &out->pointattributelist, + &out->pointmarkerlist ); #else /* not TRILIBRARY */ - writenodes(outnodefilename, argc, argv); /* Numbers the points too. */ + writenodes( outnodefilename, argc, argv ); /* Numbers the points too. */ #endif /* TRILIBRARY */ - } - if (noelewritten) { - if (!quiet) { + } + if ( noelewritten ) { + if ( !quiet ) { #ifdef TRILIBRARY - printf("NOT writing triangles.\n"); + printf( "NOT writing triangles.\n" ); #else /* not TRILIBRARY */ - printf("NOT writing an .ele file.\n"); + printf( "NOT writing an .ele file.\n" ); #endif /* not TRILIBRARY */ - } - } else { + } + } + else { #ifdef TRILIBRARY - writeelements(&out->trianglelist, &out->triangleattributelist); + writeelements( &out->trianglelist, &out->triangleattributelist ); #else /* not TRILIBRARY */ - writeelements(outelefilename, argc, argv); + writeelements( outelefilename, argc, argv ); #endif /* not TRILIBRARY */ - } - /* The -c switch (convex switch) causes a PSLG to be written */ - /* even if none was read. */ - if (poly || convex) { - /* If not using iteration numbers, don't overwrite the .poly file. */ - if (nopolywritten || noiterationnum) { - if (!quiet) { + } + /* The -c switch (convex switch) causes a PSLG to be written */ + /* even if none was read. */ + if ( poly || convex ) { + /* If not using iteration numbers, don't overwrite the .poly file. */ + if ( nopolywritten || noiterationnum ) { + if ( !quiet ) { #ifdef TRILIBRARY - printf("NOT writing segments.\n"); + printf( "NOT writing segments.\n" ); #else /* not TRILIBRARY */ - printf("NOT writing a .poly file.\n"); + printf( "NOT writing a .poly file.\n" ); #endif /* not TRILIBRARY */ - } - } else { + } + } + else { #ifdef TRILIBRARY - writepoly(&out->segmentlist, &out->segmentmarkerlist); - out->numberofholes = holes; - out->numberofregions = regions; - if (poly) { - out->holelist = in->holelist; - out->regionlist = in->regionlist; - } else { - out->holelist = (REAL *) NULL; - out->regionlist = (REAL *) NULL; - } + writepoly( &out->segmentlist, &out->segmentmarkerlist ); + out->numberofholes = holes; + out->numberofregions = regions; + if ( poly ) { + out->holelist = in->holelist; + out->regionlist = in->regionlist; + } + else { + out->holelist = (REAL *) NULL; + out->regionlist = (REAL *) NULL; + } #else /* not TRILIBRARY */ - writepoly(outpolyfilename, holearray, holes, regionarray, regions, - argc, argv); + writepoly( outpolyfilename, holearray, holes, regionarray, regions, + argc, argv ); #endif /* not TRILIBRARY */ - } - } + } + } #ifndef TRILIBRARY #ifndef CDT_ONLY - if (regions > 0) { - free(regionarray); - } + if ( regions > 0 ) { + free( regionarray ); + } #endif /* not CDT_ONLY */ - if (holes > 0) { - free(holearray); - } - if (geomview) { - writeoff(offfilename, argc, argv); - } + if ( holes > 0 ) { + free( holearray ); + } + if ( geomview ) { + writeoff( offfilename, argc, argv ); + } #endif /* not TRILIBRARY */ - if (edgesout) { + if ( edgesout ) { #ifdef TRILIBRARY - writeedges(&out->edgelist, &out->edgemarkerlist); + writeedges( &out->edgelist, &out->edgemarkerlist ); #else /* not TRILIBRARY */ - writeedges(edgefilename, argc, argv); + writeedges( edgefilename, argc, argv ); #endif /* not TRILIBRARY */ - } - if (voronoi) { + } + if ( voronoi ) { #ifdef TRILIBRARY - writevoronoi(&vorout->pointlist, &vorout->pointattributelist, - &vorout->pointmarkerlist, &vorout->edgelist, - &vorout->edgemarkerlist, &vorout->normlist); + writevoronoi( &vorout->pointlist, &vorout->pointattributelist, + &vorout->pointmarkerlist, &vorout->edgelist, + &vorout->edgemarkerlist, &vorout->normlist ); #else /* not TRILIBRARY */ - writevoronoi(vnodefilename, vedgefilename, argc, argv); + writevoronoi( vnodefilename, vedgefilename, argc, argv ); #endif /* not TRILIBRARY */ - } - if (neighbors) { + } + if ( neighbors ) { #ifdef TRILIBRARY - writeneighbors(&out->neighborlist); + writeneighbors( &out->neighborlist ); #else /* not TRILIBRARY */ - writeneighbors(neighborfilename, argc, argv); + writeneighbors( neighborfilename, argc, argv ); #endif /* not TRILIBRARY */ - } + } - if (!quiet) { + if ( !quiet ) { #ifndef NO_TIMER - gettimeofday(&tv6, &tz); - printf("\nOutput milliseconds: %ld\n", - 1000l * (tv6.tv_sec - tv5.tv_sec) - + (tv6.tv_usec - tv5.tv_usec) / 1000l); - printf("Total running milliseconds: %ld\n", - 1000l * (tv6.tv_sec - tv0.tv_sec) - + (tv6.tv_usec - tv0.tv_usec) / 1000l); + gettimeofday( &tv6, &tz ); + printf( "\nOutput milliseconds: %ld\n", + 1000l * ( tv6.tv_sec - tv5.tv_sec ) + + ( tv6.tv_usec - tv5.tv_usec ) / 1000l ); + printf( "Total running milliseconds: %ld\n", + 1000l * ( tv6.tv_sec - tv0.tv_sec ) + + ( tv6.tv_usec - tv0.tv_usec ) / 1000l ); #endif /* NO_TIMER */ - statistics(); - } + statistics(); + } #ifndef REDUCED - if (docheck) { - checkmesh(); - checkdelaunay(); - } + if ( docheck ) { + checkmesh(); + checkdelaunay(); + } #endif /* not REDUCED */ - triangledeinit(); + triangledeinit(); #ifndef TRILIBRARY - return 0; + return 0; #endif /* not TRILIBRARY */ } diff --git a/contrib/gtkgensurf/triangle.h b/contrib/gtkgensurf/triangle.h index e7d87d01..337da40c 100644 --- a/contrib/gtkgensurf/triangle.h +++ b/contrib/gtkgensurf/triangle.h @@ -250,38 +250,38 @@ extern "C" { #endif struct triangulateio { - REAL *pointlist; /* In / out */ - REAL *pointattributelist; /* In / out */ - int *pointmarkerlist; /* In / out */ - int numberofpoints; /* In / out */ - int numberofpointattributes; /* In / out */ + REAL *pointlist; /* In / out */ + REAL *pointattributelist; /* In / out */ + int *pointmarkerlist; /* In / out */ + int numberofpoints; /* In / out */ + int numberofpointattributes; /* In / out */ - int *trianglelist; /* In / out */ - REAL *triangleattributelist; /* In / out */ - REAL *trianglearealist; /* In only */ - int *neighborlist; /* Out only */ - int numberoftriangles; /* In / out */ - int numberofcorners; /* In / out */ - int numberoftriangleattributes; /* In / out */ + int *trianglelist; /* In / out */ + REAL *triangleattributelist; /* In / out */ + REAL *trianglearealist; /* In only */ + int *neighborlist; /* Out only */ + int numberoftriangles; /* In / out */ + int numberofcorners; /* In / out */ + int numberoftriangleattributes; /* In / out */ - int *segmentlist; /* In / out */ - int *segmentmarkerlist; /* In / out */ - int numberofsegments; /* In / out */ + int *segmentlist; /* In / out */ + int *segmentmarkerlist; /* In / out */ + int numberofsegments; /* In / out */ - REAL *holelist; /* In / pointer to array copied out */ - int numberofholes; /* In / copied out */ + REAL *holelist; /* In / pointer to array copied out */ + int numberofholes; /* In / copied out */ - REAL *regionlist; /* In / pointer to array copied out */ - int numberofregions; /* In / copied out */ + REAL *regionlist; /* In / pointer to array copied out */ + int numberofregions; /* In / copied out */ - int *edgelist; /* Out only */ - int *edgemarkerlist; /* Not used with Voronoi diagram; out only */ - REAL *normlist; /* Used only with Voronoi diagram; out only */ - int numberofedges; /* Out only */ + int *edgelist; /* Out only */ + int *edgemarkerlist; /* Not used with Voronoi diagram; out only */ + REAL *normlist; /* Used only with Voronoi diagram; out only */ + int numberofedges; /* Out only */ }; -void triangulate(char *, struct triangulateio *, struct triangulateio *, - struct triangulateio *); +void triangulate( char *, struct triangulateio *, struct triangulateio *, + struct triangulateio * ); #ifdef __cplusplus } diff --git a/contrib/gtkgensurf/view.cpp b/contrib/gtkgensurf/view.cpp index 88acc4bd..ba0c43d5 100644 --- a/contrib/gtkgensurf/view.cpp +++ b/contrib/gtkgensurf/view.cpp @@ -1,21 +1,21 @@ /* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com + GenSurf plugin for GtkRadiant + Copyright (C) 2001 David Hyde, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include #include @@ -28,13 +28,13 @@ extern double backface; extern double dh, dv; extern double xmin,xmax,ymin,ymax,zmin,zmax; -double SF, SFG; // Graphics scale factors -double XLo, XHi, YLo, YHi, ZLo, ZHi; -double yaw,roll; -double elevation,azimuth; -int cxChar = 10, cyChar = 16; -int X0, Y0; -int X0G, Y0G; +double SF, SFG; // Graphics scale factors +double XLo, XHi, YLo, YHi, ZLo, ZHi; +double yaw,roll; +double elevation,azimuth; +int cxChar = 10, cyChar = 16; +int X0, Y0; +int X0G, Y0G; static Rect rcCoord; // where X= Y= is drawn static Rect rcGrid; // rectangle within rcLower that forms the border of the grid, plus @@ -42,1138 +42,1121 @@ static Rect rcGrid; // rectangle within rcLower that forms the border of the static Rect rcLower; // lower half of window, where plan view is drawn static Rect rcUpper; // upper half or entire window, where isometric projection is drawn -void vertex_selected (); -void texfont_init (); -void texfont_write (const char *text, int l, int t); +void vertex_selected(); +void texfont_init(); +void texfont_write( const char *text, int l, int t ); #define PEN_GRID { \ - g_GLTable.m_pfn_qglLineWidth (1); \ - g_GLTable.m_pfn_qglColor3f (0, 1, 0); \ - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); } + g_GLTable.m_pfn_qglLineWidth( 1 ); \ + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); \ + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); } #define PEN_RED { \ - g_GLTable.m_pfn_qglLineWidth (2); \ - g_GLTable.m_pfn_qglColor3f (1, 0, 0); \ - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); } + g_GLTable.m_pfn_qglLineWidth( 2 ); \ + g_GLTable.m_pfn_qglColor3f( 1, 0, 0 ); \ + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); } #define PEN_DASH { \ - g_GLTable.m_pfn_qglLineWidth (1); \ - g_GLTable.m_pfn_qglColor3f (0, 1, 0); \ - g_GLTable.m_pfn_qglLineStipple (1, 0xF0F0); \ - g_GLTable.m_pfn_qglEnable (GL_LINE_STIPPLE); } - -#define DRAW_QUAD(rc,r,g,b) { \ - g_GLTable.m_pfn_qglBegin (GL_QUADS); \ - g_GLTable.m_pfn_qglColor3f (0,1,0); \ - g_GLTable.m_pfn_qglVertex2i (rc.left-1, rc.bottom); \ - g_GLTable.m_pfn_qglVertex2i (rc.right, rc.bottom); \ - g_GLTable.m_pfn_qglVertex2i (rc.right, rc.top+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.left-1, rc.top+1); \ - g_GLTable.m_pfn_qglColor3f (r,g,b); \ - g_GLTable.m_pfn_qglVertex2i (rc.left, rc.bottom+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.right-1, rc.bottom+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.right-1, rc.top); \ - g_GLTable.m_pfn_qglVertex2i (rc.left, rc.top); \ - g_GLTable.m_pfn_qglEnd (); } + g_GLTable.m_pfn_qglLineWidth( 1 ); \ + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); \ + g_GLTable.m_pfn_qglLineStipple( 1, 0xF0F0 ); \ + g_GLTable.m_pfn_qglEnable( GL_LINE_STIPPLE ); } + +#define DRAW_QUAD( rc,r,g,b ) { \ + g_GLTable.m_pfn_qglBegin( GL_QUADS ); \ + g_GLTable.m_pfn_qglColor3f( 0,1,0 ); \ + g_GLTable.m_pfn_qglVertex2i( rc.left - 1, rc.bottom ); \ + g_GLTable.m_pfn_qglVertex2i( rc.right, rc.bottom ); \ + g_GLTable.m_pfn_qglVertex2i( rc.right, rc.top + 1 ); \ + g_GLTable.m_pfn_qglVertex2i( rc.left - 1, rc.top + 1 ); \ + g_GLTable.m_pfn_qglColor3f( r,g,b ); \ + g_GLTable.m_pfn_qglVertex2i( rc.left, rc.bottom + 1 ); \ + g_GLTable.m_pfn_qglVertex2i( rc.right - 1, rc.bottom + 1 ); \ + g_GLTable.m_pfn_qglVertex2i( rc.right - 1, rc.top ); \ + g_GLTable.m_pfn_qglVertex2i( rc.left, rc.top ); \ + g_GLTable.m_pfn_qglEnd(); } #ifndef ISOMETRIC -double D=65536.; -double ct[3],st[3]; -double Hhi, Hlo, Vhi, Vlo; +double D = 65536.; +double ct[3],st[3]; +double Hhi, Hlo, Vhi, Vlo; #endif #define SUBDIVS 6 -void ShowPreview () -{ - if (Preview) - { - if (g_pWndPreview == NULL) - CreateViewWindow (); - gtk_widget_show (g_pWndPreview); +void ShowPreview(){ + if ( Preview ) { + if ( g_pWndPreview == NULL ) { + CreateViewWindow(); + } + gtk_widget_show( g_pWndPreview ); - UpdatePreview (true); - } - else - gtk_widget_hide (g_pWndPreview); + UpdatePreview( true ); + } + else{ + gtk_widget_hide( g_pWndPreview ); + } } -static void draw_preview () -{ - int width = g_pPreviewWidget->allocation.width, height = g_pPreviewWidget->allocation.height; - - g_GLTable.m_pfn_qglClearColor (0, 0, 0, 1); - g_GLTable.m_pfn_qglViewport (0, 0, width, height); - g_GLTable.m_pfn_qglMatrixMode (GL_PROJECTION); - g_GLTable.m_pfn_qglLoadIdentity (); - g_GLTable.m_pfn_qglOrtho (0, width, 0, height, -1, 1); - g_GLTable.m_pfn_qglClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); - +static void draw_preview(){ + int width = g_pPreviewWidget->allocation.width, height = g_pPreviewWidget->allocation.height; + + g_GLTable.m_pfn_qglClearColor( 0, 0, 0, 1 ); + g_GLTable.m_pfn_qglViewport( 0, 0, width, height ); + g_GLTable.m_pfn_qglMatrixMode( GL_PROJECTION ); + g_GLTable.m_pfn_qglLoadIdentity(); + g_GLTable.m_pfn_qglOrtho( 0, width, 0, height, -1, 1 ); + g_GLTable.m_pfn_qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + // ^Fishman - Antializing for the preview window. - if (Antialiasing) - { - g_GLTable.m_pfn_qglEnable(GL_BLEND); - g_GLTable.m_pfn_qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - g_GLTable.m_pfn_qglEnable(GL_LINE_SMOOTH); + if ( Antialiasing ) { + g_GLTable.m_pfn_qglEnable( GL_BLEND ); + g_GLTable.m_pfn_qglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + g_GLTable.m_pfn_qglEnable( GL_LINE_SMOOTH ); } else { - g_GLTable.m_pfn_qglDisable(GL_BLEND); - g_GLTable.m_pfn_qglDisable(GL_LINE_SMOOTH); + g_GLTable.m_pfn_qglDisable( GL_BLEND ); + g_GLTable.m_pfn_qglDisable( GL_LINE_SMOOTH ); } - texfont_init (); - - if (!ValidSurface ()) - return; - - rcUpper.left = 0; - rcUpper.right = width; - rcUpper.bottom = 0; - rcUpper.top = height; - rcLower.left = 0; - rcLower.right = width; - rcLower.bottom = 0; - rcLower.top = height; - - if (VertexMode) - { - rcUpper.bottom = rcUpper.top/2; - DrawPreview (rcUpper); - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (rcUpper.left, rcUpper.bottom); - g_GLTable.m_pfn_qglVertex2i (rcUpper.right, rcUpper.bottom); - g_GLTable.m_pfn_qglEnd (); - rcLower.top = rcUpper.bottom-1; - DrawGrid (rcLower); - rcCoord.left = rcLower.left; - rcCoord.right = rcLower.right; - rcCoord.bottom = rcLower.bottom; - rcCoord.top = rcLower.top; - rcCoord.top = rcCoord.bottom+cyChar; - rcCoord.right = rcCoord.left + 15*cxChar; - rcGrid.left = X0G - 3; - rcGrid.bottom = Y0G - 3; - rcGrid.right = X0G + (int)(SFG*(Hur-Hll)) + 3; - rcGrid.top = Y0G + (int)(SFG*(Vur-Vll)) + 3; - } - else - DrawPreview (rcUpper); + texfont_init(); + + if ( !ValidSurface() ) { + return; + } + + rcUpper.left = 0; + rcUpper.right = width; + rcUpper.bottom = 0; + rcUpper.top = height; + rcLower.left = 0; + rcLower.right = width; + rcLower.bottom = 0; + rcLower.top = height; + + if ( VertexMode ) { + rcUpper.bottom = rcUpper.top / 2; + DrawPreview( rcUpper ); + g_GLTable.m_pfn_qglBegin( GL_LINES ); + g_GLTable.m_pfn_qglVertex2i( rcUpper.left, rcUpper.bottom ); + g_GLTable.m_pfn_qglVertex2i( rcUpper.right, rcUpper.bottom ); + g_GLTable.m_pfn_qglEnd(); + rcLower.top = rcUpper.bottom - 1; + DrawGrid( rcLower ); + rcCoord.left = rcLower.left; + rcCoord.right = rcLower.right; + rcCoord.bottom = rcLower.bottom; + rcCoord.top = rcLower.top; + rcCoord.top = rcCoord.bottom + cyChar; + rcCoord.right = rcCoord.left + 15 * cxChar; + rcGrid.left = X0G - 3; + rcGrid.bottom = Y0G - 3; + rcGrid.right = X0G + (int)( SFG * ( Hur - Hll ) ) + 3; + rcGrid.top = Y0G + (int)( SFG * ( Vur - Vll ) ) + 3; + } + else{ + DrawPreview( rcUpper ); + } } -static gint expose (GtkWidget *widget, GdkEventExpose *event, gpointer data) -{ - if (event->count > 0) - return TRUE; +static gint expose( GtkWidget *widget, GdkEventExpose *event, gpointer data ){ + if ( event->count > 0 ) { + return TRUE; + } - if (!g_UIGtkTable.m_pfn_glwidget_make_current (g_pPreviewWidget)) - { - g_FuncTable.m_pfnSysPrintf ("GtkGenSurf: glMakeCurrent failed\n"); - return TRUE; - } + if ( !g_UIGtkTable.m_pfn_glwidget_make_current( g_pPreviewWidget ) ) { + g_FuncTable.m_pfnSysPrintf( "GtkGenSurf: glMakeCurrent failed\n" ); + return TRUE; + } - draw_preview (); + draw_preview(); - g_UIGtkTable.m_pfn_glwidget_swap_buffers (g_pPreviewWidget); - g_GLTable.m_pfn_QE_CheckOpenGLForErrors (); + g_UIGtkTable.m_pfn_glwidget_swap_buffers( g_pPreviewWidget ); + g_GLTable.m_pfn_QE_CheckOpenGLForErrors(); - return TRUE; + return TRUE; } -static void button_press (GtkWidget *widget, GdkEventButton *event, gpointer data) -{ - Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; - bool Selected; - double x,y; - int i, j, k, ks; - int i0, i1, j0, j1; - - if ((!VertexMode) || (event->button != 1)) - return; - - if (!PtInRect (&rcGrid,pt)) - { - gdk_beep (); - return; - } - - x = Hll + (pt.x-X0G)/SFG; - y = Vur - (pt.y-Y0G)/SFG; - i = (int)(floor( (x-Hll)/dh - 0.5) + 1); - j = (int)(floor( (y-Vll)/dv - 0.5) + 1); - if (i < 0 || i > NH || j < 0 || j > NV) - { - gdk_beep (); - return; - } - - if(!CanEdit(i,j)) - { - gdk_beep (); - return; - } - - // Control key pressed - add this point, or remove it if already selected - if ((event->state & GDK_CONTROL_MASK) != 0) - { - Selected = FALSE; - if (NumVerticesSelected) - { - for (k=0; kstate & GDK_SHIFT_MASK) != 0) - { - if (NumVerticesSelected) - { - NumVerticesSelected = 1; - i0 = min(Vertex[0].i, i); - i1 = max(Vertex[0].i, i); - j0 = min(Vertex[0].j, j); - j1 = max(Vertex[0].j, j); - for(i=i0; i<=i1; i++) - { - for(j=j0; j<=j1; j++) - { - if(i==0 && j==0 ) continue; - if(i==NH && j==0 ) continue; - if(i==0 && j==NV) continue; - if(i==NH && j==NV) continue; - if(i != Vertex[0].i || j != Vertex[0].j) - { - Vertex[NumVerticesSelected].i = i; - Vertex[NumVerticesSelected].j = j; - NumVerticesSelected++; - } - } - } - } - else - { - Vertex[0].i = i; - Vertex[0].j = j; - NumVerticesSelected = 1; - } - } - else - { - Vertex[0].i = i; - Vertex[0].j = j; - NumVerticesSelected = 1; - } - - vertex_selected (); +static void button_press( GtkWidget *widget, GdkEventButton *event, gpointer data ){ + Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; + bool Selected; + double x,y; + int i, j, k, ks; + int i0, i1, j0, j1; + + if ( ( !VertexMode ) || ( event->button != 1 ) ) { + return; + } + + if ( !PtInRect( &rcGrid,pt ) ) { + gdk_beep(); + return; + } + + x = Hll + ( pt.x - X0G ) / SFG; + y = Vur - ( pt.y - Y0G ) / SFG; + i = (int)( floor( ( x - Hll ) / dh - 0.5 ) + 1 ); + j = (int)( floor( ( y - Vll ) / dv - 0.5 ) + 1 ); + if ( i < 0 || i > NH || j < 0 || j > NV ) { + gdk_beep(); + return; + } + + if ( !CanEdit( i,j ) ) { + gdk_beep(); + return; + } + + // Control key pressed - add this point, or remove it if already selected + if ( ( event->state & GDK_CONTROL_MASK ) != 0 ) { + Selected = FALSE; + if ( NumVerticesSelected ) { + for ( k = 0; k < NumVerticesSelected && !Selected; k++ ) + { + if ( Vertex[k].i == i && Vertex[k].j == j ) { + Selected = TRUE; + ks = k; + } + } + } + + // Already selected - unselect it. + if ( Selected ) { + if ( ks < NumVerticesSelected ) { + for ( k = ks; k < NumVerticesSelected - 1; k++ ) + { + Vertex[k].i = Vertex[k + 1].i; + Vertex[k].j = Vertex[k + 1].j; + } + NumVerticesSelected--; + } + } + else + { + Vertex[NumVerticesSelected].i = i; + Vertex[NumVerticesSelected].j = j; + NumVerticesSelected++; + } + } + else if ( ( event->state & GDK_SHIFT_MASK ) != 0 ) { + if ( NumVerticesSelected ) { + NumVerticesSelected = 1; + i0 = min( Vertex[0].i, i ); + i1 = max( Vertex[0].i, i ); + j0 = min( Vertex[0].j, j ); + j1 = max( Vertex[0].j, j ); + for ( i = i0; i <= i1; i++ ) + { + for ( j = j0; j <= j1; j++ ) + { + if ( i == 0 && j == 0 ) { + continue; + } + if ( i == NH && j == 0 ) { + continue; + } + if ( i == 0 && j == NV ) { + continue; + } + if ( i == NH && j == NV ) { + continue; + } + if ( i != Vertex[0].i || j != Vertex[0].j ) { + Vertex[NumVerticesSelected].i = i; + Vertex[NumVerticesSelected].j = j; + NumVerticesSelected++; + } + } + } + } + else + { + Vertex[0].i = i; + Vertex[0].j = j; + NumVerticesSelected = 1; + } + } + else + { + Vertex[0].i = i; + Vertex[0].j = j; + NumVerticesSelected = 1; + } + + vertex_selected(); } -static void motion (GtkWidget *widget, GdkEventMotion *event, gpointer data) -{ - Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; - - if (!VertexMode) - return; - - if (!g_UIGtkTable.m_pfn_glwidget_make_current (g_pPreviewWidget)) - { - g_FuncTable.m_pfnSysPrintf ("GtkGenSurf: glMakeCurrent failed\n"); - return; - } - - g_GLTable.m_pfn_qglEnable (GL_SCISSOR_TEST); - g_GLTable.m_pfn_qglScissor (rcCoord.left, rcCoord.bottom, rcCoord.right-rcCoord.left, - rcCoord.top-rcCoord.bottom); - g_GLTable.m_pfn_qglClear (GL_COLOR_BUFFER_BIT); - - if (PtInRect(&rcGrid,pt)) - { - GdkCursor *cursor = gdk_cursor_new (GDK_CROSS); - gdk_window_set_cursor (g_pWndPreview->window, cursor); - gdk_cursor_unref (cursor); - - char Text[32]; - int x, y; - - x = (int)(Hll + (pt.x-X0G)/SFG); - y = (int)(Vur - (pt.y-Y0G)/SFG); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - sprintf(Text," x=%d, z=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - break; - case PLANE_YZ0: - case PLANE_YZ1: - sprintf(Text," y=%d, z=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - break; - default: - sprintf(Text," x=%d, y=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - } - - texfont_write (Text, rcCoord.left, rcCoord.top); - } - else - { - gdk_window_set_cursor (g_pWndPreview->window, NULL); - } - - g_UIGtkTable.m_pfn_glwidget_swap_buffers (g_pPreviewWidget); - g_GLTable.m_pfn_QE_CheckOpenGLForErrors (); - g_GLTable.m_pfn_qglDisable (GL_SCISSOR_TEST); +static void motion( GtkWidget *widget, GdkEventMotion *event, gpointer data ){ + Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; + + if ( !VertexMode ) { + return; + } + + if ( !g_UIGtkTable.m_pfn_glwidget_make_current( g_pPreviewWidget ) ) { + g_FuncTable.m_pfnSysPrintf( "GtkGenSurf: glMakeCurrent failed\n" ); + return; + } + + g_GLTable.m_pfn_qglEnable( GL_SCISSOR_TEST ); + g_GLTable.m_pfn_qglScissor( rcCoord.left, rcCoord.bottom, rcCoord.right - rcCoord.left, + rcCoord.top - rcCoord.bottom ); + g_GLTable.m_pfn_qglClear( GL_COLOR_BUFFER_BIT ); + + if ( PtInRect( &rcGrid,pt ) ) { + GdkCursor *cursor = gdk_cursor_new( GDK_CROSS ); + gdk_window_set_cursor( g_pWndPreview->window, cursor ); + gdk_cursor_unref( cursor ); + + char Text[32]; + int x, y; + + x = (int)( Hll + ( pt.x - X0G ) / SFG ); + y = (int)( Vur - ( pt.y - Y0G ) / SFG ); + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + sprintf( Text," x=%d, z=%d ",(int)( floor( x - 0.5 ) + 1. ),(int)( floor( y - 0.5 ) + 1. ) ); + break; + case PLANE_YZ0: + case PLANE_YZ1: + sprintf( Text," y=%d, z=%d ",(int)( floor( x - 0.5 ) + 1. ),(int)( floor( y - 0.5 ) + 1. ) ); + break; + default: + sprintf( Text," x=%d, y=%d ",(int)( floor( x - 0.5 ) + 1. ),(int)( floor( y - 0.5 ) + 1. ) ); + } + + texfont_write( Text, rcCoord.left, rcCoord.top ); + } + else + { + gdk_window_set_cursor( g_pWndPreview->window, NULL ); + } + + g_UIGtkTable.m_pfn_glwidget_swap_buffers( g_pPreviewWidget ); + g_GLTable.m_pfn_QE_CheckOpenGLForErrors(); + g_GLTable.m_pfn_qglDisable( GL_SCISSOR_TEST ); } -static gint preview_close (GtkWidget *widget, gpointer data) -{ - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "main_preview")), FALSE); - return TRUE; +static gint preview_close( GtkWidget *widget, gpointer data ){ + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( g_object_get_data( G_OBJECT( g_pWnd ), "main_preview" ) ), FALSE ); + return TRUE; } -static void preview_focusout (GtkSpinButton *spin, GdkEventFocus *event, double *data) -{ - *data = DegreesToRadians ((double)(gtk_spin_button_get_value_as_int (spin) % 360)); - UpdatePreview (false); +static void preview_focusout( GtkSpinButton *spin, GdkEventFocus *event, double *data ){ + *data = DegreesToRadians( (double)( gtk_spin_button_get_value_as_int( spin ) % 360 ) ); + UpdatePreview( false ); } -static gint doublevariable_spinfocusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) -{ - preview_focusout(GTK_SPIN_BUTTON(widget), event, reinterpret_cast(data)); - return FALSE; +static gint doublevariable_spinfocusout( GtkWidget* widget, GdkEventFocus* event, gpointer data ){ + preview_focusout( GTK_SPIN_BUTTON( widget ), event, reinterpret_cast( data ) ); + return FALSE; } -static void preview_spin (GtkAdjustment *adj, double *data) -{ - *data = DegreesToRadians (adj->value); - UpdatePreview (false); +static void preview_spin( GtkAdjustment *adj, double *data ){ + *data = DegreesToRadians( adj->value ); + UpdatePreview( false ); } -void CreateViewWindow () -{ - GtkWidget *dlg, *vbox, *hbox, *label, *spin, *frame; - GtkObject *adj; +void CreateViewWindow(){ + GtkWidget *dlg, *vbox, *hbox, *label, *spin, *frame; + GtkObject *adj; #ifndef ISOMETRIC - elevation = PI/6.; - azimuth = PI/6.; + elevation = PI / 6.; + azimuth = PI / 6.; #endif - g_pWndPreview = dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "GtkGenSurf Preview"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", GTK_SIGNAL_FUNC (preview_close), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (g_pWnd)); - gtk_window_set_default_size (GTK_WINDOW (dlg), 300, 400); + g_pWndPreview = dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( dlg ), "GtkGenSurf Preview" ); + gtk_signal_connect( GTK_OBJECT( dlg ), "delete_event", GTK_SIGNAL_FUNC( preview_close ), NULL ); + gtk_signal_connect( GTK_OBJECT( dlg ), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_transient_for( GTK_WINDOW( dlg ), GTK_WINDOW( g_pWnd ) ); + gtk_window_set_default_size( GTK_WINDOW( dlg ), 300, 400 ); - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); + vbox = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( dlg ), vbox ); #ifndef ISOMETRIC - hbox = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 0); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 3); - - label = gtk_label_new ("Elevation"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (30, -90, 90, 1, 10, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (preview_spin), &elevation); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (hbox), spin, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (doublevariable_spinfocusout), &elevation); - - adj = gtk_adjustment_new (30, 0, 359, 1, 10, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (preview_spin), &azimuth); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin), TRUE); - gtk_box_pack_end (GTK_BOX (hbox), spin, FALSE, TRUE, 0); - - label = gtk_label_new ("Azimuth"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_box_pack_end (GTK_BOX (hbox), label, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (doublevariable_spinfocusout), &azimuth); + hbox = gtk_hbox_new( TRUE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, TRUE, 0 ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ), 3 ); + + label = gtk_label_new( "Elevation" ); + gtk_widget_show( label ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_box_pack_start( GTK_BOX( hbox ), label, FALSE, TRUE, 0 ); + + adj = gtk_adjustment_new( 30, -90, 90, 1, 10, 0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( preview_spin ), &elevation ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_box_pack_start( GTK_BOX( hbox ), spin, FALSE, TRUE, 0 ); + g_signal_connect( G_OBJECT( spin ), "focus_out_event", G_CALLBACK( doublevariable_spinfocusout ), &elevation ); + + adj = gtk_adjustment_new( 30, 0, 359, 1, 10, 0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( preview_spin ), &azimuth ); + spin = gtk_spin_button_new( GTK_ADJUSTMENT( adj ), 1, 0 ); + gtk_widget_show( spin ); + gtk_spin_button_set_wrap( GTK_SPIN_BUTTON( spin ), TRUE ); + gtk_box_pack_end( GTK_BOX( hbox ), spin, FALSE, TRUE, 0 ); + + label = gtk_label_new( "Azimuth" ); + gtk_widget_show( label ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_box_pack_end( GTK_BOX( hbox ), label, FALSE, TRUE, 0 ); + g_signal_connect( G_OBJECT( spin ), "focus_out_event", G_CALLBACK( doublevariable_spinfocusout ), &azimuth ); #endif - frame = gtk_frame_new (NULL); - gtk_widget_show (frame); - gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); + frame = gtk_frame_new( NULL ); + gtk_widget_show( frame ); + gtk_frame_set_shadow_type( GTK_FRAME( frame ), GTK_SHADOW_IN ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, TRUE, TRUE, 0 ); - g_pPreviewWidget = g_UIGtkTable.m_pfn_glwidget_new (FALSE, NULL); + g_pPreviewWidget = g_UIGtkTable.m_pfn_glwidget_new( FALSE, NULL ); - gtk_widget_set_events (g_pPreviewWidget, GDK_EXPOSURE_MASK|GDK_BUTTON_PRESS_MASK|GDK_POINTER_MOTION_MASK); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "expose_event", GTK_SIGNAL_FUNC (expose), NULL); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "motion_notify_event", GTK_SIGNAL_FUNC (motion), NULL); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "button_press_event", - GTK_SIGNAL_FUNC (button_press), NULL); + gtk_widget_set_events( g_pPreviewWidget, GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK ); + gtk_signal_connect( GTK_OBJECT( g_pPreviewWidget ), "expose_event", GTK_SIGNAL_FUNC( expose ), NULL ); + gtk_signal_connect( GTK_OBJECT( g_pPreviewWidget ), "motion_notify_event", GTK_SIGNAL_FUNC( motion ), NULL ); + gtk_signal_connect( GTK_OBJECT( g_pPreviewWidget ), "button_press_event", + GTK_SIGNAL_FUNC( button_press ), NULL ); - gtk_widget_show (g_pPreviewWidget); - gtk_container_add (GTK_CONTAINER (frame), g_pPreviewWidget); + gtk_widget_show( g_pPreviewWidget ); + gtk_container_add( GTK_CONTAINER( frame ), g_pPreviewWidget ); - if (Preview) - gtk_widget_show (g_pWndPreview); + if ( Preview ) { + gtk_widget_show( g_pWndPreview ); + } - UpdatePreview (true); + UpdatePreview( true ); } //============================================================= /* DrawPreview */ -void DrawPreview (Rect rc) -{ +void DrawPreview( Rect rc ){ #define COSXA 0.8660254037844 #define SINXA 0.5 #define COSYA 0.8660254037844 #define SINYA 0.5 - double L; - double x,y; - int i, j; - Point pt[8]; - XYZ v[8]; - char axis[3][2] = {"X","Y","Z"}; + double L; + double x,y; + int i, j; + Point pt[8]; + XYZ v[8]; + char axis[3][2] = {"X","Y","Z"}; #ifndef ISOMETRIC - evaluate(); + evaluate(); #endif - XLo = xmin; - XHi = xmax; - YLo = ymin; - YHi = ymax; - ZLo = zmin; - ZHi = zmax; - switch (Plane) - { - case PLANE_XY1: - ZHi = backface; - break; - case PLANE_XZ0: - YLo = backface; - break; - case PLANE_XZ1: - YHi = backface; - break; - case PLANE_YZ0: - XLo = backface; - break; - case PLANE_YZ1: - XHi = backface; - break; - default: - ZLo = backface; - } - - - - GetScaleFactor(rc); + XLo = xmin; + XHi = xmax; + YLo = ymin; + YHi = ymax; + ZLo = zmin; + ZHi = zmax; + switch ( Plane ) + { + case PLANE_XY1: + ZHi = backface; + break; + case PLANE_XZ0: + YLo = backface; + break; + case PLANE_XZ1: + YHi = backface; + break; + case PLANE_YZ0: + XLo = backface; + break; + case PLANE_YZ1: + XHi = backface; + break; + default: + ZLo = backface; + } + + + + GetScaleFactor( rc ); //PEN_GRID - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - - if (Decimate > 0 && (Game != QUAKE3 || UsePatches==0) ) - { - XYZ *vv; - - vv = (XYZ *) malloc(gNumNodes * sizeof(XYZ)); - for(i=0; i 0 && ( Game != QUAKE3 || UsePatches == 0 ) ) { + XYZ *vv; + + vv = (XYZ *) malloc( gNumNodes * sizeof( XYZ ) ); + for ( i = 0; i < gNumNodes; i++ ) + { + for ( j = 0; j < 3; j++ ) + vv[i].p[j] = (double)( gNode[i].p[j] ); + project( &vv[i] ); + } + + for ( i = 0; i < gNumTris; i++ ) + { + for ( j = 0; j < 3; j++ ) + Scale( rc,vv[gTri[i].v[j]],&pt[j] ); + + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + g_GLTable.m_pfn_qglVertex2i( pt[1].x, pt[1].y ); + g_GLTable.m_pfn_qglVertex2i( pt[2].x, pt[2].y ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + g_GLTable.m_pfn_qglEnd(); + } + free( vv ); + } + else if ( Game == QUAKE3 && UsePatches != 0 ) { + int axis, ii, jj, k; + float u, v; + XYZ uv[3][3]; + XYZ Ctrl[3],out; + + switch ( Plane ) + { + case PLANE_XY0: + case PLANE_XY1: + k = 2; + break; + case PLANE_XZ0: + case PLANE_XZ1: + k = 1; + break; + default: + k = 0; + } + for ( i = 0; i < NH; i += 2 ) + { + for ( j = 0; j < NV; j += 2 ) + { + VectorCopy( xyz[i ][j ].p,uv[0][0].p ); + VectorCopy( xyz[i + 1][j ].p,uv[1][0].p ); + VectorCopy( xyz[i + 2][j ].p,uv[2][0].p ); + VectorCopy( xyz[i ][j + 1].p,uv[0][1].p ); + VectorCopy( xyz[i + 1][j + 1].p,uv[1][1].p ); + VectorCopy( xyz[i + 2][j + 1].p,uv[2][1].p ); + VectorCopy( xyz[i ][j + 2].p,uv[0][2].p ); + VectorCopy( xyz[i + 1][j + 2].p,uv[1][2].p ); + VectorCopy( xyz[i + 2][j + 2].p,uv[2][2].p ); + uv[1][0].p[k] = ( 4 * xyz[i + 1][j ].p[k] - xyz[i ][j ].p[k] - xyz[i + 2][j ].p[k] ) / 2; + uv[0][1].p[k] = ( 4 * xyz[i ][j + 1].p[k] - xyz[i ][j ].p[k] - xyz[i ][j + 2].p[k] ) / 2; + uv[2][1].p[k] = ( 4 * xyz[i + 2][j + 1].p[k] - xyz[i + 2][j ].p[k] - xyz[i + 2][j + 2].p[k] ) / 2; + uv[1][2].p[k] = ( 4 * xyz[i + 1][j + 2].p[k] - xyz[i ][j + 2].p[k] - xyz[i + 2][j + 2].p[k] ) / 2; + uv[1][1].p[k] = ( 16 * xyz[i + 1][j + 1].p[k] - + xyz[i ][j ].p[k] - 2 * xyz[i + 1][j ].p[k] - xyz[i + 2][j ].p[k] - + 2 * xyz[i ][j + 1].p[k] - 2 * xyz[i + 2][j + 1].p[k] - + xyz[i ][j + 2].p[k] - 2 * xyz[i + 1][j + 2].p[k] - xyz[i + 2][j + 2].p[k] ) / 4; + + for ( ii = 0; ii <= SUBDIVS; ii++ ) + { + if ( ii == 0 || ii == SUBDIVS / 2 || ii == SUBDIVS ) { + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); + // PEN_GRID + } + else + { + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglLineStipple( 1, 0xF0F0 ); + g_GLTable.m_pfn_qglEnable( GL_LINE_STIPPLE ); + // PEN_DASH + } + + u = (float)( ii ) / (float)( SUBDIVS ); + for ( jj = 0; jj < 3; jj++ ) + { + for ( axis = 0; axis < 3; axis++ ) { - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - // PEN_GRID + float a, b, c; + float qA, qB, qC; + a = (float)uv[0][jj].p[axis]; + b = (float)uv[1][jj].p[axis]; + c = (float)uv[2][jj].p[axis]; + qA = a - 2 * b + c; + qB = 2 * b - 2 * a; + qC = a; + Ctrl[jj].p[axis] = qA * u * u + qB * u + qC; } - else + } + VectorCopy( Ctrl[0].p,out.p ); + project( &out ); + Scale( rc,out,&pt[0] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + for ( jj = 1; jj <= SUBDIVS; jj++ ) + { + v = (float)( jj ) / (float)( SUBDIVS ); + for ( axis = 0 ; axis < 3 ; axis++ ) { - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglLineStipple (1, 0xF0F0); - g_GLTable.m_pfn_qglEnable (GL_LINE_STIPPLE); - // PEN_DASH + float a, b, c; + float qA, qB, qC; + a = (float)Ctrl[0].p[axis]; + b = (float)Ctrl[1].p[axis]; + c = (float)Ctrl[2].p[axis]; + qA = a - 2 * b + c; + qB = 2 * b - 2 * a; + qC = a; + out.p[axis] = qA * v * v + qB * v + qC; } - - u = (float)(ii)/(float)(SUBDIVS); - for(jj=0; jj<3; jj++) - { - for(axis=0; axis<3; axis++) - { - float a, b, c; - float qA, qB, qC; - a = (float)uv[0][jj].p[axis]; - b = (float)uv[1][jj].p[axis]; - c = (float)uv[2][jj].p[axis]; - qA = a - 2 * b + c; - qB = 2 * b - 2 * a; - qC = a; - Ctrl[jj].p[axis] = qA * u * u + qB * u + qC; - } - } - VectorCopy(Ctrl[0].p,out.p); - project(&out); - Scale(rc,out,&pt[0]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - for(jj=1; jj<=SUBDIVS; jj++) - { - v = (float)(jj)/(float)(SUBDIVS); - for (axis = 0 ; axis < 3 ; axis++) - { - float a, b, c; - float qA, qB, qC; - a = (float)Ctrl[0].p[axis]; - b = (float)Ctrl[1].p[axis]; - c = (float)Ctrl[2].p[axis]; - qA = a - 2 * b + c; - qB = 2 * b - 2 * a; - qC = a; - out.p[axis] = qA * v * v + qB * v + qC; - } - project(&out); - Scale(rc,out,&pt[0]); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - } - for(jj=0; jj<=SUBDIVS; jj++) - { - if(jj==0 || jj==SUBDIVS/2 || jj==SUBDIVS) + project( &out ); + Scale( rc,out,&pt[0] ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + } + g_GLTable.m_pfn_qglEnd(); + } + for ( jj = 0; jj <= SUBDIVS; jj++ ) + { + if ( jj == 0 || jj == SUBDIVS / 2 || jj == SUBDIVS ) { + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); + // PEN_GRID + } + else + { + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglLineStipple( 1, 0xF0F0 ); + g_GLTable.m_pfn_qglEnable( GL_LINE_STIPPLE ); + // PEN_DASH + } + + v = (float)( jj ) / (float)( SUBDIVS ); + for ( ii = 0; ii < 3; ii++ ) + { + for ( axis = 0; axis < 3; axis++ ) { - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - // PEN_GRID + float a, b, c; + float qA, qB, qC; + a = (float)uv[ii][0].p[axis]; + b = (float)uv[ii][1].p[axis]; + c = (float)uv[ii][2].p[axis]; + qA = a - 2 * b + c; + qB = 2 * b - 2 * a; + qC = a; + Ctrl[ii].p[axis] = qA * v * v + qB * v + qC; } - else + } + VectorCopy( Ctrl[0].p,out.p ); + project( &out ); + Scale( rc,out,&pt[0] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + for ( ii = 1; ii <= SUBDIVS; ii++ ) + { + u = (float)( ii ) / (float)( SUBDIVS ); + for ( axis = 0 ; axis < 3 ; axis++ ) { - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglLineStipple (1, 0xF0F0); - g_GLTable.m_pfn_qglEnable (GL_LINE_STIPPLE); - // PEN_DASH + float a, b, c; + float qA, qB, qC; + a = (float)Ctrl[0].p[axis]; + b = (float)Ctrl[1].p[axis]; + c = (float)Ctrl[2].p[axis]; + qA = a - 2 * b + c; + qB = 2 * b - 2 * a; + qC = a; + out.p[axis] = qA * u * u + qB * u + qC; } + project( &out ); + Scale( rc,out,&pt[0] ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + } + g_GLTable.m_pfn_qglEnd(); + } + } + } + } + else + { + for ( i = 0; i <= NH; i++ ) + { + Scale( rc,xyz[i][0],&pt[0] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + for ( j = 1; j <= NV; j++ ) + { + Scale( rc,xyz[i][j],&pt[0] ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + } + g_GLTable.m_pfn_qglEnd(); + } + for ( j = 0; j <= NV; j++ ) + { + Scale( rc,xyz[0][j],&pt[0] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + for ( i = 1; i <= NH; i++ ) + { + Scale( rc,xyz[i][j],&pt[0] ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + } + g_GLTable.m_pfn_qglEnd(); + } + } - v = (float)(jj)/(float)(SUBDIVS); - for(ii=0; ii<3; ii++) - { - for(axis=0; axis<3; axis++) - { - float a, b, c; - float qA, qB, qC; - a = (float)uv[ii][0].p[axis]; - b = (float)uv[ii][1].p[axis]; - c = (float)uv[ii][2].p[axis]; - qA = a - 2 * b + c; - qB = 2 * b - 2 * a; - qC = a; - Ctrl[ii].p[axis] = qA * v * v + qB * v + qC; - } - } - VectorCopy(Ctrl[0].p,out.p); - project(&out); - Scale(rc,out,&pt[0]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - for(ii=1; ii<=SUBDIVS; ii++) - { - u = (float)(ii)/(float)(SUBDIVS); - for (axis = 0 ; axis < 3 ; axis++) - { - float a, b, c; - float qA, qB, qC; - a = (float)Ctrl[0].p[axis]; - b = (float)Ctrl[1].p[axis]; - c = (float)Ctrl[2].p[axis]; - qA = a - 2 * b + c; - qB = 2 * b - 2 * a; - qC = a; - out.p[axis] = qA * u * u + qB * u + qC; - } - project(&out); - Scale(rc,out,&pt[0]); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - } - } - } - } - else - { - for(i=0; i<=NH; i++) - { - Scale(rc,xyz[i][0],&pt[0]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - for(j=1; j<=NV; j++) - { - Scale(rc,xyz[i][j],&pt[0]); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - } - for(j=0; j<=NV; j++) - { - Scale(rc,xyz[0][j],&pt[0]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - for(i=1; i<=NH; i++) - { - Scale(rc,xyz[i][j],&pt[0]); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - } - } - - if(Game!=QUAKE3 || UsePatches==0) - { - // Draw lines from corners to base, and lines around base - for(i=0; i<=NH; i+=NH) - { - for(j=0; j<=NV; j+=NV) - { - VectorCopy(xyz[i][j].p, v[0].p); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - v[0].p[1] = backface; - break; - case PLANE_YZ0: - case PLANE_YZ1: - v[0].p[0] = backface; - break; - default: - v[0].p[2] = backface; - } - Scale(rc,xyz[i][j],&pt[0]); + if ( Game != QUAKE3 || UsePatches == 0 ) { + // Draw lines from corners to base, and lines around base + for ( i = 0; i <= NH; i += NH ) + { + for ( j = 0; j <= NV; j += NV ) + { + VectorCopy( xyz[i][j].p, v[0].p ); + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + v[0].p[1] = backface; + break; + case PLANE_YZ0: + case PLANE_YZ1: + v[0].p[0] = backface; + break; + default: + v[0].p[2] = backface; + } + Scale( rc,xyz[i][j],&pt[0] ); #ifndef ISOMETRIC - project(&v[0]); + project( &v[0] ); #endif - Scale(rc,v[0],&pt[1]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x, pt[1].y); - g_GLTable.m_pfn_qglEnd (); - } - } - VectorCopy(xyz[ 0][ 0].p, v[0].p); - VectorCopy(xyz[NH][ 0].p, v[1].p); - VectorCopy(xyz[NH][NV].p, v[2].p); - VectorCopy(xyz[ 0][NV].p, v[3].p); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - v[0].p[1] = backface;; - v[1].p[1] = v[0].p[1]; - v[2].p[1] = v[0].p[1]; - v[3].p[1] = v[0].p[1]; - break; - case PLANE_YZ0: - case PLANE_YZ1: - v[0].p[0] = backface; - v[1].p[0] = v[0].p[0]; - v[2].p[0] = v[0].p[0]; - v[3].p[0] = v[0].p[0]; - break; - default: - v[0].p[2] = backface; - v[1].p[2] = v[0].p[2]; - v[2].p[2] = v[0].p[2]; - v[3].p[2] = v[0].p[2]; - } + Scale( rc,v[0],&pt[1] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + g_GLTable.m_pfn_qglVertex2i( pt[1].x, pt[1].y ); + g_GLTable.m_pfn_qglEnd(); + } + } + VectorCopy( xyz[ 0][ 0].p, v[0].p ); + VectorCopy( xyz[NH][ 0].p, v[1].p ); + VectorCopy( xyz[NH][NV].p, v[2].p ); + VectorCopy( xyz[ 0][NV].p, v[3].p ); + switch ( Plane ) + { + case PLANE_XZ0: + case PLANE_XZ1: + v[0].p[1] = backface;; + v[1].p[1] = v[0].p[1]; + v[2].p[1] = v[0].p[1]; + v[3].p[1] = v[0].p[1]; + break; + case PLANE_YZ0: + case PLANE_YZ1: + v[0].p[0] = backface; + v[1].p[0] = v[0].p[0]; + v[2].p[0] = v[0].p[0]; + v[3].p[0] = v[0].p[0]; + break; + default: + v[0].p[2] = backface; + v[1].p[2] = v[0].p[2]; + v[2].p[2] = v[0].p[2]; + v[3].p[2] = v[0].p[2]; + } #ifndef ISOMETRIC - project(&v[3]); + project( &v[3] ); #endif - Scale(rc,v[3],&pt[0]); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - for(i=0; i<3; i++) - { + Scale( rc,v[3],&pt[0] ); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + for ( i = 0; i < 3; i++ ) + { #ifndef ISOMETRIC - project(&v[i]); + project( &v[i] ); #endif - Scale(rc,v[i],&pt[1]); - g_GLTable.m_pfn_qglVertex2i (pt[1].x, pt[1].y); - } - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - g_GLTable.m_pfn_qglEnd (); - } + Scale( rc,v[i],&pt[1] ); + g_GLTable.m_pfn_qglVertex2i( pt[1].x, pt[1].y ); + } + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + g_GLTable.m_pfn_qglEnd(); + } - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); #ifdef ISOMETRIC - // Draw small depiction of coordinate axes - pt[0].x = rc.right - cxChar - cxChar/2 - cyChar; - pt[0].y = rc.bottom - cyChar/2 - cxChar/2; - pt[1].x = pt[0].x + (int)(cyChar*COSXA); - pt[1].y = pt[0].y - (int)(cyChar*SINXA); - MoveToEx(hdc,pt[0].x,pt[0].y,NULL); - LineTo(hdc,pt[1].x,pt[1].y); - SetTextAlign(hdc,TA_LEFT | TA_TOP); - TextOut(hdc,pt[1].x,pt[1].y-cyChar/2,"X",1); - pt[1].x = pt[0].x - (int)(cyChar*COSYA); - pt[1].y = pt[0].y - (int)(cyChar*SINYA); - MoveToEx(hdc,pt[0].x,pt[0].y,NULL); - LineTo(hdc,pt[1].x,pt[1].y); - SetTextAlign(hdc,TA_RIGHT | TA_TOP); - TextOut(hdc,pt[1].x,pt[1].y-cyChar/2,"Y",1); - pt[1].x = pt[0].x; - pt[1].y = pt[0].y - cyChar; - MoveToEx(hdc,pt[0].x,pt[0].y,NULL); - LineTo(hdc,pt[1].x,pt[1].y); - SetTextAlign(hdc,TA_CENTER | TA_BOTTOM); - TextOut(hdc,pt[1].x,pt[1].y,"Z",1); + // Draw small depiction of coordinate axes + pt[0].x = rc.right - cxChar - cxChar / 2 - cyChar; + pt[0].y = rc.bottom - cyChar / 2 - cxChar / 2; + pt[1].x = pt[0].x + (int)( cyChar * COSXA ); + pt[1].y = pt[0].y - (int)( cyChar * SINXA ); + MoveToEx( hdc,pt[0].x,pt[0].y,NULL ); + LineTo( hdc,pt[1].x,pt[1].y ); + SetTextAlign( hdc,TA_LEFT | TA_TOP ); + TextOut( hdc,pt[1].x,pt[1].y - cyChar / 2,"X",1 ); + pt[1].x = pt[0].x - (int)( cyChar * COSYA ); + pt[1].y = pt[0].y - (int)( cyChar * SINYA ); + MoveToEx( hdc,pt[0].x,pt[0].y,NULL ); + LineTo( hdc,pt[1].x,pt[1].y ); + SetTextAlign( hdc,TA_RIGHT | TA_TOP ); + TextOut( hdc,pt[1].x,pt[1].y - cyChar / 2,"Y",1 ); + pt[1].x = pt[0].x; + pt[1].y = pt[0].y - cyChar; + MoveToEx( hdc,pt[0].x,pt[0].y,NULL ); + LineTo( hdc,pt[1].x,pt[1].y ); + SetTextAlign( hdc,TA_CENTER | TA_BOTTOM ); + TextOut( hdc,pt[1].x,pt[1].y,"Z",1 ); #else - L = 2*(double)cyChar/SF; - v[0].p[0] = 0.; - v[0].p[1] = 0.; - v[0].p[2] = 0.; - v[1].p[0] = L; - v[1].p[1] = 0.; - v[1].p[2] = 0.; - v[2].p[0] = 0.; - v[2].p[1] = L; - v[2].p[2] = 0.; - v[3].p[0] = 0.; - v[3].p[1] = 0.; - v[3].p[2] = L; - for(i=0; i<=3; i++) - { - project(&v[i]); - Scale(rc,v[i],&pt[i]); - } - for(i=1; i<=3; i++) - { - pt[i].x += -pt[0].x + rc.right - 2*cyChar; - pt[i].y += -pt[0].y + rc.bottom + 2*cyChar; - } - pt[0].x = rc.right - 2*cyChar; - pt[0].y = rc.bottom + 2*cyChar; - - for(i=1; i<=3; i++) - { - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (pt[0].x, pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[i].x, pt[i].y); - g_GLTable.m_pfn_qglEnd (); - texfont_write (axis[i-1], pt[i].x-cxChar/2,pt[i].y+cyChar/2); - } + L = 2 * (double)cyChar / SF; + v[0].p[0] = 0.; + v[0].p[1] = 0.; + v[0].p[2] = 0.; + v[1].p[0] = L; + v[1].p[1] = 0.; + v[1].p[2] = 0.; + v[2].p[0] = 0.; + v[2].p[1] = L; + v[2].p[2] = 0.; + v[3].p[0] = 0.; + v[3].p[1] = 0.; + v[3].p[2] = L; + for ( i = 0; i <= 3; i++ ) + { + project( &v[i] ); + Scale( rc,v[i],&pt[i] ); + } + for ( i = 1; i <= 3; i++ ) + { + pt[i].x += -pt[0].x + rc.right - 2 * cyChar; + pt[i].y += -pt[0].y + rc.bottom + 2 * cyChar; + } + pt[0].x = rc.right - 2 * cyChar; + pt[0].y = rc.bottom + 2 * cyChar; + + for ( i = 1; i <= 3; i++ ) + { + g_GLTable.m_pfn_qglBegin( GL_LINES ); + g_GLTable.m_pfn_qglVertex2i( pt[0].x, pt[0].y ); + g_GLTable.m_pfn_qglVertex2i( pt[i].x, pt[i].y ); + g_GLTable.m_pfn_qglEnd(); + texfont_write( axis[i - 1], pt[i].x - cxChar / 2,pt[i].y + cyChar / 2 ); + } #endif - // Draw player model's bounding box in red to give a sense of scale - // PEN_RED - g_GLTable.m_pfn_qglLineWidth (2); - g_GLTable.m_pfn_qglColor3f (1, 0, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - - switch(Plane) - { - case PLANE_XY1: - v[0].p[0] = xyz[NH/2][NV/2].p[0] + PlayerBox[Game].x[0]; - v[0].p[1] = xyz[NH/2][NV/2].p[1] + PlayerBox[Game].y[0]; - v[0].p[2] = zmin - PlayerBox[Game].z[0] - 32; - break; - case PLANE_XZ0: - v[0].p[0] = (xmax+xmin)/2 + PlayerBox[Game].x[0]; - v[0].p[1] = ymax+64; - v[0].p[2] = zmin; - break; - case PLANE_XZ1: - v[0].p[0] = (xmax+xmin)/2 + PlayerBox[Game].x[0]; - v[0].p[1] = ymin-64; - v[0].p[2] = zmin; - break; - case PLANE_YZ0: - v[0].p[0] = xmax+64; - v[0].p[1] = (ymax+ymin)/2 + PlayerBox[Game].y[0]; - v[0].p[2] = zmin; - break; - case PLANE_YZ1: - v[0].p[0] = xmin-64; - v[0].p[1] = (ymax+ymin)/2 + PlayerBox[Game].y[0]; - v[0].p[2] = zmin; - break; - default: - // Put player on a node. For patches, put on an even numbered node. - if(Game==QUAKE3 && UsePatches!=0) - { - if(NH > 2) - x = Hll + dh * (int)(NH/2 + 1); - else - x = Hll + dh * (int)(NH/2); - if(NV > 2) - y = Vll + dv * (int)(NV/2 + 1); - else - y = Vll + dv * (int)(NV/2); - } - else - { - if(NH > 1) - x = Hll + dh * (int)(NH/2); - else - x = Hll + dh/2; - if(NV > 1) - y = Vll + dv * (int)(NV/2); - else - y = Vll + dv/2; - } + // Draw player model's bounding box in red to give a sense of scale + // PEN_RED + g_GLTable.m_pfn_qglLineWidth( 2 ); + g_GLTable.m_pfn_qglColor3f( 1, 0, 0 ); + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); + + switch ( Plane ) + { + case PLANE_XY1: + v[0].p[0] = xyz[NH / 2][NV / 2].p[0] + PlayerBox[Game].x[0]; + v[0].p[1] = xyz[NH / 2][NV / 2].p[1] + PlayerBox[Game].y[0]; + v[0].p[2] = zmin - PlayerBox[Game].z[0] - 32; + break; + case PLANE_XZ0: + v[0].p[0] = ( xmax + xmin ) / 2 + PlayerBox[Game].x[0]; + v[0].p[1] = ymax + 64; + v[0].p[2] = zmin; + break; + case PLANE_XZ1: + v[0].p[0] = ( xmax + xmin ) / 2 + PlayerBox[Game].x[0]; + v[0].p[1] = ymin - 64; + v[0].p[2] = zmin; + break; + case PLANE_YZ0: + v[0].p[0] = xmax + 64; + v[0].p[1] = ( ymax + ymin ) / 2 + PlayerBox[Game].y[0]; + v[0].p[2] = zmin; + break; + case PLANE_YZ1: + v[0].p[0] = xmin - 64; + v[0].p[1] = ( ymax + ymin ) / 2 + PlayerBox[Game].y[0]; + v[0].p[2] = zmin; + break; + default: + // Put player on a node. For patches, put on an even numbered node. + if ( Game == QUAKE3 && UsePatches != 0 ) { + if ( NH > 2 ) { + x = Hll + dh * (int)( NH / 2 + 1 ); + } + else{ + x = Hll + dh * (int)( NH / 2 ); + } + if ( NV > 2 ) { + y = Vll + dv * (int)( NV / 2 + 1 ); + } + else{ + y = Vll + dv * (int)( NV / 2 ); + } + } + else + { + if ( NH > 1 ) { + x = Hll + dh * (int)( NH / 2 ); + } + else{ + x = Hll + dh / 2; + } + if ( NV > 1 ) { + y = Vll + dv * (int)( NV / 2 ); + } + else{ + y = Vll + dv / 2; + } + } // x = (Hll+Hur)/2.; // y = (Vll+Vur)/2.; - v[0].p[0] = x + PlayerBox[Game].x[0]; - v[0].p[1] = y + PlayerBox[Game].y[0]; - v[0].p[2] = PlayerStartZ(x,y) + PlayerBox[Game].z[0] + 8; // add 8 cuz I'm a pessimist - } - v[1].p[0] = v[0].p[0] + PlayerBox[Game].x[1] - PlayerBox[Game].x[0]; - v[1].p[1] = v[0].p[1]; - v[1].p[2] = v[0].p[2]; - v[2].p[0] = v[1].p[0]; - v[2].p[1] = v[1].p[1] + PlayerBox[Game].y[1] - PlayerBox[Game].y[0]; - v[2].p[2] = v[0].p[2]; - v[3].p[0] = v[0].p[0]; - v[3].p[1] = v[2].p[1]; - v[3].p[2] = v[0].p[2]; - VectorCopy(v[0].p,v[4].p); - VectorCopy(v[1].p,v[5].p); - VectorCopy(v[2].p,v[6].p); - VectorCopy(v[3].p,v[7].p); - v[4].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[5].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[6].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[7].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - for(i=0; i<=7; i++) - { + v[0].p[0] = x + PlayerBox[Game].x[0]; + v[0].p[1] = y + PlayerBox[Game].y[0]; + v[0].p[2] = PlayerStartZ( x,y ) + PlayerBox[Game].z[0] + 8; // add 8 cuz I'm a pessimist + } + v[1].p[0] = v[0].p[0] + PlayerBox[Game].x[1] - PlayerBox[Game].x[0]; + v[1].p[1] = v[0].p[1]; + v[1].p[2] = v[0].p[2]; + v[2].p[0] = v[1].p[0]; + v[2].p[1] = v[1].p[1] + PlayerBox[Game].y[1] - PlayerBox[Game].y[0]; + v[2].p[2] = v[0].p[2]; + v[3].p[0] = v[0].p[0]; + v[3].p[1] = v[2].p[1]; + v[3].p[2] = v[0].p[2]; + VectorCopy( v[0].p,v[4].p ); + VectorCopy( v[1].p,v[5].p ); + VectorCopy( v[2].p,v[6].p ); + VectorCopy( v[3].p,v[7].p ); + v[4].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; + v[5].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; + v[6].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; + v[7].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; + for ( i = 0; i <= 7; i++ ) + { #ifndef ISOMETRIC - project(&v[i]); + project( &v[i] ); #endif - Scale(rc,v[i],&pt[i]); - } - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[3].x, pt[3].y); - for(i=0; i<=3; i++) - g_GLTable.m_pfn_qglVertex2i (pt[i].x, pt[i].y); - g_GLTable.m_pfn_qglEnd (); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[7].x, pt[7].y); - for(i=4; i<=7; i++) - g_GLTable.m_pfn_qglVertex2i (pt[i].x, pt[i].y); - g_GLTable.m_pfn_qglEnd (); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=3; i++) - { - g_GLTable.m_pfn_qglVertex2i (pt[i].x,pt[i].y); - g_GLTable.m_pfn_qglVertex2i (pt[i+4].x,pt[i+4].y); - } - g_GLTable.m_pfn_qglEnd (); - - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); + Scale( rc,v[i],&pt[i] ); + } + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[3].x, pt[3].y ); + for ( i = 0; i <= 3; i++ ) + g_GLTable.m_pfn_qglVertex2i( pt[i].x, pt[i].y ); + g_GLTable.m_pfn_qglEnd(); + g_GLTable.m_pfn_qglBegin( GL_LINE_STRIP ); + g_GLTable.m_pfn_qglVertex2i( pt[7].x, pt[7].y ); + for ( i = 4; i <= 7; i++ ) + g_GLTable.m_pfn_qglVertex2i( pt[i].x, pt[i].y ); + g_GLTable.m_pfn_qglEnd(); + g_GLTable.m_pfn_qglBegin( GL_LINES ); + for ( i = 0; i <= 3; i++ ) + { + g_GLTable.m_pfn_qglVertex2i( pt[i].x,pt[i].y ); + g_GLTable.m_pfn_qglVertex2i( pt[i + 4].x,pt[i + 4].y ); + } + g_GLTable.m_pfn_qglEnd(); + + g_GLTable.m_pfn_qglLineWidth( 1 ); + g_GLTable.m_pfn_qglColor3f( 0, 1, 0 ); + g_GLTable.m_pfn_qglDisable( GL_LINE_STIPPLE ); } //============================================================= -void DrawGrid(Rect rc) -{ - int i, j, k; - double h,w,x,y; - Point pt[2]; - Rect rcBox; - - w = (double)(rc.right-rc.left+1) - cxChar; - h = (double)(rc.top-rc.bottom+1) - cxChar - cyChar; - - SFG = w/(Hur-Hll); - SFG = min(SFG, h/(Vur-Vll)); - - // Center drawing - X0G = (int)(rc.left + rc.right - (int)(SFG*(Hur-Hll)))/2; - Y0G = (int)(rc.top + rc.bottom + cyChar - (int)(SFG*(Vur-Vll)))/2; - - g_GLTable.m_pfn_qglLineWidth (2); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - - pt[0].y = Y0G; - pt[1].y = Y0G + (int)(SFG*(Vur-Vll)); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=NH; i++) - { - x = Hll + i * dh; - pt[0].x = X0G + (int)(SFG*(x-Hll)); - g_GLTable.m_pfn_qglVertex2i(pt[0].x, pt[0].y); - g_GLTable.m_pfn_qglVertex2i(pt[0].x, pt[1].y); - } - g_GLTable.m_pfn_qglEnd (); - pt[0].x = X0G; - pt[1].x = X0G + (int)(SFG*(Hur-Hll)); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=NV; i++) - { - y = Vll + i * dv; - pt[0].y = Y0G + (int)(SFG*(Vur-y)); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - - g_GLTable.m_pfn_qglLineWidth (1); - - // Draw axes - pt[0].x = rc.right - cyChar - cxChar - cyChar/2; - pt[0].y = rc.bottom + cyChar/2; - pt[1].x = pt[0].x + cyChar; - pt[1].y = pt[0].y; - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[1].y); - g_GLTable.m_pfn_qglEnd (); - switch(Plane) - { - case PLANE_YZ0: - case PLANE_YZ1: - texfont_write ("Y", pt[1].x, pt[1].y+cyChar/2); - break; - default: - texfont_write ("X", pt[1].x, pt[1].y+cyChar/2); - } - pt[1].x = pt[0].x; - pt[1].y = pt[0].y + cyChar; - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[1].y); - g_GLTable.m_pfn_qglEnd (); - switch(Plane) - { - case PLANE_XY0: - case PLANE_XY1: - texfont_write ("Y", pt[1].x-cyChar/2, pt[1].y+cyChar); - break; - default: - texfont_write ("Z", pt[1].x-cyChar/2, pt[1].y+cyChar); - } - - // Denote fixed points with a 5x5 red rectangle - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - { - x = Hll + i*dh; - y = Vll + j*dv; - rcBox.left = X0G + (int)(SFG*(x-Hll)) - 2; - rcBox.top = Y0G + (int)(SFG*(Vur-y)) + 2; - rcBox.right = rcBox.left + 5; - rcBox.bottom = rcBox.top - 5; - - DRAW_QUAD (rcBox, 1,0,0); - } - } - } - - // Denote currently selected point with a 5x5 green rectangle - if (NumVerticesSelected) - { - for(k=0; kp[2]; // yaw - xa = ct[0]*x - st[0]*z; - za = st[0]*x + ct[0]*z; + xa = ct[0] * x - st[0] * z; + za = st[0] * x + ct[0] * z; // roll - x = ct[1]*xa + st[1]*y; - ya = ct[1]*y - st[1]*xa; + x = ct[1] * xa + st[1] * y; + ya = ct[1] * y - st[1] * xa; // azimuth - z = ct[2]*za - st[2]*ya; - y = ct[2]*ya + st[2]*za; + z = ct[2] * za - st[2] * ya; + y = ct[2] * ya + st[2] * za; // horizontal and vertical projections: // v->pp[0] = D*x/z; @@ -1207,28 +1190,29 @@ void project(XYZ *v) // v->projected_v = -v->projected_v * persp/(v->projected_z-persp); } /*=======================================================================*/ -void evaluate() -{ +void evaluate(){ int i, j; XYZ v[4]; - - if(elevation > PI) elevation -= 2.*PI; - roll = elevation * sin(azimuth); - yaw = 1.5*PI + elevation*cos(azimuth); + + if ( elevation > PI ) { + elevation -= 2. * PI; + } + roll = elevation * sin( azimuth ); + yaw = 1.5 * PI + elevation*cos( azimuth ); // Find angles from midpoint to viewpoint: - st[0] = sin(yaw); - st[1] = sin(roll); - st[2] = sin(azimuth); - ct[0] = cos(yaw); - ct[1] = cos(roll); - ct[2] = cos(azimuth); - - for(i=0; i<=NH; i++) + st[0] = sin( yaw ); + st[1] = sin( roll ); + st[2] = sin( azimuth ); + ct[0] = cos( yaw ); + ct[1] = cos( roll ); + ct[2] = cos( azimuth ); + + for ( i = 0; i <= NH; i++ ) { - for(j=0; j<=NV; j++) + for ( j = 0; j <= NV; j++ ) { - project(&xyz[i][j]); + project( &xyz[i][j] ); } } @@ -1236,23 +1220,23 @@ void evaluate() Hlo = Hhi; Vhi = xyz[0][0].pp[1]; Vlo = Vhi; - for(i=0; i<=NH; i++) + for ( i = 0; i <= NH; i++ ) { - for(j=0; j<=NV; j++) + for ( j = 0; j <= NV; j++ ) { - Hlo = min(Hlo,xyz[i][j].pp[0]); - Hhi = max(Hhi,xyz[i][j].pp[0]); - Vlo = min(Vlo,xyz[i][j].pp[1]); - Vhi = max(Vhi,xyz[i][j].pp[1]); + Hlo = min( Hlo,xyz[i][j].pp[0] ); + Hhi = max( Hhi,xyz[i][j].pp[0] ); + Vlo = min( Vlo,xyz[i][j].pp[1] ); + Vhi = max( Vhi,xyz[i][j].pp[1] ); } } // Include backface in min-max - VectorCopy(xyz[ 0][ 0].p,v[0].p); - VectorCopy(xyz[NH][ 0].p,v[1].p); - VectorCopy(xyz[NH][NV].p,v[2].p); - VectorCopy(xyz[ 0][NV].p,v[3].p); - switch(Plane) + VectorCopy( xyz[ 0][ 0].p,v[0].p ); + VectorCopy( xyz[NH][ 0].p,v[1].p ); + VectorCopy( xyz[NH][NV].p,v[2].p ); + VectorCopy( xyz[ 0][NV].p,v[3].p ); + switch ( Plane ) { case PLANE_XZ0: case PLANE_XZ1: @@ -1274,13 +1258,13 @@ void evaluate() v[2].p[2] = v[0].p[2]; v[3].p[2] = v[0].p[2]; } - for(i=0; i<=3; i++) + for ( i = 0; i <= 3; i++ ) { - project(&v[i]); - Hlo = min(Hlo,v[i].pp[0]); - Hhi = max(Hhi,v[i].pp[0]); - Vlo = min(Vlo,v[i].pp[1]); - Vhi = max(Vhi,v[i].pp[1]); + project( &v[i] ); + Hlo = min( Hlo,v[i].pp[0] ); + Hhi = max( Hhi,v[i].pp[0] ); + Vlo = min( Vlo,v[i].pp[1] ); + Vhi = max( Vhi,v[i].pp[1] ); } } diff --git a/contrib/hydratoolz/plugin.cpp b/contrib/hydratoolz/plugin.cpp index abc57fc3..44393ea1 100644 --- a/contrib/hydratoolz/plugin.cpp +++ b/contrib/hydratoolz/plugin.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "plugin.h" #include "version.h" @@ -41,9 +41,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ToDo ==== - * Code it ? :) + * Code it ? :) -*/ + */ // ============================================================================= // Globals @@ -58,142 +58,136 @@ void *g_pMainWnd; // ============================================================================= // Ripped from TexTool.cpp -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; +static void dialog_button_callback( GtkWidget *widget, gpointer data ){ + GtkWidget *parent; + int *loop, *ret; - parent = gtk_widget_get_toplevel (widget); - loop = (int*)gtk_object_get_data (GTK_OBJECT (parent), "loop"); - ret = (int*)gtk_object_get_data (GTK_OBJECT (parent), "ret"); + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)gtk_object_get_data( GTK_OBJECT( parent ), "loop" ); + ret = (int*)gtk_object_get_data( GTK_OBJECT( parent ), "ret" ); - *loop = 0; - *ret = gpointer_to_int (data); + *loop = 0; + *ret = gpointer_to_int( data ); } -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; +static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ + int *loop; - gtk_widget_hide (widget); - loop = (int*)gtk_object_get_data (GTK_OBJECT (widget), "loop"); - *loop = 0; + gtk_widget_hide( widget ); + loop = (int*)gtk_object_get_data( GTK_OBJECT( widget ), "loop" ); + *loop = 0; - return TRUE; + return TRUE; } -int DoMessageBox (const char* lpText, const char* lpCaption, guint32 uType) -{ - GtkWidget *window, *w, *vbox, *hbox; - int mode = (uType & MB_TYPEMASK), ret, loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_signal_connect (GTK_OBJECT (window), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_title (GTK_WINDOW (window), lpCaption); - gtk_container_border_width (GTK_CONTAINER (window), 10); - gtk_object_set_data (GTK_OBJECT (window), "loop", &loop); - gtk_object_set_data (GTK_OBJECT (window), "ret", &ret); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - w = gtk_label_new (lpText); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - if (mode == MB_OK) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - ret = IDOK; - } - else if (mode == MB_OKCANCEL) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else if (mode == MB_YESNOCANCEL) - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else /* if (mode == MB_YESNO) */ - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - ret = IDNO; - } - - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; +int DoMessageBox( const char* lpText, const char* lpCaption, guint32 uType ){ + GtkWidget *window, *w, *vbox, *hbox; + int mode = ( uType & MB_TYPEMASK ), ret, loop = 1; + + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_signal_connect( GTK_OBJECT( window ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( window ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_window_set_title( GTK_WINDOW( window ), lpCaption ); + gtk_container_border_width( GTK_CONTAINER( window ), 10 ); + gtk_object_set_data( GTK_OBJECT( window ), "loop", &loop ); + gtk_object_set_data( GTK_OBJECT( window ), "ret", &ret ); + gtk_widget_realize( window ); + + vbox = gtk_vbox_new( FALSE, 10 ); + gtk_container_add( GTK_CONTAINER( window ), vbox ); + gtk_widget_show( vbox ); + + w = gtk_label_new( lpText ); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_label_set_justify( GTK_LABEL( w ), GTK_JUSTIFY_LEFT ); + gtk_widget_show( w ); + + w = gtk_hseparator_new(); + gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 2 ); + gtk_widget_show( w ); + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 2 ); + gtk_widget_show( hbox ); + + if ( mode == MB_OK ) { + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + ret = IDOK; + } + else if ( mode == MB_OKCANCEL ) { + w = gtk_button_new_with_label( "Ok" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + gtk_widget_show( w ); + ret = IDCANCEL; + } + else if ( mode == MB_YESNOCANCEL ) { + w = gtk_button_new_with_label( "Yes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "No" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "Cancel" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + gtk_widget_show( w ); + ret = IDCANCEL; + } + else /* if (mode == MB_YESNO) */ + { + w = gtk_button_new_with_label( "Yes" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDYES ) ); + GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( w ); + gtk_widget_show( w ); + + w = gtk_button_new_with_label( "No" ); + gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( w ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDNO ) ); + gtk_widget_show( w ); + ret = IDNO; + } + + gtk_widget_show( window ); + gtk_grab_add( window ); + + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( window ); + gtk_widget_destroy( window ); + + return ret; } // End of rip from TexTool.cpp @@ -202,57 +196,56 @@ int DoMessageBox (const char* lpText, const char* lpCaption, guint32 uType) // Ripped from cmdlib.cpp /* -==================== -Extract file parts -==================== -*/ -void ExtractFilePath (const char *path, char *dest) -{ - const char *src; + ==================== + Extract file parts + ==================== + */ +void ExtractFilePath( const char *path, char *dest ){ + const char *src; - src = path + strlen(path) - 1; + src = path + strlen( path ) - 1; // // back up until a \ or the start // - while (src != path && *(src-1) != '/' && *(src-1) != '\\') - src--; + while ( src != path && *( src - 1 ) != '/' && *( src - 1 ) != '\\' ) + src--; - memcpy (dest, path, src-path); - dest[src-path] = 0; + memcpy( dest, path, src - path ); + dest[src - path] = 0; } -void ExtractFileName (const char *path, char *dest) -{ - const char *src; +void ExtractFileName( const char *path, char *dest ){ + const char *src; - src = path + strlen(path) - 1; + src = path + strlen( path ) - 1; // // back up until a \ or the start // - while (src != path && *(src-1) != '/' - && *(src-1) != '\\' ) - src--; - - while (*src) - { - *dest++ = *src++; - } - *dest = 0; + while ( src != path && *( src - 1 ) != '/' + && *( src - 1 ) != '\\' ) + src--; + + while ( *src ) + { + *dest++ = *src++; + } + *dest = 0; } -void ConvertDOSToUnixName( char *dst, const char *src ) -{ - while ( *src ) - { - if ( *src == '\\' ) - *dst = '/'; - else - *dst = *src; - dst++; src++; - } - *dst = 0; +void ConvertDOSToUnixName( char *dst, const char *src ){ + while ( *src ) + { + if ( *src == '\\' ) { + *dst = '/'; + } + else{ + *dst = *src; + } + dst++; src++; + } + *dst = 0; } // End of rip from cmdlib.cpp @@ -263,191 +256,192 @@ void ConvertDOSToUnixName( char *dst, const char *src ) // get the wad name from the shader name (or an actual wadname) and add to a list of wad names making // sure we don't add duplicates. -GSList *AddToWadList(GSList *wadlist, const char *shadername, const char *wad) -{ - char tmpstr[QER_MAX_NAMELEN]; - char *wadname; - if (!shadername && !wad) return wadlist; - - if (shadername) - { - if (strcmp(shadername,"color") == 0) - return wadlist; - ExtractFilePath(shadername,tmpstr); - // Sys_Printf("checking: %s\n",shadername); - - int l = strlen(tmpstr) - 1; - - if (tmpstr[l] == '/' || tmpstr[l] == '\\') - tmpstr[l] = 0; - else - { - Sys_Printf("WARNING: Unknown wad file for shader %s\n",shadername); - return wadlist; - } - - ExtractFileName(tmpstr,tmpstr); - - wadname = (char *)malloc(strlen(tmpstr) + 5); - sprintf(wadname,"%s.wad",tmpstr); - } - else - { - wadname=strdup(wad); - } - - for (GSList *l = wadlist; l != NULL ; l = l->next) - { - if (string_equal_nocase((char *)l->data,wadname)) - { - free( wadname ); - return wadlist; - } - } - - Sys_Printf("Adding Wad File to WAD list: %s (reason: ",wadname); - if (shadername) - Sys_Printf("see shader \"%s\")\n", shadername); - else - Sys_Printf("already in WAD key. )\n"); - return ( g_slist_append (wadlist, wadname ) ); +GSList *AddToWadList( GSList *wadlist, const char *shadername, const char *wad ){ + char tmpstr[QER_MAX_NAMELEN]; + char *wadname; + if ( !shadername && !wad ) { + return wadlist; + } + + if ( shadername ) { + if ( strcmp( shadername,"color" ) == 0 ) { + return wadlist; + } + ExtractFilePath( shadername,tmpstr ); + // Sys_Printf("checking: %s\n",shadername); + + int l = strlen( tmpstr ) - 1; + + if ( tmpstr[l] == '/' || tmpstr[l] == '\\' ) { + tmpstr[l] = 0; + } + else + { + Sys_Printf( "WARNING: Unknown wad file for shader %s\n",shadername ); + return wadlist; + } + + ExtractFileName( tmpstr,tmpstr ); + + wadname = (char *)malloc( strlen( tmpstr ) + 5 ); + sprintf( wadname,"%s.wad",tmpstr ); + } + else + { + wadname = strdup( wad ); + } + + for ( GSList *l = wadlist; l != NULL ; l = l->next ) + { + if ( string_equal_nocase( (char *)l->data,wadname ) ) { + free( wadname ); + return wadlist; + } + } + + Sys_Printf( "Adding Wad File to WAD list: %s (reason: ",wadname ); + if ( shadername ) { + Sys_Printf( "see shader \"%s\")\n", shadername ); + } + else{ + Sys_Printf( "already in WAD key. )\n" ); + } + return ( g_slist_append( wadlist, wadname ) ); } -void UpdateWadKeyPair( void ) -{ - int i,nb; - - char wads[2048]; // change to CString usage ? - wads[0] = 0; - char *p1,*p2; - entity_t *pEntity; - epair_t *pEpair; - GSList *wadlist = NULL; - face_t *f; - brush_t *b; - char cleanwadname[QER_MAX_NAMELEN]; - const char *actualwad; - - - pEntity = (entity_t *)g_FuncTable.m_pfnGetEntityHandle(0); // get the worldspawn ent - - Sys_Printf("Searching for in-use wad files...\n"); - for(pEpair = pEntity->epairs; pEpair != NULL; pEpair = pEpair->next) - { - if (string_equal_nocase(pEpair->key,"wad")) - { - strcpy(wads,pEpair->value); - ConvertDOSToUnixName(wads,wads); - - // ok, we got the list of ; delimited wads, now split it into a GSList that contains - // just the wad names themselves. - - p1 = wads; - - do - { - p2 = strchr(p1,';'); - if (p2) - *p2 = 0; // swap the ; with a null terminator - - if (strchr(p1,'/') || strchr(p1,'\\')) - { - ExtractFileName(p1,cleanwadname); - wadlist = AddToWadList (wadlist, NULL, cleanwadname); - } - else - { - wadlist = AddToWadList (wadlist, NULL, p1); - } - if (p2) - p1 = p2+1; // point back to the remainder of the string - else - p1 = NULL; // make it so we exit the loop. - - } while (p1); - - // ok, now we have a list of wads in GSList. - // now we need to add any new wadfiles (with their paths) to this list - // so scan all brushes and see what wads are in use - // FIXME: scan brushes only in the region ? - - break; // we don't need to process any more key/pairs. - } - } - - nb = g_FuncTable.m_pfnAllocateActiveBrushHandles(); - for( i = 0; i < nb; i++ ) +void UpdateWadKeyPair( void ){ + int i,nb; + + char wads[2048]; // change to CString usage ? + wads[0] = 0; + char *p1,*p2; + entity_t *pEntity; + epair_t *pEpair; + GSList *wadlist = NULL; + face_t *f; + brush_t *b; + char cleanwadname[QER_MAX_NAMELEN]; + const char *actualwad; + + + pEntity = (entity_t *)g_FuncTable.m_pfnGetEntityHandle( 0 ); // get the worldspawn ent + + Sys_Printf( "Searching for in-use wad files...\n" ); + for ( pEpair = pEntity->epairs; pEpair != NULL; pEpair = pEpair->next ) + { + if ( string_equal_nocase( pEpair->key,"wad" ) ) { + strcpy( wads,pEpair->value ); + ConvertDOSToUnixName( wads,wads ); + + // ok, we got the list of ; delimited wads, now split it into a GSList that contains + // just the wad names themselves. + + p1 = wads; + + do + { + p2 = strchr( p1,';' ); + if ( p2 ) { + *p2 = 0; // swap the ; with a null terminator + + } + if ( strchr( p1,'/' ) || strchr( p1,'\\' ) ) { + ExtractFileName( p1,cleanwadname ); + wadlist = AddToWadList( wadlist, NULL, cleanwadname ); + } + else + { + wadlist = AddToWadList( wadlist, NULL, p1 ); + } + if ( p2 ) { + p1 = p2 + 1; // point back to the remainder of the string + } + else{ + p1 = NULL; // make it so we exit the loop. + + } + } while ( p1 ); + + // ok, now we have a list of wads in GSList. + // now we need to add any new wadfiles (with their paths) to this list + // so scan all brushes and see what wads are in use + // FIXME: scan brushes only in the region ? + + break; // we don't need to process any more key/pairs. + } + } + + nb = g_FuncTable.m_pfnAllocateActiveBrushHandles(); + for ( i = 0; i < nb; i++ ) + { + b = (brush_t *)g_FuncTable.m_pfnGetActiveBrushHandle( i ); + if ( b->patchBrush ) { // patches in halflife ? + wadlist = AddToWadList( wadlist, b->pPatch->pShader->getName(),NULL ); + } + else + { + for ( f = b->brush_faces ; f ; f = f->next ) + { + wadlist = AddToWadList( wadlist, f->pShader->getName(),NULL ); + } + } + } + g_FuncTable.m_pfnReleaseActiveBrushHandles(); + + nb = g_FuncTable.m_pfnAllocateSelectedBrushHandles(); + for ( i = 0; i < nb; i++ ) { - b = (brush_t *)g_FuncTable.m_pfnGetActiveBrushHandle(i); - if (b->patchBrush) // patches in halflife ? - { - wadlist = AddToWadList(wadlist, b->pPatch->pShader->getName(),NULL); - } else - { - for (f=b->brush_faces ; f ; f=f->next) - { - wadlist = AddToWadList(wadlist, f->pShader->getName(),NULL); - } - } - } - g_FuncTable.m_pfnReleaseActiveBrushHandles(); - - nb = g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - for( i = 0; i < nb; i++ ) + b = (brush_t *)g_FuncTable.m_pfnGetSelectedBrushHandle( i ); + if ( b->patchBrush ) { // patches in halflife ? + wadlist = AddToWadList( wadlist, b->pPatch->pShader->getName(),NULL ); + } + else + { + for ( f = b->brush_faces ; f ; f = f->next ) + { + wadlist = AddToWadList( wadlist, f->pShader->getName(),NULL ); + } + } + } + g_FuncTable.m_pfnReleaseSelectedBrushHandles(); + + // Now we have a complete list of wadnames (without paths) so we just have to turn this + // back to a ; delimited list. + + wads[0] = 0; + while ( wadlist ) { - b = (brush_t *)g_FuncTable.m_pfnGetSelectedBrushHandle(i); - if (b->patchBrush) // patches in halflife ? - { - wadlist = AddToWadList(wadlist, b->pPatch->pShader->getName(),NULL); - } else - { - for (f=b->brush_faces ; f ; f=f->next) - { - wadlist = AddToWadList(wadlist, f->pShader->getName(),NULL); - } - } - } - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); - - // Now we have a complete list of wadnames (without paths) so we just have to turn this - // back to a ; delimited list. - - wads[0] = 0; - while (wadlist) - { - if (string_equal_nocase((char *)wadlist->data,"common-hydra.wad")) - { - Sys_Printf("Skipping radiant-supplied wad file %s\n",(char *)wadlist->data); - } - else - { - if (wads[0]) - strcat(wads,";"); - - actualwad = vfsGetFullPath((char *)wadlist->data); - - if (actualwad) - { - strcat(wads, actualwad); - } - else - { - Sys_Printf("WARNING: could not locate wad file %s\n",(char *)wadlist->data); - strcat(wads, (char *)wadlist->data); - } - } - - free (wadlist->data); - wadlist = g_slist_remove (wadlist, wadlist->data); - } - - // store the wad list back in the worldspawn. - if (wads[0]) - { - //free(pEpair->value); - //pEpair->value = strdup(wads); - SetKeyValue(pEntity, "wad", wads); - } + if ( string_equal_nocase( (char *)wadlist->data,"common-hydra.wad" ) ) { + Sys_Printf( "Skipping radiant-supplied wad file %s\n",(char *)wadlist->data ); + } + else + { + if ( wads[0] ) { + strcat( wads,";" ); + } + + actualwad = vfsGetFullPath( (char *)wadlist->data ); + + if ( actualwad ) { + strcat( wads, actualwad ); + } + else + { + Sys_Printf( "WARNING: could not locate wad file %s\n",(char *)wadlist->data ); + strcat( wads, (char *)wadlist->data ); + } + } + + free( wadlist->data ); + wadlist = g_slist_remove( wadlist, wadlist->data ); + } + + // store the wad list back in the worldspawn. + if ( wads[0] ) { + //free(pEpair->value); + //pEpair->value = strdup(wads); + SetKeyValue( pEntity, "wad", wads ); + } } @@ -461,39 +455,36 @@ const char *PLUGIN_NAME = "Q3 Texture Tools"; const char *PLUGIN_COMMANDS = "About...;Create/Update WAD keypair"; const char *PLUGIN_ABOUT = "HydraToolz for GTKRadiant\n\n" - "By Hydra!"; + "By Hydra!"; -extern "C" void* WINAPI QERPlug_GetFuncTable () -{ - return &g_FuncTable; +extern "C" void* WINAPI QERPlug_GetFuncTable(){ + return &g_FuncTable; } -const char* QERPlug_Init (void* hApp, void *pWidget) -{ - GtkWidget* pMainWidget = static_cast(pWidget); +const char* QERPlug_Init( void* hApp, void *pWidget ){ + GtkWidget* pMainWidget = static_cast( pWidget ); - g_pMainWnd = pMainWidget; - memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); - g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); - return "HydraToolz for GTKRadiant"; // do we need this ? hmmm + g_pMainWnd = pMainWidget; + memset( &g_FuncTable, 0, sizeof( _QERFuncTable_1 ) ); + g_FuncTable.m_nSize = sizeof( _QERFuncTable_1 ); + return "HydraToolz for GTKRadiant"; // do we need this ? hmmm } -const char* QERPlug_GetName() -{ - return (char*)PLUGIN_NAME; +const char* QERPlug_GetName(){ + return (char*)PLUGIN_NAME; } -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; +const char* QERPlug_GetCommandList(){ + return PLUGIN_COMMANDS; } -extern "C" void QERPlug_Dispatch(const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - if(!strcmp(p, "Create/Update WAD keypair")) +extern "C" void QERPlug_Dispatch( const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush ){ + if ( !strcmp( p, "Create/Update WAD keypair" ) ) { UpdateWadKeyPair(); - else if(!strcmp(p, "About...")) - g_FuncTable.m_pfnMessageBox((GtkWidget*)NULL, PLUGIN_ABOUT, "About", eMB_OK); + } + else if ( !strcmp( p, "About..." ) ) { + g_FuncTable.m_pfnMessageBox( (GtkWidget*)NULL, PLUGIN_ABOUT, "About", eMB_OK ); + } } // ============================================================================= @@ -502,41 +493,36 @@ extern "C" void QERPlug_Dispatch(const char* p, vec3_t vMin, vec3_t vMax, bool b CSynapseServer* g_pSynapseServer = NULL; CSynapseClientHydraToolz g_SynapseClient; -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "HydraToolz", sizeof(_QERPluginTable)); - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(g_FuncTable), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(VFS_MAJOR, "wad", sizeof(g_FileSystemTable), SYN_REQUIRE, &g_FileSystemTable); - g_SynapseClient.AddAPI(ENTITY_MAJOR, NULL, sizeof(g_EntityTable), SYN_REQUIRE, &g_EntityTable); - return &g_SynapseClient; +extern "C" CSynapseClient * SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces( const char *version, CSynapseServer *pServer ){ + if ( strcmp( version, SYNAPSE_VERSION ) ) { + Syn_Printf( "ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version ); + return NULL; + } + g_pSynapseServer = pServer; + g_pSynapseServer->IncRef(); + Set_Syn_Printf( g_pSynapseServer->Get_Syn_Printf() ); + + g_SynapseClient.AddAPI( PLUGIN_MAJOR, "HydraToolz", sizeof( _QERPluginTable ) ); + g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( g_FuncTable ), SYN_REQUIRE, &g_FuncTable ); + g_SynapseClient.AddAPI( VFS_MAJOR, "wad", sizeof( g_FileSystemTable ), SYN_REQUIRE, &g_FileSystemTable ); + g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( g_EntityTable ), SYN_REQUIRE, &g_EntityTable ); + return &g_SynapseClient; } -bool CSynapseClientHydraToolz::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable *pTable = static_cast<_QERPluginTable*>(pAPI->mpTable); - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; +bool CSynapseClientHydraToolz::RequestAPI( APIDescriptor_t *pAPI ){ + if ( !strcmp( pAPI->major_name, PLUGIN_MAJOR ) ) { + _QERPluginTable *pTable = static_cast<_QERPluginTable*>( pAPI->mpTable ); + pTable->m_pfnQERPlug_Init = QERPlug_Init; + pTable->m_pfnQERPlug_GetName = QERPlug_GetName; + pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + return true; + } + + Syn_Printf( "ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo() ); + return false; } -const char* CSynapseClientHydraToolz::GetInfo() -{ - return "HydraToolz plugin built " __DATE__ " " RADIANT_VERSION; +const char* CSynapseClientHydraToolz::GetInfo(){ + return "HydraToolz plugin built " __DATE__ " " RADIANT_VERSION; } diff --git a/contrib/hydratoolz/plugin.h b/contrib/hydratoolz/plugin.h index 70e3ea9b..7e9e9771 100644 --- a/contrib/hydratoolz/plugin.h +++ b/contrib/hydratoolz/plugin.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #ifndef _PLUGIN_H_ #define _PLUGIN_H_ @@ -47,12 +47,12 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class CSynapseClientHydraToolz : public CSynapseClient { public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); +// CSynapseClient API +bool RequestAPI( APIDescriptor_t *pAPI ); +const char* GetInfo(); - CSynapseClientHydraToolz() { } - virtual ~CSynapseClientHydraToolz() { } +CSynapseClientHydraToolz() { } +virtual ~CSynapseClientHydraToolz() { } }; #endif // _PLUGIN_H_ diff --git a/contrib/prtview/AboutDialog.cpp b/contrib/prtview/AboutDialog.cpp index 4ac45ab8..1baec68d 100644 --- a/contrib/prtview/AboutDialog.cpp +++ b/contrib/prtview/AboutDialog.cpp @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "AboutDialog.h" #include @@ -26,78 +26,75 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "prtview.h" #include "ConfigDialog.h" -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; +static void dialog_button_callback( GtkWidget *widget, gpointer data ){ + GtkWidget *parent; + int *loop, *ret; - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + ret = (int*)g_object_get_data( G_OBJECT( parent ), "ret" ); - *loop = 0; - *ret = gpointer_to_int(data); + *loop = 0; + *ret = gpointer_to_int( data ); } -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; +static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ + int *loop; - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; + gtk_widget_hide( widget ); + loop = (int*)g_object_get_data( G_OBJECT( widget ), "loop" ); + *loop = 0; - return TRUE; + return TRUE; } -void DoAboutDlg () -{ - GtkWidget *dlg, *hbox, *vbox, *button, *label; - int loop = 1, ret = IDCANCEL; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "About Portal Viewer"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_widget_show (hbox); - gtk_container_add (GTK_CONTAINER (dlg), hbox); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 10); - - label = gtk_label_new ("Version 1.000\n\n" - "Gtk port by Leonardo Zide\nleo@lokigames.com\n\n" - "Written by Geoffrey DeWan\ngdewan@prairienet.org\n\n" - "Built against NetRadiant " RADIANT_VERSION "\n" - __DATE__ - ); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT); - - vbox = gtk_vbox_new (FALSE, 0); - gtk_widget_show (vbox); - gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); +void DoAboutDlg(){ + GtkWidget *dlg, *hbox, *vbox, *button, *label; + int loop = 1, ret = IDCANCEL; + + dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( dlg ), "About Portal Viewer" ); + gtk_signal_connect( GTK_OBJECT( dlg ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( dlg ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); + g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); + + hbox = gtk_hbox_new( FALSE, 10 ); + gtk_widget_show( hbox ); + gtk_container_add( GTK_CONTAINER( dlg ), hbox ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ), 10 ); + + label = gtk_label_new( "Version 1.000\n\n" + "Gtk port by Leonardo Zide\nleo@lokigames.com\n\n" + "Written by Geoffrey DeWan\ngdewan@prairienet.org\n\n" + "Built against NetRadiant " RADIANT_VERSION "\n" + __DATE__ + ); + gtk_widget_show( label ); + gtk_box_pack_start( GTK_BOX( hbox ), label, TRUE, TRUE, 0 ); + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); + + vbox = gtk_vbox_new( FALSE, 0 ); + gtk_widget_show( vbox ); + gtk_box_pack_start( GTK_BOX( hbox ), vbox, FALSE, FALSE, 0 ); + + button = gtk_button_new_with_label( "OK" ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + gtk_widget_set_usize( button, 60, -2 ); + + gtk_grab_add( dlg ); + gtk_widget_show( dlg ); + + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( dlg ); + gtk_widget_destroy( dlg ); } diff --git a/contrib/prtview/AboutDialog.h b/contrib/prtview/AboutDialog.h index bf72885f..b46fa93a 100644 --- a/contrib/prtview/AboutDialog.h +++ b/contrib/prtview/AboutDialog.h @@ -1,25 +1,25 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_ABOUTDIALOG_H) +#if !defined( INCLUDED_ABOUTDIALOG_H ) #define INCLUDED_ABOUTDIALOG_H -void DoAboutDlg (); +void DoAboutDlg(); #endif diff --git a/contrib/prtview/ConfigDialog.cpp b/contrib/prtview/ConfigDialog.cpp index 0b52adad..a91a6a2b 100644 --- a/contrib/prtview/ConfigDialog.cpp +++ b/contrib/prtview/ConfigDialog.cpp @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "ConfigDialog.h" #include @@ -27,500 +27,471 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "prtview.h" #include "portals.h" -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; +static void dialog_button_callback( GtkWidget *widget, gpointer data ){ + GtkWidget *parent; + int *loop, *ret; - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + ret = (int*)g_object_get_data( G_OBJECT( parent ), "ret" ); - *loop = 0; - *ret = gpointer_to_int(data); + *loop = 0; + *ret = gpointer_to_int( data ); } -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; +static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ + int *loop; - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; + gtk_widget_hide( widget ); + loop = (int*)g_object_get_data( G_OBJECT( widget ), "loop" ); + *loop = 0; - return TRUE; + return TRUE; } // ============================================================================= // Color selection dialog -static int DoColor (PackedColour *c) -{ - GtkWidget* dlg; - double clr[4]; - int loop = 1, ret = IDCANCEL; - - clr[0] = ((double)GetRValue (*c)) / 255.0; - clr[1] = ((double)GetGValue (*c)) / 255.0; - clr[2] = ((double)GetBValue (*c)) / 255.0; - - dlg = gtk_color_selection_dialog_new ("Choose Color"); - gtk_color_selection_set_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_signal_connect (GTK_OBJECT (GTK_COLOR_SELECTION_DIALOG (dlg)->ok_button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_signal_connect (GTK_OBJECT (GTK_COLOR_SELECTION_DIALOG (dlg)->cancel_button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - gtk_widget_show(dlg); - gtk_grab_add(dlg); - - while (loop) - gtk_main_iteration (); - - gtk_color_selection_get_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); - - if (ret == IDOK) - { - *c = RGB (clr[0]*255, clr[1]*255, clr[2]*255); - } - - return ret; +static int DoColor( PackedColour *c ){ + GtkWidget* dlg; + double clr[4]; + int loop = 1, ret = IDCANCEL; + + clr[0] = ( (double)GetRValue( *c ) ) / 255.0; + clr[1] = ( (double)GetGValue( *c ) ) / 255.0; + clr[2] = ( (double)GetBValue( *c ) ) / 255.0; + + dlg = gtk_color_selection_dialog_new( "Choose Color" ); + gtk_color_selection_set_color( GTK_COLOR_SELECTION( GTK_COLOR_SELECTION_DIALOG( dlg )->colorsel ), clr ); + gtk_signal_connect( GTK_OBJECT( dlg ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( dlg ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + gtk_signal_connect( GTK_OBJECT( GTK_COLOR_SELECTION_DIALOG( dlg )->ok_button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + gtk_signal_connect( GTK_OBJECT( GTK_COLOR_SELECTION_DIALOG( dlg )->cancel_button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); + g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); + + gtk_widget_show( dlg ); + gtk_grab_add( dlg ); + + while ( loop ) + gtk_main_iteration(); + + gtk_color_selection_get_color( GTK_COLOR_SELECTION( GTK_COLOR_SELECTION_DIALOG( dlg )->colorsel ), clr ); + + gtk_grab_remove( dlg ); + gtk_widget_destroy( dlg ); + + if ( ret == IDOK ) { + *c = RGB( clr[0] * 255, clr[1] * 255, clr[2] * 255 ); + } + + return ret; } -static void Set2DText (GtkWidget* label) -{ - char s[40]; +static void Set2DText( GtkWidget* label ){ + char s[40]; - sprintf(s, "Line Width = %6.3f", portals.width_2d * 0.5f); + sprintf( s, "Line Width = %6.3f", portals.width_2d * 0.5f ); - gtk_label_set_text (GTK_LABEL (label), s); + gtk_label_set_text( GTK_LABEL( label ), s ); } -static void Set3DText (GtkWidget* label) -{ - char s[40]; +static void Set3DText( GtkWidget* label ){ + char s[40]; - sprintf(s, "Line Width = %6.3f", portals.width_3d * 0.5f); + sprintf( s, "Line Width = %6.3f", portals.width_3d * 0.5f ); - gtk_label_set_text (GTK_LABEL (label), s); + gtk_label_set_text( GTK_LABEL( label ), s ); } -static void Set3DTransText (GtkWidget* label) -{ - char s[40]; +static void Set3DTransText( GtkWidget* label ){ + char s[40]; - sprintf(s, "Polygon transparency = %d%%", (int)portals.trans_3d); + sprintf( s, "Polygon transparency = %d%%", (int)portals.trans_3d ); - gtk_label_set_text (GTK_LABEL (label), s); + gtk_label_set_text( GTK_LABEL( label ), s ); } -static void SetClipText (GtkWidget* label) -{ - char s[40]; +static void SetClipText( GtkWidget* label ){ + char s[40]; - sprintf(s, "Cubic clip range = %d", (int)portals.clip_range * 64); + sprintf( s, "Cubic clip range = %d", (int)portals.clip_range * 64 ); - gtk_label_set_text (GTK_LABEL (label), s); + gtk_label_set_text( GTK_LABEL( label ), s ); } -static void OnScroll2d (GtkAdjustment *adj, gpointer data) -{ - portals.width_2d = static_cast(adj->value); - Set2DText (GTK_WIDGET (data)); +static void OnScroll2d( GtkAdjustment *adj, gpointer data ){ + portals.width_2d = static_cast( adj->value ); + Set2DText( GTK_WIDGET( data ) ); - Portals_shadersChanged(); - SceneChangeNotify(); + Portals_shadersChanged(); + SceneChangeNotify(); } -static void OnScroll3d (GtkAdjustment *adj, gpointer data) -{ - portals.width_3d = static_cast(adj->value); - Set3DText (GTK_WIDGET (data)); +static void OnScroll3d( GtkAdjustment *adj, gpointer data ){ + portals.width_3d = static_cast( adj->value ); + Set3DText( GTK_WIDGET( data ) ); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnScrollTrans (GtkAdjustment *adj, gpointer data) -{ - portals.trans_3d = static_cast(adj->value); - Set3DTransText (GTK_WIDGET (data)); +static void OnScrollTrans( GtkAdjustment *adj, gpointer data ){ + portals.trans_3d = static_cast( adj->value ); + Set3DTransText( GTK_WIDGET( data ) ); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnScrollClip (GtkAdjustment *adj, gpointer data) -{ - portals.clip_range = static_cast(adj->value); - SetClipText (GTK_WIDGET (data)); +static void OnScrollClip( GtkAdjustment *adj, gpointer data ){ + portals.clip_range = static_cast( adj->value ); + SetClipText( GTK_WIDGET( data ) ); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnAntiAlias2d (GtkWidget *widget, gpointer data) -{ - portals.aa_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnAntiAlias2d( GtkWidget *widget, gpointer data ){ + portals.aa_2d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - Portals_shadersChanged(); + Portals_shadersChanged(); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnConfig2d (GtkWidget *widget, gpointer data) -{ - portals.show_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnConfig2d( GtkWidget *widget, gpointer data ){ + portals.show_2d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnColor2d (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_2d) == IDOK) - { - Portals_shadersChanged(); +static void OnColor2d( GtkWidget *widget, gpointer data ){ + if ( DoColor( &portals.color_2d ) == IDOK ) { + Portals_shadersChanged(); - SceneChangeNotify(); - } + SceneChangeNotify(); + } } -static void OnConfig3d (GtkWidget *widget, gpointer data) -{ - portals.show_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnConfig3d( GtkWidget *widget, gpointer data ){ + portals.show_3d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnAntiAlias3d (GtkWidget *widget, gpointer data) -{ - portals.aa_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnAntiAlias3d( GtkWidget *widget, gpointer data ){ + portals.aa_3d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - Portals_shadersChanged(); - SceneChangeNotify(); + Portals_shadersChanged(); + SceneChangeNotify(); } -static void OnColor3d (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_3d) == IDOK) - { - Portals_shadersChanged(); +static void OnColor3d( GtkWidget *widget, gpointer data ){ + if ( DoColor( &portals.color_3d ) == IDOK ) { + Portals_shadersChanged(); - SceneChangeNotify(); - } + SceneChangeNotify(); + } } -static void OnColorFog (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_fog) == IDOK) - { - Portals_shadersChanged(); +static void OnColorFog( GtkWidget *widget, gpointer data ){ + if ( DoColor( &portals.color_fog ) == IDOK ) { + Portals_shadersChanged(); - SceneChangeNotify(); - } + SceneChangeNotify(); + } } -static void OnFog (GtkWidget *widget, gpointer data) -{ - portals.fog = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnFog( GtkWidget *widget, gpointer data ){ + portals.fog = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - Portals_shadersChanged(); - SceneChangeNotify(); + Portals_shadersChanged(); + SceneChangeNotify(); } -static void OnSelchangeZbuffer (GtkWidget *widget, gpointer data) -{ - portals.zbuffer = gpointer_to_int(data); +static void OnSelchangeZbuffer( GtkWidget *widget, gpointer data ){ + portals.zbuffer = gpointer_to_int( data ); - Portals_shadersChanged(); - SceneChangeNotify(); + Portals_shadersChanged(); + SceneChangeNotify(); } -static void OnPoly (GtkWidget *widget, gpointer data) -{ - portals.polygons = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); +static void OnPoly( GtkWidget *widget, gpointer data ){ + portals.polygons = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnLines (GtkWidget *widget, gpointer data) -{ - portals.lines = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); +static void OnLines( GtkWidget *widget, gpointer data ){ + portals.lines = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ); - SceneChangeNotify(); + SceneChangeNotify(); } -static void OnClip (GtkWidget *widget, gpointer data) -{ - portals.clip = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; +static void OnClip( GtkWidget *widget, gpointer data ){ + portals.clip = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( widget ) ) ? true : false; - SceneChangeNotify(); + SceneChangeNotify(); } -void DoConfigDialog () -{ - GtkWidget *dlg, *hbox, *vbox, *vbox2, *button, *table, *frame; - GtkWidget *lw3slider, *lw3label, *lw2slider, *lw2label, *zlist, *menu, *item; - GtkWidget *aa2check, *aa3check, *depthcheck, *linescheck, *polyscheck; - GtkWidget *transslider, *translabel, *clipslider, *cliplabel; - GtkWidget *show2check, *show3check, *portalcheck; - int loop = 1, ret = IDCANCEL; - GtkObject *adj; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "Portal Viewer Configuration"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - frame = gtk_frame_new ("3D View"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox2); - gtk_container_add (GTK_CONTAINER (frame), vbox2); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 5); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, TRUE, 0); - - adj = gtk_adjustment_new (portals.width_3d, 2, 40, 1, 1, 0); - lw3slider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (lw3slider); - gtk_box_pack_start (GTK_BOX (hbox), lw3slider, TRUE, TRUE, 0); - gtk_scale_set_draw_value (GTK_SCALE (lw3slider), FALSE); - - lw3label = gtk_label_new (""); - gtk_widget_show (lw3label); - gtk_box_pack_start (GTK_BOX (hbox), lw3label, FALSE, TRUE, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScroll3d), lw3label); - - table = gtk_table_new (2, 4, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox2), table, TRUE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - button = gtk_button_new_with_label ("Color"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColor3d), NULL); - - button = gtk_button_new_with_label ("Depth Color"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColorFog), NULL); - - aa3check = gtk_check_button_new_with_label ("Anti-Alias (May not work on some video cards)"); - gtk_widget_show (aa3check); - gtk_table_attach (GTK_TABLE (table), aa3check, 1, 4, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (aa3check), "toggled", GTK_SIGNAL_FUNC (OnAntiAlias3d), NULL); - - depthcheck = gtk_check_button_new_with_label ("Depth Cue"); - gtk_widget_show (depthcheck); - gtk_table_attach (GTK_TABLE (table), depthcheck, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (depthcheck), "toggled", GTK_SIGNAL_FUNC (OnFog), NULL); - - linescheck = gtk_check_button_new_with_label ("Lines"); - gtk_widget_show (linescheck); - gtk_table_attach (GTK_TABLE (table), linescheck, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (linescheck), "toggled", GTK_SIGNAL_FUNC (OnLines), NULL); - - polyscheck = gtk_check_button_new_with_label ("Polygons"); - gtk_widget_show (polyscheck); - gtk_table_attach (GTK_TABLE (table), polyscheck, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (polyscheck), "toggled", GTK_SIGNAL_FUNC (OnPoly), NULL); - - zlist = gtk_option_menu_new (); - gtk_widget_show (zlist); - gtk_box_pack_start (GTK_BOX (vbox2), zlist, TRUE, FALSE, 0); - - menu = gtk_menu_new (); - gtk_widget_show (menu); - gtk_option_menu_set_menu (GTK_OPTION_MENU (zlist), menu); - - item = gtk_menu_item_new_with_label ("Z-Buffer Test and Write (recommended for solid or no polygons)"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (0)); - gtk_menu_append (GTK_MENU (menu), item); - - item = gtk_menu_item_new_with_label ("Z-Buffer Test Only (recommended for transparent polygons)"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (1)); - gtk_menu_append (GTK_MENU (menu), item); - - item = gtk_menu_item_new_with_label ("Z-Buffer Off"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (2)); - gtk_menu_append (GTK_MENU (menu), item); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox2), table, TRUE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - adj = gtk_adjustment_new (portals.trans_3d, 0, 100, 1, 1, 0); - transslider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (transslider); - gtk_table_attach (GTK_TABLE (table), transslider, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_scale_set_draw_value (GTK_SCALE (transslider), FALSE); - - translabel = gtk_label_new (""); - gtk_widget_show (translabel); - gtk_table_attach (GTK_TABLE (table), translabel, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (translabel), 0.0, 0.0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScrollTrans), translabel); - - adj = gtk_adjustment_new (portals.clip_range, 1, 128, 1, 1, 0); - clipslider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (clipslider); - gtk_table_attach (GTK_TABLE (table), clipslider, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_scale_set_draw_value (GTK_SCALE (clipslider), FALSE); - - cliplabel = gtk_label_new (""); - gtk_widget_show (cliplabel); - gtk_table_attach (GTK_TABLE (table), cliplabel, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (cliplabel), 0.0, 0.0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScrollClip), cliplabel); - - hbox = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - show3check = gtk_check_button_new_with_label ("Show"); - gtk_widget_show (show3check); - gtk_box_pack_start (GTK_BOX (hbox), show3check, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (show3check), "toggled", GTK_SIGNAL_FUNC (OnConfig3d), NULL); - - portalcheck = gtk_check_button_new_with_label ("Portal cubic clipper"); - gtk_widget_show (portalcheck); - gtk_box_pack_start (GTK_BOX (hbox), portalcheck, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (portalcheck), "toggled", GTK_SIGNAL_FUNC (OnClip), NULL); - - frame = gtk_frame_new ("2D View"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox2); - gtk_container_add (GTK_CONTAINER (frame), vbox2); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 5); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - adj = gtk_adjustment_new (portals.width_2d, 2, 40, 1, 1, 0); - lw2slider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (lw2slider); - gtk_box_pack_start (GTK_BOX (hbox), lw2slider, TRUE, TRUE, 0); - gtk_scale_set_draw_value (GTK_SCALE (lw2slider), FALSE); - - lw2label = gtk_label_new (""); - gtk_widget_show (lw2label); - gtk_box_pack_start (GTK_BOX (hbox), lw2label, FALSE, TRUE, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScroll2d), lw2label); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - button = gtk_button_new_with_label ("Color"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColor2d), NULL); - gtk_widget_set_usize (button, 60, -2); - - aa2check = gtk_check_button_new_with_label ("Anti-Alias (May not work on some video cards)"); - gtk_widget_show (aa2check); - gtk_box_pack_start (GTK_BOX (hbox), aa2check, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (aa2check), "toggled", GTK_SIGNAL_FUNC (OnAntiAlias2d), NULL); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - show2check = gtk_check_button_new_with_label ("Show"); - gtk_widget_show (show2check); - gtk_box_pack_start (GTK_BOX (hbox), show2check, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (show2check), "toggled", GTK_SIGNAL_FUNC (OnConfig2d), NULL); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - // initialize dialog - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (show2check), portals.show_2d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (aa2check), portals.aa_2d); - Set2DText (lw2label); - - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (show3check), portals.show_3d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (depthcheck), portals.fog); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (polyscheck), portals.polygons); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (linescheck), portals.lines); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (aa3check), portals.aa_3d); - gtk_option_menu_set_history (GTK_OPTION_MENU (zlist), portals.zbuffer); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (portalcheck), portals.clip); - - Set3DText (lw3label); - Set3DTransText (translabel); - SetClipText (cliplabel); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); +void DoConfigDialog(){ + GtkWidget *dlg, *hbox, *vbox, *vbox2, *button, *table, *frame; + GtkWidget *lw3slider, *lw3label, *lw2slider, *lw2label, *zlist, *menu, *item; + GtkWidget *aa2check, *aa3check, *depthcheck, *linescheck, *polyscheck; + GtkWidget *transslider, *translabel, *clipslider, *cliplabel; + GtkWidget *show2check, *show3check, *portalcheck; + int loop = 1, ret = IDCANCEL; + GtkObject *adj; + + dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( dlg ), "Portal Viewer Configuration" ); + gtk_signal_connect( GTK_OBJECT( dlg ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( dlg ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); + g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); + + vbox = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( dlg ), vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + frame = gtk_frame_new( "3D View" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, TRUE, TRUE, 0 ); + + vbox2 = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox2 ); + gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 5 ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox, TRUE, TRUE, 0 ); + + adj = gtk_adjustment_new( portals.width_3d, 2, 40, 1, 1, 0 ); + lw3slider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); + gtk_widget_show( lw3slider ); + gtk_box_pack_start( GTK_BOX( hbox ), lw3slider, TRUE, TRUE, 0 ); + gtk_scale_set_draw_value( GTK_SCALE( lw3slider ), FALSE ); + + lw3label = gtk_label_new( "" ); + gtk_widget_show( lw3label ); + gtk_box_pack_start( GTK_BOX( hbox ), lw3label, FALSE, TRUE, 0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( OnScroll3d ), lw3label ); + + table = gtk_table_new( 2, 4, FALSE ); + gtk_widget_show( table ); + gtk_box_pack_start( GTK_BOX( vbox2 ), table, TRUE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + button = gtk_button_new_with_label( "Color" ); + gtk_widget_show( button ); + gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", GTK_SIGNAL_FUNC( OnColor3d ), NULL ); + + button = gtk_button_new_with_label( "Depth Color" ); + gtk_widget_show( button ); + gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", GTK_SIGNAL_FUNC( OnColorFog ), NULL ); + + aa3check = gtk_check_button_new_with_label( "Anti-Alias (May not work on some video cards)" ); + gtk_widget_show( aa3check ); + gtk_table_attach( GTK_TABLE( table ), aa3check, 1, 4, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( aa3check ), "toggled", GTK_SIGNAL_FUNC( OnAntiAlias3d ), NULL ); + + depthcheck = gtk_check_button_new_with_label( "Depth Cue" ); + gtk_widget_show( depthcheck ); + gtk_table_attach( GTK_TABLE( table ), depthcheck, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( depthcheck ), "toggled", GTK_SIGNAL_FUNC( OnFog ), NULL ); + + linescheck = gtk_check_button_new_with_label( "Lines" ); + gtk_widget_show( linescheck ); + gtk_table_attach( GTK_TABLE( table ), linescheck, 2, 3, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( linescheck ), "toggled", GTK_SIGNAL_FUNC( OnLines ), NULL ); + + polyscheck = gtk_check_button_new_with_label( "Polygons" ); + gtk_widget_show( polyscheck ); + gtk_table_attach( GTK_TABLE( table ), polyscheck, 3, 4, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_signal_connect( GTK_OBJECT( polyscheck ), "toggled", GTK_SIGNAL_FUNC( OnPoly ), NULL ); + + zlist = gtk_option_menu_new(); + gtk_widget_show( zlist ); + gtk_box_pack_start( GTK_BOX( vbox2 ), zlist, TRUE, FALSE, 0 ); + + menu = gtk_menu_new(); + gtk_widget_show( menu ); + gtk_option_menu_set_menu( GTK_OPTION_MENU( zlist ), menu ); + + item = gtk_menu_item_new_with_label( "Z-Buffer Test and Write (recommended for solid or no polygons)" ); + gtk_widget_show( item ); + gtk_signal_connect( GTK_OBJECT( item ), "activate", + GTK_SIGNAL_FUNC( OnSelchangeZbuffer ), GINT_TO_POINTER( 0 ) ); + gtk_menu_append( GTK_MENU( menu ), item ); + + item = gtk_menu_item_new_with_label( "Z-Buffer Test Only (recommended for transparent polygons)" ); + gtk_widget_show( item ); + gtk_signal_connect( GTK_OBJECT( item ), "activate", + GTK_SIGNAL_FUNC( OnSelchangeZbuffer ), GINT_TO_POINTER( 1 ) ); + gtk_menu_append( GTK_MENU( menu ), item ); + + item = gtk_menu_item_new_with_label( "Z-Buffer Off" ); + gtk_widget_show( item ); + gtk_signal_connect( GTK_OBJECT( item ), "activate", + GTK_SIGNAL_FUNC( OnSelchangeZbuffer ), GINT_TO_POINTER( 2 ) ); + gtk_menu_append( GTK_MENU( menu ), item ); + + table = gtk_table_new( 2, 2, FALSE ); + gtk_widget_show( table ); + gtk_box_pack_start( GTK_BOX( vbox2 ), table, TRUE, TRUE, 0 ); + gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); + gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); + + adj = gtk_adjustment_new( portals.trans_3d, 0, 100, 1, 1, 0 ); + transslider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); + gtk_widget_show( transslider ); + gtk_table_attach( GTK_TABLE( table ), transslider, 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_scale_set_draw_value( GTK_SCALE( transslider ), FALSE ); + + translabel = gtk_label_new( "" ); + gtk_widget_show( translabel ); + gtk_table_attach( GTK_TABLE( table ), translabel, 1, 2, 0, 1, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( translabel ), 0.0, 0.0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( OnScrollTrans ), translabel ); + + adj = gtk_adjustment_new( portals.clip_range, 1, 128, 1, 1, 0 ); + clipslider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); + gtk_widget_show( clipslider ); + gtk_table_attach( GTK_TABLE( table ), clipslider, 0, 1, 1, 2, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_scale_set_draw_value( GTK_SCALE( clipslider ), FALSE ); + + cliplabel = gtk_label_new( "" ); + gtk_widget_show( cliplabel ); + gtk_table_attach( GTK_TABLE( table ), cliplabel, 1, 2, 1, 2, + (GtkAttachOptions) ( GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); + gtk_misc_set_alignment( GTK_MISC( cliplabel ), 0.0, 0.0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( OnScrollClip ), cliplabel ); + + hbox = gtk_hbox_new( TRUE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox, TRUE, FALSE, 0 ); + + show3check = gtk_check_button_new_with_label( "Show" ); + gtk_widget_show( show3check ); + gtk_box_pack_start( GTK_BOX( hbox ), show3check, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( show3check ), "toggled", GTK_SIGNAL_FUNC( OnConfig3d ), NULL ); + + portalcheck = gtk_check_button_new_with_label( "Portal cubic clipper" ); + gtk_widget_show( portalcheck ); + gtk_box_pack_start( GTK_BOX( hbox ), portalcheck, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( portalcheck ), "toggled", GTK_SIGNAL_FUNC( OnClip ), NULL ); + + frame = gtk_frame_new( "2D View" ); + gtk_widget_show( frame ); + gtk_box_pack_start( GTK_BOX( vbox ), frame, TRUE, TRUE, 0 ); + + vbox2 = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox2 ); + gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); + gtk_container_set_border_width( GTK_CONTAINER( vbox2 ), 5 ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox, TRUE, FALSE, 0 ); + + adj = gtk_adjustment_new( portals.width_2d, 2, 40, 1, 1, 0 ); + lw2slider = gtk_hscale_new( GTK_ADJUSTMENT( adj ) ); + gtk_widget_show( lw2slider ); + gtk_box_pack_start( GTK_BOX( hbox ), lw2slider, TRUE, TRUE, 0 ); + gtk_scale_set_draw_value( GTK_SCALE( lw2slider ), FALSE ); + + lw2label = gtk_label_new( "" ); + gtk_widget_show( lw2label ); + gtk_box_pack_start( GTK_BOX( hbox ), lw2label, FALSE, TRUE, 0 ); + gtk_signal_connect( adj, "value_changed", GTK_SIGNAL_FUNC( OnScroll2d ), lw2label ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox, TRUE, FALSE, 0 ); + + button = gtk_button_new_with_label( "Color" ); + gtk_widget_show( button ); + gtk_box_pack_start( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", GTK_SIGNAL_FUNC( OnColor2d ), NULL ); + gtk_widget_set_usize( button, 60, -2 ); + + aa2check = gtk_check_button_new_with_label( "Anti-Alias (May not work on some video cards)" ); + gtk_widget_show( aa2check ); + gtk_box_pack_start( GTK_BOX( hbox ), aa2check, TRUE, TRUE, 0 ); + gtk_signal_connect( GTK_OBJECT( aa2check ), "toggled", GTK_SIGNAL_FUNC( OnAntiAlias2d ), NULL ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox2 ), hbox, TRUE, FALSE, 0 ); + + show2check = gtk_check_button_new_with_label( "Show" ); + gtk_widget_show( show2check ); + gtk_box_pack_start( GTK_BOX( hbox ), show2check, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( show2check ), "toggled", GTK_SIGNAL_FUNC( OnConfig2d ), NULL ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + + button = gtk_button_new_with_label( "OK" ); + gtk_widget_show( button ); + gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + gtk_widget_set_usize( button, 60, -2 ); + + // initialize dialog + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( show2check ), portals.show_2d ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( aa2check ), portals.aa_2d ); + Set2DText( lw2label ); + + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( show3check ), portals.show_3d ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( depthcheck ), portals.fog ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( polyscheck ), portals.polygons ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( linescheck ), portals.lines ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( aa3check ), portals.aa_3d ); + gtk_option_menu_set_history( GTK_OPTION_MENU( zlist ), portals.zbuffer ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( portalcheck ), portals.clip ); + + Set3DText( lw3label ); + Set3DTransText( translabel ); + SetClipText( cliplabel ); + + gtk_grab_add( dlg ); + gtk_widget_show( dlg ); + + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( dlg ); + gtk_widget_destroy( dlg ); } - diff --git a/contrib/prtview/ConfigDialog.h b/contrib/prtview/ConfigDialog.h index ef35db06..a9725847 100644 --- a/contrib/prtview/ConfigDialog.h +++ b/contrib/prtview/ConfigDialog.h @@ -1,25 +1,25 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_CONFIGDIALOG_H) +#if !defined( INCLUDED_CONFIGDIALOG_H ) #define INCLUDED_CONFIGDIALOG_H -void DoConfigDialog (); +void DoConfigDialog(); #endif diff --git a/contrib/prtview/LoadPortalFileDialog.cpp b/contrib/prtview/LoadPortalFileDialog.cpp index 03d84397..f3d4df8d 100644 --- a/contrib/prtview/LoadPortalFileDialog.cpp +++ b/contrib/prtview/LoadPortalFileDialog.cpp @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ // LoadPortalFileDialog.cpp : implementation file // @@ -33,170 +33,163 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "prtview.h" #include "portals.h" -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; +static void dialog_button_callback( GtkWidget *widget, gpointer data ){ + GtkWidget *parent; + int *loop, *ret; - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + ret = (int*)g_object_get_data( G_OBJECT( parent ), "ret" ); - *loop = 0; - *ret = gpointer_to_int(data); + *loop = 0; + *ret = gpointer_to_int( data ); } -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; +static gint dialog_delete_callback( GtkWidget *widget, GdkEvent* event, gpointer data ){ + int *loop; - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; + gtk_widget_hide( widget ); + loop = (int*)g_object_get_data( G_OBJECT( widget ), "loop" ); + *loop = 0; - return TRUE; + return TRUE; } -static void file_sel_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop; - char **filename; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - filename = (char**)g_object_get_data (G_OBJECT (parent), "filename"); - - *loop = 0; - if (gpointer_to_int(data) == IDOK) - *filename = g_strdup (gtk_file_selection_get_filename (GTK_FILE_SELECTION (parent))); +static void file_sel_callback( GtkWidget *widget, gpointer data ){ + GtkWidget *parent; + int *loop; + char **filename; + + parent = gtk_widget_get_toplevel( widget ); + loop = (int*)g_object_get_data( G_OBJECT( parent ), "loop" ); + filename = (char**)g_object_get_data( G_OBJECT( parent ), "filename" ); + + *loop = 0; + if ( gpointer_to_int( data ) == IDOK ) { + *filename = g_strdup( gtk_file_selection_get_filename( GTK_FILE_SELECTION( parent ) ) ); + } } -static void change_clicked (GtkWidget *widget, gpointer data) -{ - GtkWidget* file_sel; - char* filename = NULL; - int loop = 1; - - file_sel = gtk_file_selection_new ("Locate portal (.prt) file"); - gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (file_sel)->ok_button), "clicked", - GTK_SIGNAL_FUNC (file_sel_callback), GINT_TO_POINTER (IDOK)); - gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (file_sel)->cancel_button), "clicked", - GTK_SIGNAL_FUNC (file_sel_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_signal_connect (GTK_OBJECT (file_sel), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_file_selection_hide_fileop_buttons (GTK_FILE_SELECTION (file_sel)); - - g_object_set_data (G_OBJECT (file_sel), "loop", &loop); - g_object_set_data (G_OBJECT (file_sel), "filename", &filename); - gtk_file_selection_set_filename (GTK_FILE_SELECTION (file_sel), portals.fn); - - gtk_grab_add (file_sel); - gtk_widget_show (file_sel); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (file_sel); - gtk_widget_destroy (file_sel); - - if (filename != NULL) - { - strcpy (portals.fn, filename); - gtk_entry_set_text (GTK_ENTRY (data), filename); - g_free (filename); - } +static void change_clicked( GtkWidget *widget, gpointer data ){ + GtkWidget* file_sel; + char* filename = NULL; + int loop = 1; + + file_sel = gtk_file_selection_new( "Locate portal (.prt) file" ); + gtk_signal_connect( GTK_OBJECT( GTK_FILE_SELECTION( file_sel )->ok_button ), "clicked", + GTK_SIGNAL_FUNC( file_sel_callback ), GINT_TO_POINTER( IDOK ) ); + gtk_signal_connect( GTK_OBJECT( GTK_FILE_SELECTION( file_sel )->cancel_button ), "clicked", + GTK_SIGNAL_FUNC( file_sel_callback ), GINT_TO_POINTER( IDCANCEL ) ); + gtk_signal_connect( GTK_OBJECT( file_sel ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_file_selection_hide_fileop_buttons( GTK_FILE_SELECTION( file_sel ) ); + + g_object_set_data( G_OBJECT( file_sel ), "loop", &loop ); + g_object_set_data( G_OBJECT( file_sel ), "filename", &filename ); + gtk_file_selection_set_filename( GTK_FILE_SELECTION( file_sel ), portals.fn ); + + gtk_grab_add( file_sel ); + gtk_widget_show( file_sel ); + + while ( loop ) + gtk_main_iteration(); + + gtk_grab_remove( file_sel ); + gtk_widget_destroy( file_sel ); + + if ( filename != NULL ) { + strcpy( portals.fn, filename ); + gtk_entry_set_text( GTK_ENTRY( data ), filename ); + g_free( filename ); + } } -int DoLoadPortalFileDialog () -{ - GtkWidget *dlg, *vbox, *hbox, *button, *entry, *check2d, *check3d; - int loop = 1, ret = IDCANCEL; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "Load .prt"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_entry_set_editable (GTK_ENTRY (entry), FALSE); - gtk_box_pack_start (GTK_BOX (vbox), entry, FALSE, FALSE, 0); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - check3d = gtk_check_button_new_with_label ("Show 3D"); - gtk_widget_show (check3d); - gtk_box_pack_start (GTK_BOX (hbox), check3d, FALSE, FALSE, 0); - - check2d = gtk_check_button_new_with_label ("Show 2D"); - gtk_widget_show (check2d); - gtk_box_pack_start (GTK_BOX (hbox), check2d, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("Change"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (change_clicked), entry); - gtk_widget_set_usize (button, 60, -2); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("Cancel"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_set_usize (button, 60, -2); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - strcpy (portals.fn, GlobalRadiant().getMapName()); - char* fn = strrchr (portals.fn, '.'); - if (fn != NULL) - { - strcpy(fn, ".prt"); - } - - StringOutputStream value(256); - value << portals.fn; - gtk_entry_set_text (GTK_ENTRY (entry), value.c_str()); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check2d), portals.show_2d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check3d), portals.show_3d); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - if (ret == IDOK) - { - portals.Purge(); - - portals.show_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (check3d)) ? true : false; - portals.show_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (check2d)) ? true : false; - } - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); - - return ret; +int DoLoadPortalFileDialog(){ + GtkWidget *dlg, *vbox, *hbox, *button, *entry, *check2d, *check3d; + int loop = 1, ret = IDCANCEL; + + dlg = gtk_window_new( GTK_WINDOW_TOPLEVEL ); + gtk_window_set_title( GTK_WINDOW( dlg ), "Load .prt" ); + gtk_signal_connect( GTK_OBJECT( dlg ), "delete_event", + GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); + gtk_signal_connect( GTK_OBJECT( dlg ), "destroy", + GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); + g_object_set_data( G_OBJECT( dlg ), "loop", &loop ); + g_object_set_data( G_OBJECT( dlg ), "ret", &ret ); + + vbox = gtk_vbox_new( FALSE, 5 ); + gtk_widget_show( vbox ); + gtk_container_add( GTK_CONTAINER( dlg ), vbox ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); + + entry = gtk_entry_new(); + gtk_widget_show( entry ); + gtk_entry_set_editable( GTK_ENTRY( entry ), FALSE ); + gtk_box_pack_start( GTK_BOX( vbox ), entry, FALSE, FALSE, 0 ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + + check3d = gtk_check_button_new_with_label( "Show 3D" ); + gtk_widget_show( check3d ); + gtk_box_pack_start( GTK_BOX( hbox ), check3d, FALSE, FALSE, 0 ); + + check2d = gtk_check_button_new_with_label( "Show 2D" ); + gtk_widget_show( check2d ); + gtk_box_pack_start( GTK_BOX( hbox ), check2d, FALSE, FALSE, 0 ); + + button = gtk_button_new_with_label( "Change" ); + gtk_widget_show( button ); + gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", GTK_SIGNAL_FUNC( change_clicked ), entry ); + gtk_widget_set_usize( button, 60, -2 ); + + hbox = gtk_hbox_new( FALSE, 5 ); + gtk_widget_show( hbox ); + gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); + + button = gtk_button_new_with_label( "Cancel" ); + gtk_widget_show( button ); + gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDCANCEL ) ); + gtk_widget_set_usize( button, 60, -2 ); + + button = gtk_button_new_with_label( "OK" ); + gtk_widget_show( button ); + gtk_box_pack_end( GTK_BOX( hbox ), button, FALSE, FALSE, 0 ); + gtk_signal_connect( GTK_OBJECT( button ), "clicked", + GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( IDOK ) ); + gtk_widget_set_usize( button, 60, -2 ); + + strcpy( portals.fn, GlobalRadiant().getMapName() ); + char* fn = strrchr( portals.fn, '.' ); + if ( fn != NULL ) { + strcpy( fn, ".prt" ); + } + + StringOutputStream value( 256 ); + value << portals.fn; + gtk_entry_set_text( GTK_ENTRY( entry ), value.c_str() ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( check2d ), portals.show_2d ); + gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( check3d ), portals.show_3d ); + + gtk_grab_add( dlg ); + gtk_widget_show( dlg ); + + while ( loop ) + gtk_main_iteration(); + + if ( ret == IDOK ) { + portals.Purge(); + + portals.show_3d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( check3d ) ) ? true : false; + portals.show_2d = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( check2d ) ) ? true : false; + } + + gtk_grab_remove( dlg ); + gtk_widget_destroy( dlg ); + + return ret; } diff --git a/contrib/prtview/LoadPortalFileDialog.h b/contrib/prtview/LoadPortalFileDialog.h index a4a40c6c..62dfc3d4 100644 --- a/contrib/prtview/LoadPortalFileDialog.h +++ b/contrib/prtview/LoadPortalFileDialog.h @@ -1,26 +1,25 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_LOADPORTALFILEDIALOG_H) +#if !defined( INCLUDED_LOADPORTALFILEDIALOG_H ) #define INCLUDED_LOADPORTALFILEDIALOG_H -int DoLoadPortalFileDialog (); +int DoLoadPortalFileDialog(); #endif - diff --git a/contrib/prtview/portals.cpp b/contrib/prtview/portals.cpp index d3bef1b6..a896fcd4 100644 --- a/contrib/prtview/portals.cpp +++ b/contrib/prtview/portals.cpp @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "portals.h" #include @@ -35,70 +35,68 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA CPortals portals; CPortalsRender render; -int compare( const void *arg1, const void *arg2 ) -{ +int compare( const void *arg1, const void *arg2 ){ - if(portals.portal[*((int *)arg1)].dist > portals.portal[*((int *)arg2)].dist) + if ( portals.portal[*( (int *)arg1 )].dist > portals.portal[*( (int *)arg2 )].dist ) { return -1; - else if(portals.portal[*((int *)arg1)].dist < portals.portal[*((int *)arg2)].dist) + } + else if ( portals.portal[*( (int *)arg1 )].dist < portals.portal[*( (int *)arg2 )].dist ) { return 1; + } return 0; } -CBspPortal::CBspPortal() -{ - memset(this, 0, sizeof(CBspPortal)); +CBspPortal::CBspPortal(){ + memset( this, 0, sizeof( CBspPortal ) ); } -CBspPortal::~CBspPortal() -{ +CBspPortal::~CBspPortal(){ delete[] point; delete[] inner_point; } -bool CBspPortal::Build(char *def) -{ +bool CBspPortal::Build( char *def ){ char *c = def; unsigned int n; int dummy1, dummy2; int res_cnt, i; - if(portals.hint_flags) - { - res_cnt = sscanf(def, "%u %d %d %d", &point_count, &dummy1, &dummy2, (int *)&hint); + if ( portals.hint_flags ) { + res_cnt = sscanf( def, "%u %d %d %d", &point_count, &dummy1, &dummy2, (int *)&hint ); } else { - sscanf(def, "%u", &point_count); + sscanf( def, "%u", &point_count ); hint = false; } - if(point_count < 3 || (portals.hint_flags && res_cnt < 4)) + if ( point_count < 3 || ( portals.hint_flags && res_cnt < 4 ) ) { return false; + } point = new CBspPoint[point_count]; inner_point = new CBspPoint[point_count]; - for(n = 0; n < point_count; n++) + for ( n = 0; n < point_count; n++ ) { - for(; *c != 0 && *c != '('; c++); + for (; *c != 0 && *c != '('; c++ ) ; - if(*c == 0) + if ( *c == 0 ) { return false; + } c++; - sscanf(c, "%f %f %f", point[n].p, point[n].p+1, point[n].p+2); + sscanf( c, "%f %f %f", point[n].p, point[n].p + 1, point[n].p + 2 ); center.p[0] += point[n].p[0]; center.p[1] += point[n].p[1]; center.p[2] += point[n].p[2]; - if(n == 0) - { - for(i = 0; i < 3; i++) + if ( n == 0 ) { + for ( i = 0; i < 3; i++ ) { min[i] = point[n].p[i]; max[i] = point[n].p[i]; @@ -106,12 +104,14 @@ bool CBspPortal::Build(char *def) } else { - for(i = 0; i < 3; i++) + for ( i = 0; i < 3; i++ ) { - if(min[i] > point[n].p[i]) + if ( min[i] > point[n].p[i] ) { min[i] = point[n].p[i]; - if(max[i] < point[n].p[i]) + } + if ( max[i] < point[n].p[i] ) { max[i] = point[n].p[i]; + } } } } @@ -120,33 +120,30 @@ bool CBspPortal::Build(char *def) center.p[1] /= (float)point_count; center.p[2] /= (float)point_count; - for(n = 0; n < point_count; n++) + for ( n = 0; n < point_count; n++ ) { - inner_point[n].p[0] = (0.01f * center.p[0]) + (0.99f * point[n].p[0]); - inner_point[n].p[1] = (0.01f * center.p[1]) + (0.99f * point[n].p[1]); - inner_point[n].p[2] = (0.01f * center.p[2]) + (0.99f * point[n].p[2]); + inner_point[n].p[0] = ( 0.01f * center.p[0] ) + ( 0.99f * point[n].p[0] ); + inner_point[n].p[1] = ( 0.01f * center.p[1] ) + ( 0.99f * point[n].p[1] ); + inner_point[n].p[2] = ( 0.01f * center.p[2] ) + ( 0.99f * point[n].p[2] ); } - fp_color_random[0] = (float)(rand() & 0xff) / 255.0f; - fp_color_random[1] = (float)(rand() & 0xff) / 255.0f; - fp_color_random[2] = (float)(rand() & 0xff) / 255.0f; + fp_color_random[0] = (float)( rand() & 0xff ) / 255.0f; + fp_color_random[1] = (float)( rand() & 0xff ) / 255.0f; + fp_color_random[2] = (float)( rand() & 0xff ) / 255.0f; fp_color_random[3] = 1.0f; return true; } -CPortals::CPortals() -{ - memset(this, 0, sizeof(CPortals)); +CPortals::CPortals(){ + memset( this, 0, sizeof( CPortals ) ); } -CPortals::~CPortals() -{ +CPortals::~CPortals(){ Purge(); } -void CPortals::Purge() -{ +void CPortals::Purge(){ delete[] portal; delete[] portal_sort; portal = NULL; @@ -154,77 +151,71 @@ void CPortals::Purge() portal_count = 0; /* - delete[] node; - node = NULL; - node_count = 0; - */ + delete[] node; + node = NULL; + node_count = 0; + */ } -void CPortals::Load() -{ - char buf[LINE_BUF+1]; +void CPortals::Load(){ + char buf[LINE_BUF + 1]; + + memset( buf, 0, LINE_BUF + 1 ); - memset(buf, 0, LINE_BUF + 1); - Purge(); globalOutputStream() << MSG_PREFIX "Loading portal file " << fn << ".\n"; FILE *in; - in = fopen(fn, "rt"); + in = fopen( fn, "rt" ); - if(in == NULL) - { + if ( in == NULL ) { globalOutputStream() << " ERROR - could not open file.\n"; return; } - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); globalOutputStream() << " ERROR - File ended prematurely.\n"; return; } - if(strncmp("PRT1", buf, 4) != 0) - { - fclose(in); + if ( strncmp( "PRT1", buf, 4 ) != 0 ) { + fclose( in ); globalOutputStream() << " ERROR - File header indicates wrong file type (should be \"PRT1\").\n"; return; } - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); globalOutputStream() << " ERROR - File ended prematurely.\n"; return; } - sscanf(buf, "%u", &node_count); + sscanf( buf, "%u", &node_count ); /* - if(node_count > 0xFFFF) - { - fclose(in); + if(node_count > 0xFFFF) + { + fclose(in); - node_count = 0; + node_count = 0; - globalOutputStream() << " ERROR - Extreme number of nodes, aborting.\n"; + globalOutputStream() << " ERROR - Extreme number of nodes, aborting.\n"; - return; - } - */ + return; + } + */ - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); node_count = 0; @@ -233,11 +224,10 @@ void CPortals::Load() return; } - sscanf(buf, "%u", &portal_count); + sscanf( buf, "%u", &portal_count ); - if(portal_count > 0xFFFF) - { - fclose(in); + if ( portal_count > 0xFFFF ) { + fclose( in ); portal_count = 0; node_count = 0; @@ -247,9 +237,8 @@ void CPortals::Load() return; } - if(portal_count == 0) - { - fclose(in); + if ( portal_count == 0 ) { + fclose( in ); portal_count = 0; node_count = 0; @@ -269,11 +258,10 @@ void CPortals::Load() hint_flags = false; - for(n = 0; n < portal_count; ) + for ( n = 0; n < portal_count; ) { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); + if ( !fgets( buf, LINE_BUF, in ) ) { + fclose( in ); Purge(); @@ -282,10 +270,8 @@ void CPortals::Load() return; } - if(!portal[n].Build(buf)) - { - if(first && sscanf(buf, "%d %d", &test_vals_1, &test_vals_2) == 1) // skip additional counts of later data, not needed - { + if ( !portal[n].Build( buf ) ) { + if ( first && sscanf( buf, "%d %d", &test_vals_1, &test_vals_2 ) == 1 ) { // skip additional counts of later data, not needed // We can count on hint flags being in the file hint_flags = true; continue; @@ -293,7 +279,7 @@ void CPortals::Load() first = false; - fclose(in); + fclose( in ); Purge(); @@ -305,7 +291,7 @@ void CPortals::Load() n++; } - fclose(in); + fclose( in ); globalOutputStream() << " " << node_count << " portals read in.\n"; } @@ -319,32 +305,29 @@ Shader* g_shader_solid = 0; Shader* g_shader_solid_outline = 0; Shader* g_shader_wireframe = 0; -void Portals_constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = portals.width_2d * 0.5f; - state.m_colour[0] = portals.fp_color_2d[0]; - state.m_colour[1] = portals.fp_color_2d[1]; - state.m_colour[2] = portals.fp_color_2d[2]; - state.m_colour[3] = portals.fp_color_2d[3]; - if(portals.aa_2d) - { - state.m_state |= RENDER_BLEND|RENDER_LINESMOOTH; - } - GlobalOpenGLStateLibrary().insert(g_state_wireframe, state); - - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_COLOURCHANGE|RENDER_SMOOTH; - - if(portals.aa_3d) - { +void Portals_constructShaders(){ + OpenGLState state; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortOverlayFirst; + state.m_linewidth = portals.width_2d * 0.5f; + state.m_colour[0] = portals.fp_color_2d[0]; + state.m_colour[1] = portals.fp_color_2d[1]; + state.m_colour[2] = portals.fp_color_2d[2]; + state.m_colour[3] = portals.fp_color_2d[3]; + if ( portals.aa_2d ) { + state.m_state |= RENDER_BLEND | RENDER_LINESMOOTH; + } + GlobalOpenGLStateLibrary().insert( g_state_wireframe, state ); + + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_FILL | RENDER_BLEND | RENDER_COLOURWRITE | RENDER_COLOURCHANGE | RENDER_SMOOTH; + + if ( portals.aa_3d ) { state.m_state |= RENDER_POLYGONSMOOTH; - } + } - switch(portals.zbuffer) + switch ( portals.zbuffer ) { case 1: state.m_state |= RENDER_DEPTHTEST; @@ -356,8 +339,7 @@ void Portals_constructShaders() state.m_state |= RENDER_DEPTHWRITE; } - if(portals.fog) - { + if ( portals.fog ) { state.m_state |= RENDER_FOG; state.m_fog.mode = GL_EXP; @@ -371,23 +353,22 @@ void Portals_constructShaders() state.m_fog.colour[3] = portals.fp_color_fog[3]; } - GlobalOpenGLStateLibrary().insert(g_state_solid, state); + GlobalOpenGLStateLibrary().insert( g_state_solid, state ); - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortOverlayFirst; + GlobalOpenGLStateLibrary().getDefaultState( state ); + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortOverlayFirst; state.m_linewidth = portals.width_3d * 0.5f; - state.m_colour[0] = portals.fp_color_3d[0]; - state.m_colour[1] = portals.fp_color_3d[1]; - state.m_colour[2] = portals.fp_color_3d[2]; - state.m_colour[3] = portals.fp_color_3d[3]; + state.m_colour[0] = portals.fp_color_3d[0]; + state.m_colour[1] = portals.fp_color_3d[1]; + state.m_colour[2] = portals.fp_color_3d[2]; + state.m_colour[3] = portals.fp_color_3d[3]; - if(portals.aa_3d) - { + if ( portals.aa_3d ) { state.m_state |= RENDER_LINESMOOTH; - } + } - switch(portals.zbuffer) + switch ( portals.zbuffer ) { case 1: state.m_state |= RENDER_DEPTHTEST; @@ -399,8 +380,7 @@ void Portals_constructShaders() state.m_state |= RENDER_DEPTHWRITE; } - if(portals.fog) - { + if ( portals.fog ) { state.m_state |= RENDER_FOG; state.m_fog.mode = GL_EXP; @@ -414,128 +394,119 @@ void Portals_constructShaders() state.m_fog.colour[3] = portals.fp_color_fog[3]; } - GlobalOpenGLStateLibrary().insert(g_state_solid_outline, state); + GlobalOpenGLStateLibrary().insert( g_state_solid_outline, state ); - g_shader_solid = GlobalShaderCache().capture(g_state_solid); - g_shader_solid_outline = GlobalShaderCache().capture(g_state_solid_outline); - g_shader_wireframe = GlobalShaderCache().capture(g_state_wireframe); + g_shader_solid = GlobalShaderCache().capture( g_state_solid ); + g_shader_solid_outline = GlobalShaderCache().capture( g_state_solid_outline ); + g_shader_wireframe = GlobalShaderCache().capture( g_state_wireframe ); } -void Portals_destroyShaders() -{ - GlobalShaderCache().release(g_state_solid); - GlobalShaderCache().release(g_state_solid_outline); - GlobalShaderCache().release(g_state_wireframe); - GlobalOpenGLStateLibrary().erase(g_state_solid); - GlobalOpenGLStateLibrary().erase(g_state_solid_outline); - GlobalOpenGLStateLibrary().erase(g_state_wireframe); +void Portals_destroyShaders(){ + GlobalShaderCache().release( g_state_solid ); + GlobalShaderCache().release( g_state_solid_outline ); + GlobalShaderCache().release( g_state_wireframe ); + GlobalOpenGLStateLibrary().erase( g_state_solid ); + GlobalOpenGLStateLibrary().erase( g_state_solid_outline ); + GlobalOpenGLStateLibrary().erase( g_state_wireframe ); } -void Portals_shadersChanged() -{ - Portals_destroyShaders(); - portals.FixColors(); - Portals_constructShaders(); +void Portals_shadersChanged(){ + Portals_destroyShaders(); + portals.FixColors(); + Portals_constructShaders(); } -void CPortals::FixColors() -{ - fp_color_2d[0] = (float)GetRValue(color_2d) / 255.0f; - fp_color_2d[1] = (float)GetGValue(color_2d) / 255.0f; - fp_color_2d[2] = (float)GetBValue(color_2d) / 255.0f; +void CPortals::FixColors(){ + fp_color_2d[0] = (float)GetRValue( color_2d ) / 255.0f; + fp_color_2d[1] = (float)GetGValue( color_2d ) / 255.0f; + fp_color_2d[2] = (float)GetBValue( color_2d ) / 255.0f; fp_color_2d[3] = 1.0f; - fp_color_3d[0] = (float)GetRValue(color_3d) / 255.0f; - fp_color_3d[1] = (float)GetGValue(color_3d) / 255.0f; - fp_color_3d[2] = (float)GetBValue(color_3d) / 255.0f; + fp_color_3d[0] = (float)GetRValue( color_3d ) / 255.0f; + fp_color_3d[1] = (float)GetGValue( color_3d ) / 255.0f; + fp_color_3d[2] = (float)GetBValue( color_3d ) / 255.0f; fp_color_3d[3] = 1.0f; - fp_color_fog[0] = 0.0f;//(float)GetRValue(color_fog) / 255.0f; - fp_color_fog[1] = 0.0f;//(float)GetGValue(color_fog) / 255.0f; - fp_color_fog[2] = 0.0f;//(float)GetBValue(color_fog) / 255.0f; + fp_color_fog[0] = 0.0f; //(float)GetRValue(color_fog) / 255.0f; + fp_color_fog[1] = 0.0f; //(float)GetGValue(color_fog) / 255.0f; + fp_color_fog[2] = 0.0f; //(float)GetBValue(color_fog) / 255.0f; fp_color_fog[3] = 1.0f; } -void CPortalsRender::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - if(!portals.show_2d || portals.portal_count < 1) +void CPortalsRender::renderWireframe( Renderer& renderer, const VolumeTest& volume ) const { + if ( !portals.show_2d || portals.portal_count < 1 ) { return; + } - renderer.SetState(g_shader_wireframe, Renderer::eWireframeOnly); + renderer.SetState( g_shader_wireframe, Renderer::eWireframeOnly ); - renderer.addRenderable(m_drawWireframe, g_matrix4_identity); + renderer.addRenderable( m_drawWireframe, g_matrix4_identity ); } -void CPortalsDrawWireframe::render(RenderStateFlags state) const -{ +void CPortalsDrawWireframe::render( RenderStateFlags state ) const { unsigned int n, p; - for(n = 0; n < portals.portal_count; n++) + for ( n = 0; n < portals.portal_count; n++ ) { - glBegin(GL_LINE_LOOP); + glBegin( GL_LINE_LOOP ); - for(p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].point[p].p); + for ( p = 0; p < portals.portal[n].point_count; p++ ) + glVertex3fv( portals.portal[n].point[p].p ); glEnd(); } } -CubicClipVolume calculateCubicClipVolume(const Matrix4& viewproj) -{ - CubicClipVolume clip; - clip.cam = vector4_projected( - matrix4_transformed_vector4( - matrix4_full_inverse(viewproj), - Vector4(0, 0, -1, 1) - ) - ); - clip.min[0] = clip.cam[0] + (portals.clip_range * 64.0f); - clip.min[1] = clip.cam[1] + (portals.clip_range * 64.0f); - clip.min[2] = clip.cam[2] + (portals.clip_range * 64.0f); - clip.max[0] = clip.cam[0] - (portals.clip_range * 64.0f); - clip.max[1] = clip.cam[1] - (portals.clip_range * 64.0f); - clip.max[2] = clip.cam[2] - (portals.clip_range * 64.0f); - return clip; +CubicClipVolume calculateCubicClipVolume( const Matrix4& viewproj ){ + CubicClipVolume clip; + clip.cam = vector4_projected( + matrix4_transformed_vector4( + matrix4_full_inverse( viewproj ), + Vector4( 0, 0, -1, 1 ) + ) + ); + clip.min[0] = clip.cam[0] + ( portals.clip_range * 64.0f ); + clip.min[1] = clip.cam[1] + ( portals.clip_range * 64.0f ); + clip.min[2] = clip.cam[2] + ( portals.clip_range * 64.0f ); + clip.max[0] = clip.cam[0] - ( portals.clip_range * 64.0f ); + clip.max[1] = clip.cam[1] - ( portals.clip_range * 64.0f ); + clip.max[2] = clip.cam[2] - ( portals.clip_range * 64.0f ); + return clip; } -void CPortalsRender::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!portals.show_3d || portals.portal_count < 1) +void CPortalsRender::renderSolid( Renderer& renderer, const VolumeTest& volume ) const { + if ( !portals.show_3d || portals.portal_count < 1 ) { return; + } - CubicClipVolume clip = calculateCubicClipVolume(matrix4_multiplied_by_matrix4(volume.GetProjection(), volume.GetModelview())); + CubicClipVolume clip = calculateCubicClipVolume( matrix4_multiplied_by_matrix4( volume.GetProjection(), volume.GetModelview() ) ); - if(portals.polygons) - { - renderer.SetState(g_shader_solid, Renderer::eWireframeOnly); - renderer.SetState(g_shader_solid, Renderer::eFullMaterials); + if ( portals.polygons ) { + renderer.SetState( g_shader_solid, Renderer::eWireframeOnly ); + renderer.SetState( g_shader_solid, Renderer::eFullMaterials ); - m_drawSolid.clip = clip; - renderer.addRenderable(m_drawSolid, g_matrix4_identity); - } + m_drawSolid.clip = clip; + renderer.addRenderable( m_drawSolid, g_matrix4_identity ); + } - if(portals.lines) - { - renderer.SetState(g_shader_solid_outline, Renderer::eWireframeOnly); - renderer.SetState(g_shader_solid_outline, Renderer::eFullMaterials); + if ( portals.lines ) { + renderer.SetState( g_shader_solid_outline, Renderer::eWireframeOnly ); + renderer.SetState( g_shader_solid_outline, Renderer::eFullMaterials ); - m_drawSolidOutline.clip = clip; - renderer.addRenderable(m_drawSolidOutline, g_matrix4_identity); - } + m_drawSolidOutline.clip = clip; + renderer.addRenderable( m_drawSolidOutline, g_matrix4_identity ); + } } -void CPortalsDrawSolid::render(RenderStateFlags state) const -{ - float trans = (100.0f - portals.trans_3d) / 100.0f; +void CPortalsDrawSolid::render( RenderStateFlags state ) const { + float trans = ( 100.0f - portals.trans_3d ) / 100.0f; unsigned int n, p; - if(portals.zbuffer != 0) - { + if ( portals.zbuffer != 0 ) { float d; - for(n = 0; n < portals.portal_count; n++) + for ( n = 0; n < portals.portal_count; n++ ) { d = (float)clip.cam[0] - portals.portal[n].center.p[0]; portals.portal[n].dist = d * d; @@ -549,103 +520,120 @@ void CPortalsDrawSolid::render(RenderStateFlags state) const portals.portal_sort[n] = n; } - qsort(portals.portal_sort, portals.portal_count, 4, compare); - - for(n = 0; n < portals.portal_count; n++) + qsort( portals.portal_sort, portals.portal_count, 4, compare ); + + for ( n = 0; n < portals.portal_count; n++ ) { - if(portals.polygons == 2 && !portals.portal[portals.portal_sort[n]].hint) + if ( portals.polygons == 2 && !portals.portal[portals.portal_sort[n]].hint ) { continue; + } - if(portals.clip) - { - if(clip.min[0] < portals.portal[portals.portal_sort[n]].min[0]) + if ( portals.clip ) { + if ( clip.min[0] < portals.portal[portals.portal_sort[n]].min[0] ) { continue; - else if(clip.min[1] < portals.portal[portals.portal_sort[n]].min[1]) + } + else if ( clip.min[1] < portals.portal[portals.portal_sort[n]].min[1] ) { continue; - else if(clip.min[2] < portals.portal[portals.portal_sort[n]].min[2]) + } + else if ( clip.min[2] < portals.portal[portals.portal_sort[n]].min[2] ) { continue; - else if(clip.max[0] > portals.portal[portals.portal_sort[n]].max[0]) + } + else if ( clip.max[0] > portals.portal[portals.portal_sort[n]].max[0] ) { continue; - else if(clip.max[1] > portals.portal[portals.portal_sort[n]].max[1]) + } + else if ( clip.max[1] > portals.portal[portals.portal_sort[n]].max[1] ) { continue; - else if(clip.max[2] > portals.portal[portals.portal_sort[n]].max[2]) + } + else if ( clip.max[2] > portals.portal[portals.portal_sort[n]].max[2] ) { continue; + } } - glColor4f(portals.portal[portals.portal_sort[n]].fp_color_random[0], portals.portal[portals.portal_sort[n]].fp_color_random[1], - portals.portal[portals.portal_sort[n]].fp_color_random[2], trans); + glColor4f( portals.portal[portals.portal_sort[n]].fp_color_random[0], portals.portal[portals.portal_sort[n]].fp_color_random[1], + portals.portal[portals.portal_sort[n]].fp_color_random[2], trans ); - glBegin(GL_POLYGON); + glBegin( GL_POLYGON ); - for(p = 0; p < portals.portal[portals.portal_sort[n]].point_count; p++) - glVertex3fv(portals.portal[portals.portal_sort[n]].point[p].p); + for ( p = 0; p < portals.portal[portals.portal_sort[n]].point_count; p++ ) + glVertex3fv( portals.portal[portals.portal_sort[n]].point[p].p ); glEnd(); } } else { - for(n = 0; n < portals.portal_count; n++) + for ( n = 0; n < portals.portal_count; n++ ) { - if(portals.polygons == 2 && !portals.portal[n].hint) + if ( portals.polygons == 2 && !portals.portal[n].hint ) { continue; + } - if(portals.clip) - { - if(clip.min[0] < portals.portal[n].min[0]) + if ( portals.clip ) { + if ( clip.min[0] < portals.portal[n].min[0] ) { continue; - else if(clip.min[1] < portals.portal[n].min[1]) + } + else if ( clip.min[1] < portals.portal[n].min[1] ) { continue; - else if(clip.min[2] < portals.portal[n].min[2]) + } + else if ( clip.min[2] < portals.portal[n].min[2] ) { continue; - else if(clip.max[0] > portals.portal[n].max[0]) + } + else if ( clip.max[0] > portals.portal[n].max[0] ) { continue; - else if(clip.max[1] > portals.portal[n].max[1]) + } + else if ( clip.max[1] > portals.portal[n].max[1] ) { continue; - else if(clip.max[2] > portals.portal[n].max[2]) + } + else if ( clip.max[2] > portals.portal[n].max[2] ) { continue; + } } - glColor4f(portals.portal[n].fp_color_random[0], portals.portal[n].fp_color_random[1], - portals.portal[n].fp_color_random[2], trans); + glColor4f( portals.portal[n].fp_color_random[0], portals.portal[n].fp_color_random[1], + portals.portal[n].fp_color_random[2], trans ); - glBegin(GL_POLYGON); + glBegin( GL_POLYGON ); - for(p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].point[p].p); + for ( p = 0; p < portals.portal[n].point_count; p++ ) + glVertex3fv( portals.portal[n].point[p].p ); glEnd(); } } } -void CPortalsDrawSolidOutline::render(RenderStateFlags state) const -{ - for(int n = 0; n < portals.portal_count; n++) +void CPortalsDrawSolidOutline::render( RenderStateFlags state ) const { + for ( int n = 0; n < portals.portal_count; n++ ) { - if(portals.lines == 2 && !portals.portal[n].hint) + if ( portals.lines == 2 && !portals.portal[n].hint ) { continue; + } - if(portals.clip) - { - if(clip.min[0] < portals.portal[n].min[0]) + if ( portals.clip ) { + if ( clip.min[0] < portals.portal[n].min[0] ) { continue; - else if(clip.min[1] < portals.portal[n].min[1]) + } + else if ( clip.min[1] < portals.portal[n].min[1] ) { continue; - else if(clip.min[2] < portals.portal[n].min[2]) + } + else if ( clip.min[2] < portals.portal[n].min[2] ) { continue; - else if(clip.max[0] > portals.portal[n].max[0]) + } + else if ( clip.max[0] > portals.portal[n].max[0] ) { continue; - else if(clip.max[1] > portals.portal[n].max[1]) + } + else if ( clip.max[1] > portals.portal[n].max[1] ) { continue; - else if(clip.max[2] > portals.portal[n].max[2]) + } + else if ( clip.max[2] > portals.portal[n].max[2] ) { continue; + } } - glBegin(GL_LINE_LOOP); + glBegin( GL_LINE_LOOP ); - for(int p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].inner_point[p].p); + for ( int p = 0; p < portals.portal[n].point_count; p++ ) + glVertex3fv( portals.portal[n].inner_point[p].p ); glEnd(); } diff --git a/contrib/prtview/portals.h b/contrib/prtview/portals.h index c6bd678d..1fd2f037 100644 --- a/contrib/prtview/portals.h +++ b/contrib/prtview/portals.h @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef _PORTALS_H_ #define _PORTALS_H_ @@ -28,28 +28,28 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class CBspPoint { public: - float p[3]; +float p[3]; }; class CBspPortal { public: - CBspPortal(); - ~CBspPortal(); +CBspPortal(); +~CBspPortal(); protected: public: - CBspPoint center; - unsigned point_count; - CBspPoint *point; - CBspPoint *inner_point; - float fp_color_random[4]; - float min[3]; - float max[3]; - float dist; - bool hint; - - bool Build(char *def); +CBspPoint center; +unsigned point_count; +CBspPoint *point; +CBspPoint *inner_point; +float fp_color_random[4]; +float min[3]; +float max[3]; +float dist; +bool hint; + +bool Build( char *def ); }; #ifdef PATH_MAX @@ -58,95 +58,95 @@ public: #define PRTVIEW_PATH_MAX 260 #endif typedef guint32 PackedColour; -#define RGB(r, g, b) ((guint32)(((guint8) (r) | ((guint16) (g) << 8))|(((guint32) (guint8) (b)) << 16))) -#define GetRValue(rgb) ((guint8)(rgb)) -#define GetGValue(rgb) ((guint8)(((guint16)(rgb)) >> 8)) -#define GetBValue(rgb) ((guint8)((rgb)>>16)) +#define RGB( r, g, b ) ( (guint32)( ( (guint8) ( r ) | ( (guint16) ( g ) << 8 ) ) | ( ( (guint32) (guint8) ( b ) ) << 16 ) ) ) +#define GetRValue( rgb ) ( (guint8)( rgb ) ) +#define GetGValue( rgb ) ( (guint8)( ( (guint16)( rgb ) ) >> 8 ) ) +#define GetBValue( rgb ) ( (guint8)( ( rgb ) >> 16 ) ) class CPortals { public: - CPortals(); - ~CPortals(); +CPortals(); +~CPortals(); protected: public: - void Load(); // use filename in fn - void Purge(); - - void FixColors(); - - char fn[PRTVIEW_PATH_MAX]; - - int zbuffer; - int polygons; - int lines; - bool show_3d; - bool aa_3d; - bool fog; - PackedColour color_3d; - float width_3d; // in 8'ths - float fp_color_3d[4]; - PackedColour color_fog; - float fp_color_fog[4]; - float trans_3d; - float clip_range; - bool clip; - - bool show_2d; - bool aa_2d; - PackedColour color_2d; - float width_2d; // in 8'ths - float fp_color_2d[4]; - - CBspPortal *portal; - int *portal_sort; - bool hint_flags; +void Load(); // use filename in fn +void Purge(); + +void FixColors(); + +char fn[PRTVIEW_PATH_MAX]; + +int zbuffer; +int polygons; +int lines; +bool show_3d; +bool aa_3d; +bool fog; +PackedColour color_3d; +float width_3d; // in 8'ths +float fp_color_3d[4]; +PackedColour color_fog; +float fp_color_fog[4]; +float trans_3d; +float clip_range; +bool clip; + +bool show_2d; +bool aa_2d; +PackedColour color_2d; +float width_2d; // in 8'ths +float fp_color_2d[4]; + +CBspPortal *portal; +int *portal_sort; +bool hint_flags; // CBspNode *node; - unsigned int node_count; - unsigned int portal_count; +unsigned int node_count; +unsigned int portal_count; }; class CubicClipVolume { public: - Vector3 cam, min, max; +Vector3 cam, min, max; }; class CPortalsDrawSolid : public OpenGLRenderable { public: - mutable CubicClipVolume clip; - void render(RenderStateFlags state) const; +mutable CubicClipVolume clip; +void render( RenderStateFlags state ) const; }; class CPortalsDrawSolidOutline : public OpenGLRenderable { public: - mutable CubicClipVolume clip; - void render(RenderStateFlags state) const; +mutable CubicClipVolume clip; +void render( RenderStateFlags state ) const; }; class CPortalsDrawWireframe : public OpenGLRenderable { public: - void render(RenderStateFlags state) const; +void render( RenderStateFlags state ) const; }; class CPortalsRender : public Renderable { public: - CPortalsDrawSolid m_drawSolid; - CPortalsDrawSolidOutline m_drawSolidOutline; - CPortalsDrawWireframe m_drawWireframe; +CPortalsDrawSolid m_drawSolid; +CPortalsDrawSolidOutline m_drawSolidOutline; +CPortalsDrawWireframe m_drawWireframe; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; +void renderSolid( Renderer& renderer, const VolumeTest& volume ) const; +void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const; }; extern CPortals portals; diff --git a/contrib/prtview/prtview.cpp b/contrib/prtview/prtview.cpp index c5ed86c9..301ac9ea 100644 --- a/contrib/prtview/prtview.cpp +++ b/contrib/prtview/prtview.cpp @@ -1,21 +1,21 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "prtview.h" @@ -67,113 +67,122 @@ CopiedString INIfn; #define CLIP "Clip" -void PrtView_construct() -{ - StringOutputStream tmp(64); - tmp << GlobalRadiant().getSettingsPath() << "prtview.ini"; - INIfn = tmp.c_str(); - - portals.show_2d = INIGetInt(RENDER_2D, FALSE) ? true : false; - portals.aa_2d = INIGetInt(AA_2D, FALSE) ? true : false; - portals.width_2d = (float)INIGetInt(WIDTH_2D, 10); - portals.color_2d = (PackedColour)INIGetInt(COLOR_2D, RGB(0, 0, 255)) & 0xFFFFFF; - - if (portals.width_2d > 40.0f) - portals.width_2d = 40.0f; - else if (portals.width_2d < 2.0f) - portals.width_2d = 2.0f; - - portals.show_3d = INIGetInt(RENDER_3D, TRUE) ? true : false; - - portals.zbuffer = INIGetInt(ZBUFFER, 1); - portals.fog = INIGetInt(FOG, FALSE) ? true : false; - portals.polygons = INIGetInt(POLYGON, TRUE); - portals.lines = INIGetInt(LINE, TRUE); - portals.aa_3d = INIGetInt(AA_3D, FALSE) ? true : false; - portals.width_3d = (float)INIGetInt(WIDTH_3D, 4); - portals.color_3d = (PackedColour)INIGetInt(COLOR_3D, RGB(255, 255, 0)) & 0xFFFFFF; - portals.color_fog = (PackedColour)INIGetInt(COLOR_FOG, RGB(127, 127, 127)) & 0xFFFFFF; - portals.trans_3d = (float)INIGetInt(TRANS_3D, 50); - portals.clip = INIGetInt(CLIP, FALSE) ? true : false; - portals.clip_range = (float)INIGetInt(CLIP_RANGE, 16); - - if (portals.clip_range < 1) - portals.clip_range = 1; - else if (portals.clip_range > 128) - portals.clip_range = 128; - - if (portals.zbuffer < 0) - portals.zbuffer = 0; - else if (portals.zbuffer > 2) - portals.zbuffer = 0; - - if (portals.width_3d > 40.0f) - portals.width_3d = 40.0f; - else if (portals.width_3d < 2.0f) - portals.width_3d = 2.0f; - - if (portals.trans_3d > 100.0f) - portals.trans_3d = 100.0f; - else if (portals.trans_3d < 0.0f) - portals.trans_3d = 0.0f; - - SaveConfig(); - - portals.FixColors(); - - Portals_constructShaders(); - GlobalShaderCache().attachRenderable(render); +void PrtView_construct(){ + StringOutputStream tmp( 64 ); + tmp << GlobalRadiant().getSettingsPath() << "prtview.ini"; + INIfn = tmp.c_str(); + + portals.show_2d = INIGetInt( RENDER_2D, FALSE ) ? true : false; + portals.aa_2d = INIGetInt( AA_2D, FALSE ) ? true : false; + portals.width_2d = (float)INIGetInt( WIDTH_2D, 10 ); + portals.color_2d = (PackedColour)INIGetInt( COLOR_2D, RGB( 0, 0, 255 ) ) & 0xFFFFFF; + + if ( portals.width_2d > 40.0f ) { + portals.width_2d = 40.0f; + } + else if ( portals.width_2d < 2.0f ) { + portals.width_2d = 2.0f; + } + + portals.show_3d = INIGetInt( RENDER_3D, TRUE ) ? true : false; + + portals.zbuffer = INIGetInt( ZBUFFER, 1 ); + portals.fog = INIGetInt( FOG, FALSE ) ? true : false; + portals.polygons = INIGetInt( POLYGON, TRUE ); + portals.lines = INIGetInt( LINE, TRUE ); + portals.aa_3d = INIGetInt( AA_3D, FALSE ) ? true : false; + portals.width_3d = (float)INIGetInt( WIDTH_3D, 4 ); + portals.color_3d = (PackedColour)INIGetInt( COLOR_3D, RGB( 255, 255, 0 ) ) & 0xFFFFFF; + portals.color_fog = (PackedColour)INIGetInt( COLOR_FOG, RGB( 127, 127, 127 ) ) & 0xFFFFFF; + portals.trans_3d = (float)INIGetInt( TRANS_3D, 50 ); + portals.clip = INIGetInt( CLIP, FALSE ) ? true : false; + portals.clip_range = (float)INIGetInt( CLIP_RANGE, 16 ); + + if ( portals.clip_range < 1 ) { + portals.clip_range = 1; + } + else if ( portals.clip_range > 128 ) { + portals.clip_range = 128; + } + + if ( portals.zbuffer < 0 ) { + portals.zbuffer = 0; + } + else if ( portals.zbuffer > 2 ) { + portals.zbuffer = 0; + } + + if ( portals.width_3d > 40.0f ) { + portals.width_3d = 40.0f; + } + else if ( portals.width_3d < 2.0f ) { + portals.width_3d = 2.0f; + } + + if ( portals.trans_3d > 100.0f ) { + portals.trans_3d = 100.0f; + } + else if ( portals.trans_3d < 0.0f ) { + portals.trans_3d = 0.0f; + } + + SaveConfig(); + + portals.FixColors(); + + Portals_constructShaders(); + GlobalShaderCache().attachRenderable( render ); } -void PrtView_destroy() -{ - GlobalShaderCache().detachRenderable(render); - Portals_destroyShaders(); +void PrtView_destroy(){ + GlobalShaderCache().detachRenderable( render ); + Portals_destroyShaders(); } -void SaveConfig () -{ - INISetInt(RENDER_2D, portals.show_2d, "Draw in 2D windows"); - INISetInt(WIDTH_2D, (int)portals.width_2d, "Width of lines in 2D windows (in units of 1/2)"); - INISetInt(COLOR_2D, (int)portals.color_2d, "Color of lines in 2D windows"); - INISetInt(AA_2D, portals.aa_2d, "Draw lines in 2D window anti-aliased"); - - INISetInt(ZBUFFER, portals.zbuffer, "ZBuffer level in 3D window"); - INISetInt(FOG, portals.fog, "Use depth cueing in 3D window"); - INISetInt(POLYGON, portals.polygons, "Render using polygons polygons in 3D window"); - INISetInt(LINE, portals.polygons, "Render using lines in 3D window"); - INISetInt(RENDER_3D, portals.show_3d, "Draw in 3D windows"); - INISetInt(WIDTH_3D, (int)portals.width_3d, "Width of lines in 3D window (in units of 1/2)"); - INISetInt(COLOR_3D, (int)portals.color_3d, "Color of lines/polygons in 3D window"); - INISetInt(COLOR_FOG, (int)portals.color_fog, "Color of distant lines/polygons in 3D window"); - INISetInt(AA_3D, portals.aa_3d, "Draw lines in 3D window anti-aliased"); - INISetInt(TRANS_3D, (int)portals.trans_3d, "Transparency in 3d view (0 = solid, 100 = invisible)"); - INISetInt(CLIP, portals.clip, "Cubic clipper active for portal viewer"); - INISetInt(CLIP_RANGE, (int)portals.clip_range, "Portal viewer cubic clip distance (in units of 64)"); +void SaveConfig(){ + INISetInt( RENDER_2D, portals.show_2d, "Draw in 2D windows" ); + INISetInt( WIDTH_2D, (int)portals.width_2d, "Width of lines in 2D windows (in units of 1/2)" ); + INISetInt( COLOR_2D, (int)portals.color_2d, "Color of lines in 2D windows" ); + INISetInt( AA_2D, portals.aa_2d, "Draw lines in 2D window anti-aliased" ); + + INISetInt( ZBUFFER, portals.zbuffer, "ZBuffer level in 3D window" ); + INISetInt( FOG, portals.fog, "Use depth cueing in 3D window" ); + INISetInt( POLYGON, portals.polygons, "Render using polygons polygons in 3D window" ); + INISetInt( LINE, portals.polygons, "Render using lines in 3D window" ); + INISetInt( RENDER_3D, portals.show_3d, "Draw in 3D windows" ); + INISetInt( WIDTH_3D, (int)portals.width_3d, "Width of lines in 3D window (in units of 1/2)" ); + INISetInt( COLOR_3D, (int)portals.color_3d, "Color of lines/polygons in 3D window" ); + INISetInt( COLOR_FOG, (int)portals.color_fog, "Color of distant lines/polygons in 3D window" ); + INISetInt( AA_3D, portals.aa_3d, "Draw lines in 3D window anti-aliased" ); + INISetInt( TRANS_3D, (int)portals.trans_3d, "Transparency in 3d view (0 = solid, 100 = invisible)" ); + INISetInt( CLIP, portals.clip, "Cubic clipper active for portal viewer" ); + INISetInt( CLIP_RANGE, (int)portals.clip_range, "Portal viewer cubic clip distance (in units of 64)" ); } #define CONFIG_SECTION "Configuration" -int INIGetInt(char *key, int def) -{ - char value[1024]; +int INIGetInt( char *key, int def ){ + char value[1024]; - if (read_var (INIfn.c_str(), CONFIG_SECTION, key, value)) - return atoi (value); - else - return def; + if ( read_var( INIfn.c_str(), CONFIG_SECTION, key, value ) ) { + return atoi( value ); + } + else{ + return def; + } } -void INISetInt(char *key, int val, char *comment /* = NULL */) -{ - char s[1000]; +void INISetInt( char *key, int val, char *comment /* = NULL */ ){ + char s[1000]; - if(comment) - sprintf(s, "%d ; %s", val, comment); - else - sprintf(s, "%d", val); - save_var (INIfn.c_str(), CONFIG_SECTION, key, s); + if ( comment ) { + sprintf( s, "%d ; %s", val, comment ); + } + else{ + sprintf( s, "%d", val ); + } + save_var( INIfn.c_str(), CONFIG_SECTION, key, s ); } @@ -193,126 +202,115 @@ static const char *PLUGIN_COMMANDS = -const char* QERPlug_Init (void *hApp, void* pMainWidget) -{ - return "Portal Viewer for Q3Radiant"; +const char* QERPlug_Init( void *hApp, void* pMainWidget ){ + return "Portal Viewer for Q3Radiant"; } -const char* QERPlug_GetName() -{ - return PLUGIN_NAME; +const char* QERPlug_GetName(){ + return PLUGIN_NAME; } -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; +const char* QERPlug_GetCommandList(){ + return PLUGIN_COMMANDS; } -const char* QERPlug_GetCommandTitleList() -{ - return ""; +const char* QERPlug_GetCommandTitleList(){ + return ""; } -void QERPlug_Dispatch(const char* p, float* vMin, float* vMax, bool bSingleBrush) -{ - globalOutputStream() << MSG_PREFIX "Command \"" << p << "\"\n"; - - if (!strcmp(p,Q3R_CMD_ABOUT)) - { - DoAboutDlg (); - } - else if (!strcmp(p,Q3R_CMD_LOAD)) - { - if (DoLoadPortalFileDialog () == IDOK) - { - portals.Load(); - SceneChangeNotify(); - } - else - { - globalOutputStream() << MSG_PREFIX "Portal file load aborted.\n"; - } - } - else if (!strcmp(p,Q3R_CMD_RELEASE)) - { - portals.Purge(); - - SceneChangeNotify(); - - globalOutputStream() << MSG_PREFIX "Portals unloaded.\n"; - } - else if (!strcmp(p,Q3R_CMD_SHOW_2D)) - { - portals.show_2d = !portals.show_2d; - - SceneChangeNotify(); - SaveConfig(); - - if(portals.show_2d) - globalOutputStream() << MSG_PREFIX "Portals will be rendered in 2D view.\n"; - else - globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 2D view.\n"; - } - else if (!strcmp(p,Q3R_CMD_SHOW_3D)) - { - portals.show_3d = !portals.show_3d; - SaveConfig(); - - SceneChangeNotify(); - - if (portals.show_3d) - globalOutputStream() << MSG_PREFIX "Portals will be rendered in 3D view.\n"; - else - globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 3D view.\n"; - } - else if (!strcmp(p,Q3R_CMD_OPTIONS)) - { - DoConfigDialog (); - SaveConfig(); - - SceneChangeNotify(); - } +void QERPlug_Dispatch( const char* p, float* vMin, float* vMax, bool bSingleBrush ){ + globalOutputStream() << MSG_PREFIX "Command \"" << p << "\"\n"; + + if ( !strcmp( p,Q3R_CMD_ABOUT ) ) { + DoAboutDlg(); + } + else if ( !strcmp( p,Q3R_CMD_LOAD ) ) { + if ( DoLoadPortalFileDialog() == IDOK ) { + portals.Load(); + SceneChangeNotify(); + } + else + { + globalOutputStream() << MSG_PREFIX "Portal file load aborted.\n"; + } + } + else if ( !strcmp( p,Q3R_CMD_RELEASE ) ) { + portals.Purge(); + + SceneChangeNotify(); + + globalOutputStream() << MSG_PREFIX "Portals unloaded.\n"; + } + else if ( !strcmp( p,Q3R_CMD_SHOW_2D ) ) { + portals.show_2d = !portals.show_2d; + + SceneChangeNotify(); + SaveConfig(); + + if ( portals.show_2d ) { + globalOutputStream() << MSG_PREFIX "Portals will be rendered in 2D view.\n"; + } + else{ + globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 2D view.\n"; + } + } + else if ( !strcmp( p,Q3R_CMD_SHOW_3D ) ) { + portals.show_3d = !portals.show_3d; + SaveConfig(); + + SceneChangeNotify(); + + if ( portals.show_3d ) { + globalOutputStream() << MSG_PREFIX "Portals will be rendered in 3D view.\n"; + } + else{ + globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 3D view.\n"; + } + } + else if ( !strcmp( p,Q3R_CMD_OPTIONS ) ) { + DoConfigDialog(); + SaveConfig(); + + SceneChangeNotify(); + } } #include "modulesystem/singletonmodule.h" class PrtViewPluginDependencies : - public GlobalSceneGraphModuleRef, - public GlobalRadiantModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalOpenGLModuleRef, - public GlobalOpenGLStateLibraryModuleRef + public GlobalSceneGraphModuleRef, + public GlobalRadiantModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalOpenGLModuleRef, + public GlobalOpenGLStateLibraryModuleRef { }; class PrtViewPluginModule { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "prtview"); - - PrtViewPluginModule() - { - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - - PrtView_construct(); - } - ~PrtViewPluginModule() - { - PrtView_destroy(); - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "prtview" ); + +PrtViewPluginModule(){ + m_plugin.m_pfnQERPlug_Init = QERPlug_Init; + m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; + m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + + PrtView_construct(); +} +~PrtViewPluginModule(){ + PrtView_destroy(); +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonPrtViewPluginModule; @@ -320,9 +318,8 @@ typedef SingletonModule Singleto SingletonPrtViewPluginModule g_PrtViewPluginModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); - g_PrtViewPluginModule.selfRegister(); + g_PrtViewPluginModule.selfRegister(); } diff --git a/contrib/prtview/prtview.h b/contrib/prtview/prtview.h index 472b028a..e149ae80 100644 --- a/contrib/prtview/prtview.h +++ b/contrib/prtview/prtview.h @@ -1,32 +1,32 @@ /* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com + PrtView plugin for GtkRadiant + Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ -#if !defined(INCLUDED_PRTVIEW_H) +#if !defined( INCLUDED_PRTVIEW_H ) #define INCLUDED_PRTVIEW_H #define MSG_PREFIX "Portal Viewer plugin: " -void InitInstance (); -void SaveConfig (); +void InitInstance(); +void SaveConfig(); -int INIGetInt(char *key, int def); -void INISetInt(char *key, int val, char *comment = 0); +int INIGetInt( char *key, int def ); +void INISetInt( char *key, int val, char *comment = 0 ); #define IDOK 1 #define IDCANCEL 2 diff --git a/contrib/shaderplug/shaderplug.cpp b/contrib/shaderplug/shaderplug.cpp index 6554790b..62e9abe6 100644 --- a/contrib/shaderplug/shaderplug.cpp +++ b/contrib/shaderplug/shaderplug.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2006, Stefan Greven. -All Rights Reserved. + Copyright (C) 2006, Stefan Greven. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "shaderplug.h" @@ -46,218 +46,192 @@ const char SHADERTAG_FILE[] = "shadertags.xml"; } class ShaderPlugPluginDependencies : public GlobalRadiantModuleRef, - public GlobalFileSystemModuleRef, - public GlobalShadersModuleRef + public GlobalFileSystemModuleRef, + public GlobalShadersModuleRef { public: - ShaderPlugPluginDependencies() : - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")) - { - } +ShaderPlugPluginDependencies() : + GlobalShadersModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "shaders" ) ){ +} }; namespace Shaderplug { - GtkWindow* g_window; - - std::vector archives; - std::set shaders; - std::set textures; - - XmlTagBuilder TagBuilder; - void CreateTagFile(); - - const char* init(void* hApp, void* pMainWidget) - { - g_window = GTK_WINDOW(pMainWidget); - return ""; - } - const char* getName() - { - return "ShaderPlug"; - } - const char* getCommandList() - { - return "About;Create tag file"; - } - const char* getCommandTitleList() - { - return ""; - } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), "Shaderplug (1.0)\n\n" - "by Shaderman (shaderman@gmx.net)", - "About", - eMB_OK, - eMB_ICONDEFAULT); - } - if(string_equal(command, "Create tag file")) - { - CreateTagFile(); - } - } - - void loadArchiveFile(const char* filename) - { - archives.push_back(filename); - } - - typedef FreeCaller1 LoadArchiveFileCaller; - - void LoadTextureFile(const char* filename) - { - std::string s_filename = filename; - - char buffer[256]; - strcpy(buffer, "textures/"); - - // append filename without trailing file extension (.tga or .jpg for example) - strncat(buffer, filename, s_filename.length() - 4); - - std::set::iterator iter; - iter = shaders.find(buffer); - - // a shader with this name already exists - if(iter == shaders.end()) - { - textures.insert(buffer); - } - } - - typedef FreeCaller1 LoadTextureFileCaller; - - void GetTextures(char* extension) - { - GlobalFileSystem().forEachFile("textures/", extension, LoadTextureFileCaller(), 0); - } - - void LoadShaderList(const char* filename) - { - if(string_equal_prefix(filename, "textures/")) - { - shaders.insert(filename); - } - } - - typedef FreeCaller1 LoadShaderListCaller; - - void GetAllShaders() - { - GlobalShaderSystem().foreachShaderName(LoadShaderListCaller()); - } - - void GetArchiveList() - { - GlobalFileSystem().forEachArchive(LoadArchiveFileCaller()); - globalOutputStream() << "Shaderplug: " << (const Unsigned)Shaderplug::archives.size() << " archives found.\n"; - } - - void CreateTagFile() - { - const char* shader_type = GlobalRadiant().getGameDescriptionKeyValue("shaders"); - - GetAllShaders(); - globalOutputStream() << "Shaderplug: " << (const Unsigned)shaders.size() << " shaders found.\n"; - - if(string_equal(shader_type, "quake3")) - { - GetTextures("jpg"); - GetTextures("tga"); - GetTextures("png"); - - globalOutputStream() << "Shaderplug: " << (const Unsigned)textures.size() << " textures found.\n"; - } - - if(shaders.size() || textures.size() != 0) - { - globalOutputStream() << "Shaderplug: Creating XML tag file.\n"; - - TagBuilder.CreateXmlDocument(); - - std::set::reverse_iterator r_iter; - - for(r_iter = textures.rbegin(); r_iter != textures.rend(); ++r_iter) - { - TagBuilder.AddShaderNode(const_cast((*r_iter).c_str()), STOCK, TEXTURE); - } - - for(r_iter = shaders.rbegin(); r_iter != shaders.rend(); ++r_iter) - { - TagBuilder.AddShaderNode(const_cast((*r_iter).c_str()), STOCK, SHADER); - } - - // Get the tag file - StringOutputStream tagFileStream(256); - tagFileStream << GlobalRadiant().getLocalRcPath() << SHADERTAG_FILE; - char* tagFile = tagFileStream.c_str(); - - char message[256]; - strcpy(message, "Tag file saved to\n"); - strcat(message, tagFile); - strcat(message, "\nPlease restart Radiant now.\n"); - - if(file_exists(tagFile)) - { - EMessageBoxReturn result = GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), - "WARNING! A tag file already exists! Overwrite it?", "Overwrite tag file?", - eMB_NOYES, - eMB_ICONWARNING); - - if(result == eIDYES) - { - TagBuilder.SaveXmlDoc(tagFile); - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), message, "INFO", eMB_OK, eMB_ICONASTERISK); - } - } else { - TagBuilder.SaveXmlDoc(tagFile); - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), message, "INFO", eMB_OK, eMB_ICONASTERISK); - } - } else { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), - "No shaders or textures found. No XML tag file created!\n" - "", - "ERROR", - eMB_OK, - eMB_ICONERROR); - } - } +GtkWindow* g_window; + +std::vector archives; +std::set shaders; +std::set textures; + +XmlTagBuilder TagBuilder; +void CreateTagFile(); + +const char* init( void* hApp, void* pMainWidget ){ + g_window = GTK_WINDOW( pMainWidget ); + return ""; +} +const char* getName(){ + return "ShaderPlug"; +} +const char* getCommandList(){ + return "About;Create tag file"; +} +const char* getCommandTitleList(){ + return ""; +} +void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ + if ( string_equal( command, "About" ) ) { + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), "Shaderplug (1.0)\n\n" + "by Shaderman (shaderman@gmx.net)", + "About", + eMB_OK, + eMB_ICONDEFAULT ); + } + if ( string_equal( command, "Create tag file" ) ) { + CreateTagFile(); + } +} + +void loadArchiveFile( const char* filename ){ + archives.push_back( filename ); +} + +typedef FreeCaller1 LoadArchiveFileCaller; + +void LoadTextureFile( const char* filename ){ + std::string s_filename = filename; + + char buffer[256]; + strcpy( buffer, "textures/" ); + + // append filename without trailing file extension (.tga or .jpg for example) + strncat( buffer, filename, s_filename.length() - 4 ); + + std::set::iterator iter; + iter = shaders.find( buffer ); + + // a shader with this name already exists + if ( iter == shaders.end() ) { + textures.insert( buffer ); + } +} + +typedef FreeCaller1 LoadTextureFileCaller; + +void GetTextures( char* extension ){ + GlobalFileSystem().forEachFile( "textures/", extension, LoadTextureFileCaller(), 0 ); +} + +void LoadShaderList( const char* filename ){ + if ( string_equal_prefix( filename, "textures/" ) ) { + shaders.insert( filename ); + } +} + +typedef FreeCaller1 LoadShaderListCaller; + +void GetAllShaders(){ + GlobalShaderSystem().foreachShaderName( LoadShaderListCaller() ); +} + +void GetArchiveList(){ + GlobalFileSystem().forEachArchive( LoadArchiveFileCaller() ); + globalOutputStream() << "Shaderplug: " << (const Unsigned)Shaderplug::archives.size() << " archives found.\n"; +} + +void CreateTagFile(){ + const char* shader_type = GlobalRadiant().getGameDescriptionKeyValue( "shaders" ); + + GetAllShaders(); + globalOutputStream() << "Shaderplug: " << (const Unsigned)shaders.size() << " shaders found.\n"; + + if ( string_equal( shader_type, "quake3" ) ) { + GetTextures( "jpg" ); + GetTextures( "tga" ); + GetTextures( "png" ); + + globalOutputStream() << "Shaderplug: " << (const Unsigned)textures.size() << " textures found.\n"; + } + + if ( shaders.size() || textures.size() != 0 ) { + globalOutputStream() << "Shaderplug: Creating XML tag file.\n"; + + TagBuilder.CreateXmlDocument(); + + std::set::reverse_iterator r_iter; + + for ( r_iter = textures.rbegin(); r_iter != textures.rend(); ++r_iter ) + { + TagBuilder.AddShaderNode( const_cast( ( *r_iter ).c_str() ), STOCK, TEXTURE ); + } + + for ( r_iter = shaders.rbegin(); r_iter != shaders.rend(); ++r_iter ) + { + TagBuilder.AddShaderNode( const_cast( ( *r_iter ).c_str() ), STOCK, SHADER ); + } + + // Get the tag file + StringOutputStream tagFileStream( 256 ); + tagFileStream << GlobalRadiant().getLocalRcPath() << SHADERTAG_FILE; + char* tagFile = tagFileStream.c_str(); + + char message[256]; + strcpy( message, "Tag file saved to\n" ); + strcat( message, tagFile ); + strcat( message, "\nPlease restart Radiant now.\n" ); + + if ( file_exists( tagFile ) ) { + EMessageBoxReturn result = GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), + "WARNING! A tag file already exists! Overwrite it?", "Overwrite tag file?", + eMB_NOYES, + eMB_ICONWARNING ); + + if ( result == eIDYES ) { + TagBuilder.SaveXmlDoc( tagFile ); + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), message, "INFO", eMB_OK, eMB_ICONASTERISK ); + } + } + else { + TagBuilder.SaveXmlDoc( tagFile ); + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), message, "INFO", eMB_OK, eMB_ICONASTERISK ); + } + } + else { + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_window ), + "No shaders or textures found. No XML tag file created!\n" + "", + "ERROR", + eMB_OK, + eMB_ICONERROR ); + } +} } // namespace class ShaderPluginModule { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "ShaderPlug"); - - ShaderPluginModule() - { - m_plugin.m_pfnQERPlug_Init = &Shaderplug::init; - m_plugin.m_pfnQERPlug_GetName = &Shaderplug::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &Shaderplug::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &Shaderplug::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &Shaderplug::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "ShaderPlug" ); + +ShaderPluginModule(){ + m_plugin.m_pfnQERPlug_Init = &Shaderplug::init; + m_plugin.m_pfnQERPlug_GetName = &Shaderplug::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &Shaderplug::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &Shaderplug::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &Shaderplug::dispatch; +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonShaderPluginModule; SingletonShaderPluginModule g_ShaderPluginModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); - g_ShaderPluginModule.selfRegister(); + g_ShaderPluginModule.selfRegister(); } - - - - diff --git a/contrib/shaderplug/shaderplug.h b/contrib/shaderplug/shaderplug.h index 7ee45fd2..d30c625d 100644 --- a/contrib/shaderplug/shaderplug.h +++ b/contrib/shaderplug/shaderplug.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2006, Stefan Greven. -All Rights Reserved. + Copyright (C) 2006, Stefan Greven. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_SHADERPLUG_H) +#if !defined( INCLUDED_SHADERPLUG_H ) #define INCLUDED_SHADERPLUG_H #include "xml/xmltextags.h" diff --git a/contrib/sunplug/sunplug.cpp b/contrib/sunplug/sunplug.cpp index fa005426..50fb2cd8 100644 --- a/contrib/sunplug/sunplug.cpp +++ b/contrib/sunplug/sunplug.cpp @@ -1,22 +1,22 @@ /* -Sunplug plugin for GtkRadiant -Copyright (C) 2004 Topsun -Thanks to SPoG for help! + Sunplug plugin for GtkRadiant + Copyright (C) 2004 Topsun + Thanks to SPoG for help! -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #include "sunplug.h" @@ -41,40 +41,39 @@ void MapCoordinator(); #ifndef _WIN32 // linux itoa implementation -char* itoa( int value, char* result, int base ) -{ +char* itoa( int value, char* result, int base ){ // check that the base if valid - if (base < 2 || base > 16) - { - *result = 0; - return result; + if ( base < 2 || base > 16 ) { + *result = 0; + return result; } - + char* out = result; int quotient = value; - + do { - *out = "0123456789abcdef"[abs(quotient % base)]; + *out = "0123456789abcdef"[abs( quotient % base )]; ++out; - + quotient /= base; - } while (quotient); - + } while ( quotient ); + // Only apply negative sign for base 10 - if( value < 0 && base == 10) - *out++ = '-'; - - std::reverse(result, out); - + if ( value < 0 && base == 10 ) { + *out++ = '-'; + } + + std::reverse( result, out ); + *out = 0; return result; } #endif typedef struct _mapcoord_setting_packet { - GtkSpinButton *spinner1, *spinner2, *spinner3, *spinner4; - Entity* worldspawn; + GtkSpinButton *spinner1, *spinner2, *spinner3, *spinner4; + Entity* worldspawn; } mapcoord_setting_packet; static int map_minX, map_maxX, map_minY, map_maxY; @@ -86,109 +85,98 @@ mapcoord_setting_packet msp; // ************************** class EntityFindByClassname : public scene::Graph::Walker { - const char* m_name; - Entity*& m_entity; +const char* m_name; +Entity*& m_entity; public: - EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) - { - m_entity = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(m_entity == 0) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && string_equal(m_name, entity->getKeyValue("classname"))) - { - m_entity = entity; - } - } - return true; - } +EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ + m_entity = 0; +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_entity == 0 ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 + && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + m_entity = entity; + } + } + return true; +} }; -Entity* Scene_FindEntityByClass(const char* name) -{ - Entity* entity; - GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); - return entity; +Entity* Scene_FindEntityByClass( const char* name ){ + Entity* entity; + GlobalSceneGraph().traverse( EntityFindByClassname( name, entity ) ); + return entity; } // ************************** // ** GTK callback functions ** // ************************** -static gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) -{ - /* If you return FALSE in the "delete_event" signal handler, - * GTK will emit the "destroy" signal. Returning TRUE means - * you don't want the window to be destroyed. - * This is useful for popping up 'are you sure you want to quit?' - * type dialogs. */ +static gboolean delete_event( GtkWidget *widget, GdkEvent *event, gpointer data ){ + /* If you return FALSE in the "delete_event" signal handler, + * GTK will emit the "destroy" signal. Returning TRUE means + * you don't want the window to be destroyed. + * This is useful for popping up 'are you sure you want to quit?' + * type dialogs. */ - return FALSE; + return FALSE; } // destroy widget if destroy signal is passed to widget -static void destroy(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(widget); +static void destroy( GtkWidget *widget, gpointer data ){ + gtk_widget_destroy( widget ); } // function for close button to destroy the toplevel widget -static void close_window(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(gtk_widget_get_toplevel(widget)); +static void close_window( GtkWidget *widget, gpointer data ){ + gtk_widget_destroy( gtk_widget_get_toplevel( widget ) ); } // callback function to assign the optimal mapcoords to the spinboxes -static void input_optimal(GtkWidget *widget, gpointer data) -{ - gtk_spin_button_set_value(msp.spinner1, minX); - gtk_spin_button_set_value(msp.spinner2, maxY); - gtk_spin_button_set_value(msp.spinner3, maxX); - gtk_spin_button_set_value(msp.spinner4, minY); +static void input_optimal( GtkWidget *widget, gpointer data ){ + gtk_spin_button_set_value( msp.spinner1, minX ); + gtk_spin_button_set_value( msp.spinner2, maxY ); + gtk_spin_button_set_value( msp.spinner3, maxX ); + gtk_spin_button_set_value( msp.spinner4, minY ); } // Spinner return value function -gint grab_int_value(GtkSpinButton *a_spinner, gpointer user_data) { - return gtk_spin_button_get_value_as_int(a_spinner); +gint grab_int_value( GtkSpinButton *a_spinner, gpointer user_data ) { + return gtk_spin_button_get_value_as_int( a_spinner ); } // write the values of the Spinner-Boxes to the worldspawn -static void set_coordinates(GtkWidget *widget, gpointer data) -{ - //Str str_min, str_max; - char buffer[10], str_min[20], str_max[20]; - - itoa(gtk_spin_button_get_value_as_int(msp.spinner1), str_min, 10); - itoa(gtk_spin_button_get_value_as_int(msp.spinner2), buffer, 10); - strcat(str_min, " "); - strcat(str_min, buffer); - msp.worldspawn->setKeyValue("mapcoordsmins", str_min); - - itoa(gtk_spin_button_get_value_as_int(msp.spinner3), str_max, 10); - itoa(gtk_spin_button_get_value_as_int(msp.spinner4), buffer, 10); - strcat(str_max, " "); - strcat(str_max, buffer); - UndoableCommand undo("SunPlug.entitySetMapcoords"); - msp.worldspawn->setKeyValue("mapcoordsmaxs", str_max); - - close_window(widget, NULL); +static void set_coordinates( GtkWidget *widget, gpointer data ){ + //Str str_min, str_max; + char buffer[10], str_min[20], str_max[20]; + + itoa( gtk_spin_button_get_value_as_int( msp.spinner1 ), str_min, 10 ); + itoa( gtk_spin_button_get_value_as_int( msp.spinner2 ), buffer, 10 ); + strcat( str_min, " " ); + strcat( str_min, buffer ); + msp.worldspawn->setKeyValue( "mapcoordsmins", str_min ); + + itoa( gtk_spin_button_get_value_as_int( msp.spinner3 ), str_max, 10 ); + itoa( gtk_spin_button_get_value_as_int( msp.spinner4 ), buffer, 10 ); + strcat( str_max, " " ); + strcat( str_max, buffer ); + UndoableCommand undo( "SunPlug.entitySetMapcoords" ); + msp.worldspawn->setKeyValue( "mapcoordsmaxs", str_max ); + + close_window( widget, NULL ); } class SunPlugPluginDependencies : - public GlobalRadiantModuleRef, // basic class for all other module refs - public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that - public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) - public GlobalEntityModuleRef // to access and modify the entities + public GlobalRadiantModuleRef, // basic class for all other module refs + public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that + public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) + public GlobalEntityModuleRef // to access and modify the entities { public: - SunPlugPluginDependencies() : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities"))//, - { - } +SunPlugPluginDependencies() : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ){ //, +} }; // ************************* @@ -196,63 +184,56 @@ public: // ************************* namespace SunPlug { - GtkWindow* main_window; - char MenuList[100] = ""; - - const char* init(void* hApp, void* pMainWidget) - { - main_window = GTK_WINDOW(pMainWidget); - return "Initializing SunPlug for GTKRadiant"; - } - const char* getName() - { - return "SunPlug"; // name that is shown in the menue - } - const char* getCommandList() - { - const char about[] = "About..."; - const char etMapCoordinator[] = ";ET-MapCoordinator"; - - strcat(MenuList, about); - if (strncmp(GlobalRadiant().getGameName(), "etmain", 6) == 0) strcat(MenuList, etMapCoordinator); - return (const char*)MenuList; - } - const char* getCommandTitleList() - { - return ""; - } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) // message processing - { - if(string_equal(command, "About...")) - { - about_plugin_window(); +GtkWindow* main_window; +char MenuList[100] = ""; + +const char* init( void* hApp, void* pMainWidget ){ + main_window = GTK_WINDOW( pMainWidget ); + return "Initializing SunPlug for GTKRadiant"; +} +const char* getName(){ + return "SunPlug"; // name that is shown in the menue +} +const char* getCommandList(){ + const char about[] = "About..."; + const char etMapCoordinator[] = ";ET-MapCoordinator"; + + strcat( MenuList, about ); + if ( strncmp( GlobalRadiant().getGameName(), "etmain", 6 ) == 0 ) { + strcat( MenuList, etMapCoordinator ); } - if(string_equal(command, "ET-MapCoordinator")) - { - MapCoordinator(); - } - } + return (const char*)MenuList; +} +const char* getCommandTitleList(){ + return ""; +} +void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ // message processing + if ( string_equal( command, "About..." ) ) { + about_plugin_window(); + } + if ( string_equal( command, "ET-MapCoordinator" ) ) { + MapCoordinator(); + } +} } // namespace class SunPlugModule : public TypeSystemRef { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "SunPlug"); +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "SunPlug" ); - SunPlugModule() - { +SunPlugModule(){ m_plugin.m_pfnQERPlug_Init = &SunPlug::init; m_plugin.m_pfnQERPlug_GetName = &SunPlug::getName; m_plugin.m_pfnQERPlug_GetCommandList = &SunPlug::getCommandList; m_plugin.m_pfnQERPlug_GetCommandTitleList = &SunPlug::getCommandTitleList; m_plugin.m_pfnQERPlug_Dispatch = &SunPlug::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonSunPlugModule; @@ -260,11 +241,10 @@ typedef SingletonModule SingletonSunPl SingletonSunPlugModule g_SunPlugModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); - g_SunPlugModule.selfRegister(); + g_SunPlugModule.selfRegister(); } // ************ @@ -272,191 +252,191 @@ extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) // ************ // About dialog -void about_plugin_window() -{ - GtkWidget *window, *vbox, *label, *button; +void about_plugin_window(){ + GtkWidget *window, *vbox, *label, *button; - window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // create a window - gtk_window_set_transient_for(GTK_WINDOW(window), SunPlug::main_window); // make the window to stay in front of the main window - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); // connect the delete event - g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // connect the destroy event for the window - gtk_window_set_title(GTK_WINDOW(window), "About SunPlug"); // set the title of the window for the window - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); // don't let the user resize the window - gtk_window_set_modal(GTK_WINDOW(window), TRUE); // force the user not to do something with the other windows - gtk_container_set_border_width(GTK_CONTAINER(window), 10); // set the border of the window + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); // create a window + gtk_window_set_transient_for( GTK_WINDOW( window ), SunPlug::main_window ); // make the window to stay in front of the main window + g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( delete_event ), NULL ); // connect the delete event + g_signal_connect( G_OBJECT( window ), "destroy", G_CALLBACK( destroy ), NULL ); // connect the destroy event for the window + gtk_window_set_title( GTK_WINDOW( window ), "About SunPlug" ); // set the title of the window for the window + gtk_window_set_resizable( GTK_WINDOW( window ), FALSE ); // don't let the user resize the window + gtk_window_set_modal( GTK_WINDOW( window ), TRUE ); // force the user not to do something with the other windows + gtk_container_set_border_width( GTK_CONTAINER( window ), 10 ); // set the border of the window - vbox = gtk_vbox_new(FALSE, 10); // create a box to arrange new objects vertically - gtk_container_add(GTK_CONTAINER(window), vbox); // add the box to the window + vbox = gtk_vbox_new( FALSE, 10 ); // create a box to arrange new objects vertically + gtk_container_add( GTK_CONTAINER( window ), vbox ); // add the box to the window - label = gtk_label_new("SunPlug v1.0 for NetRadiant 1.5\nby Topsun"); // create a label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // text align left - gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 2); // insert the label in the box + label = gtk_label_new( "SunPlug v1.0 for NetRadiant 1.5\nby Topsun" ); // create a label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // text align left + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, FALSE, 2 ); // insert the label in the box - button = gtk_button_new_with_label("OK"); // create a button with text - g_signal_connect_swapped(G_OBJECT(button), "clicked", G_CALLBACK (gtk_widget_destroy), window); // connect the click event to close the window - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert the button in the box + button = gtk_button_new_with_label( "OK" ); // create a button with text + g_signal_connect_swapped( G_OBJECT( button ), "clicked", G_CALLBACK( gtk_widget_destroy ), window ); // connect the click event to close the window + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 2 ); // insert the button in the box - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // center the window on screen + gtk_window_set_position( GTK_WINDOW( window ), GTK_WIN_POS_CENTER ); // center the window on screen - gtk_widget_show_all(window); // show the window and all subelements + gtk_widget_show_all( window ); // show the window and all subelements } // get the current bounding box and return the optimal coordinates -void GetOptimalCoordinates(AABB *levelBoundingBox) -{ - int half_width, half_heigth, center_x, center_y; - - half_width = levelBoundingBox->extents.x(); - half_heigth = levelBoundingBox->extents.y(); - center_x = levelBoundingBox->origin.x(); - center_y = levelBoundingBox->origin.y(); - - if (half_width > 175 || half_heigth > 175) // the square must be at least 350x350 units - { - // the wider side is the indicator for the square - if (half_width >= half_heigth) - { - minX = center_x - half_width; - maxX = center_x + half_width; - minY = center_y - half_width; - maxY = center_y + half_width; - } else { - minX = center_x - half_heigth; - maxX = center_x + half_heigth; - minY = center_y - half_heigth; - maxY = center_y + half_heigth; - } - } else { - minX = center_x - 175; - maxX = center_x + 175; - minY = center_y - 175; - maxY = center_y + 175; - } +void GetOptimalCoordinates( AABB *levelBoundingBox ){ + int half_width, half_heigth, center_x, center_y; + + half_width = levelBoundingBox->extents.x(); + half_heigth = levelBoundingBox->extents.y(); + center_x = levelBoundingBox->origin.x(); + center_y = levelBoundingBox->origin.y(); + + if ( half_width > 175 || half_heigth > 175 ) { // the square must be at least 350x350 units + // the wider side is the indicator for the square + if ( half_width >= half_heigth ) { + minX = center_x - half_width; + maxX = center_x + half_width; + minY = center_y - half_width; + maxY = center_y + half_width; + } + else { + minX = center_x - half_heigth; + maxX = center_x + half_heigth; + minY = center_y - half_heigth; + maxY = center_y + half_heigth; + } + } + else { + minX = center_x - 175; + maxX = center_x + 175; + minY = center_y - 175; + maxY = center_y + 175; + } } // MapCoordinator dialog window -void MapCoordinator() -{ - GtkWidget *window, *vbox, *table, *label, *spinnerMinX, *spinnerMinY, *spinnerMaxX, *spinnerMaxY, *button; - GtkAdjustment *spinner_adj_MinX, *spinner_adj_MinY, *spinner_adj_MaxX, *spinner_adj_MaxY; - Entity *theWorldspawn = NULL; - const char *buffer; - char line[20]; - - // in any case we need a window to show the user what to do - window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // create the window - gtk_window_set_transient_for(GTK_WINDOW(window), SunPlug::main_window); // make the window to stay in front of the main window - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); // connect the delete event for the window - g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // connect the destroy event for the window - gtk_window_set_title(GTK_WINDOW(window), "ET-MapCoordinator"); // set the title of the window for the window - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); // don't let the user resize the window - gtk_window_set_modal(GTK_WINDOW(window), TRUE); // force the user not to do something with the other windows - gtk_container_set_border_width(GTK_CONTAINER(window), 10); // set the border of the window - - vbox = gtk_vbox_new(FALSE, 10); // create a box to arrange new objects vertically - gtk_container_add(GTK_CONTAINER(window), vbox); // add the box to the window - - scene::Path path = makeReference(GlobalSceneGraph().root()); // get the path to the root element of the graph - scene::Instance* instance = GlobalSceneGraph().find(path); // find the instance to the given path - AABB levelBoundingBox = instance->worldAABB(); // get the bounding box of the level - - theWorldspawn = Scene_FindEntityByClass("worldspawn"); // find the entity worldspawn - if (theWorldspawn != 0) { // need to have a worldspawn otherwise setting a value crashes the radiant - // next two if's: get the current values of the mapcoords - buffer = theWorldspawn->getKeyValue("mapcoordsmins"); // upper left corner - if (strlen(buffer) > 0) { - strncpy(line, buffer, 19); - map_minX = atoi(strtok(line, " ")); // minimum of x value - map_minY = atoi(strtok(NULL, " ")); // maximum of y value - } else { - map_minX = 0; - map_minY = 0; +void MapCoordinator(){ + GtkWidget *window, *vbox, *table, *label, *spinnerMinX, *spinnerMinY, *spinnerMaxX, *spinnerMaxY, *button; + GtkAdjustment *spinner_adj_MinX, *spinner_adj_MinY, *spinner_adj_MaxX, *spinner_adj_MaxY; + Entity *theWorldspawn = NULL; + const char *buffer; + char line[20]; + + // in any case we need a window to show the user what to do + window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); // create the window + gtk_window_set_transient_for( GTK_WINDOW( window ), SunPlug::main_window ); // make the window to stay in front of the main window + g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( delete_event ), NULL ); // connect the delete event for the window + g_signal_connect( G_OBJECT( window ), "destroy", G_CALLBACK( destroy ), NULL ); // connect the destroy event for the window + gtk_window_set_title( GTK_WINDOW( window ), "ET-MapCoordinator" ); // set the title of the window for the window + gtk_window_set_resizable( GTK_WINDOW( window ), FALSE ); // don't let the user resize the window + gtk_window_set_modal( GTK_WINDOW( window ), TRUE ); // force the user not to do something with the other windows + gtk_container_set_border_width( GTK_CONTAINER( window ), 10 ); // set the border of the window + + vbox = gtk_vbox_new( FALSE, 10 ); // create a box to arrange new objects vertically + gtk_container_add( GTK_CONTAINER( window ), vbox ); // add the box to the window + + scene::Path path = makeReference( GlobalSceneGraph().root() ); // get the path to the root element of the graph + scene::Instance* instance = GlobalSceneGraph().find( path ); // find the instance to the given path + AABB levelBoundingBox = instance->worldAABB(); // get the bounding box of the level + + theWorldspawn = Scene_FindEntityByClass( "worldspawn" ); // find the entity worldspawn + if ( theWorldspawn != 0 ) { // need to have a worldspawn otherwise setting a value crashes the radiant + // next two if's: get the current values of the mapcoords + buffer = theWorldspawn->getKeyValue( "mapcoordsmins" ); // upper left corner + if ( strlen( buffer ) > 0 ) { + strncpy( line, buffer, 19 ); + map_minX = atoi( strtok( line, " " ) ); // minimum of x value + map_minY = atoi( strtok( NULL, " " ) ); // maximum of y value + } + else { + map_minX = 0; + map_minY = 0; + } + buffer = theWorldspawn->getKeyValue( "mapcoordsmaxs" ); // lower right corner + if ( strlen( buffer ) > 0 ) { + strncpy( line, buffer, 19 ); + map_maxX = atoi( strtok( line, " " ) ); // maximum of x value + map_maxY = atoi( strtok( NULL, " " ) ); // minimum of y value + } + else { + map_maxX = 0; + map_maxY = 0; + } + + globalOutputStream() << "SunPlug: calculating optimal coordinates\n"; // write to console that we are calculating the coordinates + GetOptimalCoordinates( &levelBoundingBox ); // calculate optimal mapcoords with the dimensions of the level bounding box + globalOutputStream() << "SunPlug: adviced mapcoordsmins=" << minX << " " << maxY << "\n"; // console info about mapcoordsmins + globalOutputStream() << "SunPlug: adviced mapcoordsmaxs=" << maxX << " " << minY << "\n"; // console info about mapcoordsmaxs + + spinner_adj_MinX = (GtkAdjustment *)gtk_adjustment_new( map_minX, -65536.0, 65536.0, 1.0, 5.0, 0 ); // create adjustment for value and range of minimum x value + spinner_adj_MinY = (GtkAdjustment *)gtk_adjustment_new( map_minY, -65536.0, 65536.0, 1.0, 5.0, 0 ); // create adjustment for value and range of minimum y value + spinner_adj_MaxX = (GtkAdjustment *)gtk_adjustment_new( map_maxX, -65536.0, 65536.0, 1.0, 5.0, 0 ); // create adjustment for value and range of maximum x value + spinner_adj_MaxY = (GtkAdjustment *)gtk_adjustment_new( map_maxY, -65536.0, 65536.0, 1.0, 5.0, 0 ); // create adjustment for value and range of maximum y value + + button = gtk_button_new_with_label( "Get optimal mapcoords" ); // create button with text + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( input_optimal ), NULL ); // connect button with callback function + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 2 ); // insert button into vbox + + gtk_box_pack_start( GTK_BOX( vbox ), gtk_hseparator_new(), FALSE, FALSE, 2 ); // insert separator into vbox + + table = gtk_table_new( 4, 3, TRUE ); // create table + gtk_table_set_row_spacings( GTK_TABLE( table ), 8 ); // set row spacings + gtk_table_set_col_spacings( GTK_TABLE( table ), 8 ); // set column spacings + gtk_box_pack_start( GTK_BOX( vbox ), table, FALSE, FALSE, 2 ); // insert table into vbox + + label = gtk_label_new( "x" ); // create label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // align text to the left side + gtk_table_attach_defaults( GTK_TABLE( table ), label, 1, 2, 0, 1 ); // insert label into table + + label = gtk_label_new( "y" ); // create label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // align text to the left side + gtk_table_attach_defaults( GTK_TABLE( table ), label, 2, 3, 0, 1 ); // insert label into table + + label = gtk_label_new( "mapcoordsmins" ); // create label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // align text to the left side + gtk_table_attach_defaults( GTK_TABLE( table ), label, 0, 1, 1, 2 ); // insert label into table + + spinnerMinX = gtk_spin_button_new( spinner_adj_MinX, 1.0, 0 ); // create textbox wiht value spin, value and value range + gtk_table_attach_defaults( GTK_TABLE( table ), spinnerMinX, 1, 2, 1, 2 ); // insert spinbox into table + + spinnerMinY = gtk_spin_button_new( spinner_adj_MinY, 1.0, 0 ); // create textbox wiht value spin, value and value range + gtk_table_attach_defaults( GTK_TABLE( table ), spinnerMinY, 2, 3, 1, 2 ); // insert spinbox into table + + label = gtk_label_new( "mapcoordsmaxs" ); // create label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // align text to the left side + gtk_table_attach_defaults( GTK_TABLE( table ), label, 0, 1, 2, 3 ); // insert label into table + + spinnerMaxX = gtk_spin_button_new( spinner_adj_MaxX, 1.0, 0 ); // create textbox wiht value spin, value and value range + gtk_table_attach_defaults( GTK_TABLE( table ), spinnerMaxX, 1, 2, 2, 3 ); // insert spinbox into table + + spinnerMaxY = gtk_spin_button_new( spinner_adj_MaxY, 1.0, 0 ); // create textbox wiht value spin, value and value range + gtk_table_attach_defaults( GTK_TABLE( table ), spinnerMaxY, 2, 3, 2, 3 ); // insert spinbox into table + + // put the references to the spinboxes and the worldspawn into the global exchange + msp.spinner1 = GTK_SPIN_BUTTON( spinnerMinX ); + msp.spinner2 = GTK_SPIN_BUTTON( spinnerMinY ); + msp.spinner3 = GTK_SPIN_BUTTON( spinnerMaxX ); + msp.spinner4 = GTK_SPIN_BUTTON( spinnerMaxY ); + msp.worldspawn = theWorldspawn; + + button = gtk_button_new_with_label( "Set" ); // create button with text + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( set_coordinates ), NULL ); // connect button with callback function + gtk_table_attach_defaults( GTK_TABLE( table ), button, 1, 2, 3, 4 ); // insert button into table + + button = gtk_button_new_with_label( "Cancel" ); // create button with text + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( close_window ), NULL ); // connect button with callback function + gtk_table_attach_defaults( GTK_TABLE( table ), button, 2, 3, 3, 4 ); // insert button into table } - buffer = theWorldspawn->getKeyValue("mapcoordsmaxs"); // lower right corner - if (strlen(buffer) > 0) { - strncpy(line, buffer, 19); - map_maxX = atoi(strtok(line, " ")); // maximum of x value - map_maxY = atoi(strtok(NULL, " ")); // minimum of y value - } else { - map_maxX = 0; - map_maxY = 0; + else { + globalOutputStream() << "SunPlug: no worldspawn found!\n"; // output error to console + + label = gtk_label_new( "ERROR: No worldspawn was found in the map!\nIn order to use this tool the map must have at least one brush in the worldspawn. " ); // create a label + gtk_label_set_justify( GTK_LABEL( label ), GTK_JUSTIFY_LEFT ); // text align left + gtk_box_pack_start( GTK_BOX( vbox ), label, FALSE, FALSE, 2 ); // insert the label in the box + + button = gtk_button_new_with_label( "OK" ); // create a button with text + g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( close_window ), NULL ); // connect the click event to close the window + gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 2 ); // insert the button in the box } - globalOutputStream() << "SunPlug: calculating optimal coordinates\n"; // write to console that we are calculating the coordinates - GetOptimalCoordinates(&levelBoundingBox); // calculate optimal mapcoords with the dimensions of the level bounding box - globalOutputStream() << "SunPlug: adviced mapcoordsmins=" << minX << " " << maxY << "\n"; // console info about mapcoordsmins - globalOutputStream() << "SunPlug: adviced mapcoordsmaxs=" << maxX << " " << minY << "\n"; // console info about mapcoordsmaxs - - spinner_adj_MinX = (GtkAdjustment *)gtk_adjustment_new(map_minX, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of minimum x value - spinner_adj_MinY = (GtkAdjustment *)gtk_adjustment_new(map_minY, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of minimum y value - spinner_adj_MaxX = (GtkAdjustment *)gtk_adjustment_new(map_maxX, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of maximum x value - spinner_adj_MaxY = (GtkAdjustment *)gtk_adjustment_new(map_maxY, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of maximum y value - - button = gtk_button_new_with_label("Get optimal mapcoords"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(input_optimal), NULL); // connect button with callback function - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert button into vbox - - gtk_box_pack_start(GTK_BOX(vbox), gtk_hseparator_new(), FALSE, FALSE, 2); // insert separator into vbox - - table = gtk_table_new(4, 3, TRUE); // create table - gtk_table_set_row_spacings(GTK_TABLE(table), 8); // set row spacings - gtk_table_set_col_spacings(GTK_TABLE(table), 8); // set column spacings - gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 2); // insert table into vbox - - label = gtk_label_new("x"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 1, 2, 0, 1); // insert label into table - - label = gtk_label_new("y"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 3, 0, 1); // insert label into table - - label = gtk_label_new("mapcoordsmins"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 1, 1, 2); // insert label into table - - spinnerMinX = gtk_spin_button_new(spinner_adj_MinX, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMinX, 1, 2, 1, 2); // insert spinbox into table - - spinnerMinY = gtk_spin_button_new(spinner_adj_MinY, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMinY, 2, 3, 1, 2); // insert spinbox into table - - label = gtk_label_new("mapcoordsmaxs"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 1, 2, 3); // insert label into table - - spinnerMaxX = gtk_spin_button_new(spinner_adj_MaxX, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMaxX, 1, 2, 2, 3); // insert spinbox into table - - spinnerMaxY = gtk_spin_button_new(spinner_adj_MaxY, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMaxY, 2, 3, 2, 3); // insert spinbox into table - - // put the references to the spinboxes and the worldspawn into the global exchange - msp.spinner1 = GTK_SPIN_BUTTON(spinnerMinX); - msp.spinner2 = GTK_SPIN_BUTTON(spinnerMinY); - msp.spinner3 = GTK_SPIN_BUTTON(spinnerMaxX); - msp.spinner4 = GTK_SPIN_BUTTON(spinnerMaxY); - msp.worldspawn = theWorldspawn; - - button = gtk_button_new_with_label("Set"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(set_coordinates), NULL); // connect button with callback function - gtk_table_attach_defaults(GTK_TABLE(table), button, 1, 2, 3, 4); // insert button into table - - button = gtk_button_new_with_label("Cancel"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(close_window), NULL); // connect button with callback function - gtk_table_attach_defaults(GTK_TABLE(table), button, 2, 3, 3, 4); // insert button into table - } else { - globalOutputStream() << "SunPlug: no worldspawn found!\n"; // output error to console - - label = gtk_label_new("ERROR: No worldspawn was found in the map!\nIn order to use this tool the map must have at least one brush in the worldspawn. "); // create a label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // text align left - gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 2); // insert the label in the box - - button = gtk_button_new_with_label("OK"); // create a button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(close_window), NULL); // connect the click event to close the window - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert the button in the box - } - - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // center the window - gtk_widget_show_all(window); // show the window and all subelements + gtk_window_set_position( GTK_WINDOW( window ), GTK_WIN_POS_CENTER ); // center the window + gtk_widget_show_all( window ); // show the window and all subelements } diff --git a/contrib/sunplug/sunplug.h b/contrib/sunplug/sunplug.h index fafdc897..8ea4f50c 100644 --- a/contrib/sunplug/sunplug.h +++ b/contrib/sunplug/sunplug.h @@ -1,22 +1,22 @@ /* -Sunplug plugin for GtkRadiant -Copyright (C) 2004 Topsun -Thanks to SPoG for help! + Sunplug plugin for GtkRadiant + Copyright (C) 2004 Topsun + Thanks to SPoG for help! -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ #ifndef _PLUGIN_SUNPLUG_ #define _PLUGIN_SUNPLUG_ diff --git a/contrib/ufoaiplug/ufoai.cpp b/contrib/ufoaiplug/ufoai.cpp index e371e833..bb118664 100644 --- a/contrib/ufoaiplug/ufoai.cpp +++ b/contrib/ufoaiplug/ufoai.cpp @@ -1,20 +1,20 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ufoai.h" #include "ufoai_level.h" @@ -44,142 +44,117 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "ieclass.h" class UFOAIPluginDependencies : - public GlobalRadiantModuleRef, // basic class for all other module refs - public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that - public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) - public GlobalEntityModuleRef, // to access and modify the entities - public GlobalEntityClassManagerModuleRef + public GlobalRadiantModuleRef, // basic class for all other module refs + public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that + public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) + public GlobalEntityModuleRef, // to access and modify the entities + public GlobalEntityClassManagerModuleRef { public: - UFOAIPluginDependencies(void) : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), - GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")) - { - } +UFOAIPluginDependencies( void ) : + GlobalEntityModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entities" ) ), + GlobalEntityClassManagerModuleRef( GlobalRadiant().getRequiredGameDescriptionKeyValue( "entityclass" ) ){ +} }; namespace UFOAI { - GtkWindow* g_mainwnd; +GtkWindow* g_mainwnd; - const char* init(void* hApp, void* pMainWidget) - { - g_mainwnd = GTK_WINDOW(pMainWidget); - return "Initializing GTKRadiant UFOAI plugin"; +const char* init( void* hApp, void* pMainWidget ){ + g_mainwnd = GTK_WINDOW( pMainWidget ); + return "Initializing GTKRadiant UFOAI plugin"; +} +const char* getName(){ + return "UFO:AI"; +} +const char* getCommandList(){ + /*GlobalRadiant().getGameName()*/ + return "About;-;Worldspawn reset;Worldspawn;Perform check;-;Level 1;Level 2;Level 3;Level 4;Level 5;Level 6;Level 7;Level 8;-;StepOn;ActorClip;WeaponClip;Nodraw"; +} +const char* getCommandTitleList(){ + return ""; +} +void dispatch( const char* command, float* vMin, float* vMax, bool bSingleBrush ){ + char *message = NULL; + if ( string_equal( command, "About" ) ) { + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), + "UFO:AI Plugin (http://ufoai.sf.net)\nBuild: " __DATE__ "\nRadiant version: " RADIANT_VERSION "\nPlugin version: " PLUGIN_VERSION "\nAuthor: Martin Gerhardy (tlh2000/mattn)\n", "About", + eMB_OK, eMB_ICONDEFAULT ); } - const char* getName() - { - return "UFO:AI"; + else if ( string_equal( command, "Level 1" ) ) { + filter_level( CONTENTS_LEVEL1 ); } - const char* getCommandList() - { - /*GlobalRadiant().getGameName()*/ - return "About;-;Worldspawn reset;Worldspawn;Perform check;-;Level 1;Level 2;Level 3;Level 4;Level 5;Level 6;Level 7;Level 8;-;StepOn;ActorClip;WeaponClip;Nodraw"; + else if ( string_equal( command, "Level 2" ) ) { + filter_level( CONTENTS_LEVEL2 ); } - const char* getCommandTitleList() - { - return ""; + else if ( string_equal( command, "Level 3" ) ) { + filter_level( CONTENTS_LEVEL3 ); } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - char *message = NULL; - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), - "UFO:AI Plugin (http://ufoai.sf.net)\nBuild: " __DATE__ "\nRadiant version: " RADIANT_VERSION "\nPlugin version: " PLUGIN_VERSION "\nAuthor: Martin Gerhardy (tlh2000/mattn)\n", "About", - eMB_OK, eMB_ICONDEFAULT); - } - else if(string_equal(command, "Level 1")) - { - filter_level(CONTENTS_LEVEL1); - } - else if(string_equal(command, "Level 2")) - { - filter_level(CONTENTS_LEVEL2); - } - else if(string_equal(command, "Level 3")) - { - filter_level(CONTENTS_LEVEL3); - } - else if(string_equal(command, "Worldspawn")) - { - assign_default_values_to_worldspawn(false, &message); - } - else if(string_equal(command, "Worldspawn reset")) - { - assign_default_values_to_worldspawn(true, &message); - } - else if(string_equal(command, "Perform check")) - { - check_map_values(&message); - } - else if(string_equal(command, "Level 4")) - { - filter_level(CONTENTS_LEVEL4); - } - else if(string_equal(command, "Level 5")) - { - filter_level(CONTENTS_LEVEL5); - } - else if(string_equal(command, "Level 6")) - { - filter_level(CONTENTS_LEVEL6); - } - else if(string_equal(command, "Level 7")) - { - filter_level(CONTENTS_LEVEL7); - } - else if(string_equal(command, "Level 8")) - { - filter_level(CONTENTS_LEVEL8); - } - else if(string_equal(command, "StepOn")) - { - filter_stepon(); - } - else if(string_equal(command, "ActorClip")) - { - filter_actorclip(); - } - else if(string_equal(command, "WeaponClip")) - { - filter_weaponclip(); - } - else if(string_equal(command, "NoDraw")) - { - filter_nodraw(); - } - - if (message != NULL) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), - message, "Note", - eMB_OK, eMB_ICONDEFAULT); - } - SceneChangeNotify(); + else if ( string_equal( command, "Worldspawn" ) ) { + assign_default_values_to_worldspawn( false, &message ); + } + else if ( string_equal( command, "Worldspawn reset" ) ) { + assign_default_values_to_worldspawn( true, &message ); + } + else if ( string_equal( command, "Perform check" ) ) { + check_map_values( &message ); + } + else if ( string_equal( command, "Level 4" ) ) { + filter_level( CONTENTS_LEVEL4 ); + } + else if ( string_equal( command, "Level 5" ) ) { + filter_level( CONTENTS_LEVEL5 ); + } + else if ( string_equal( command, "Level 6" ) ) { + filter_level( CONTENTS_LEVEL6 ); + } + else if ( string_equal( command, "Level 7" ) ) { + filter_level( CONTENTS_LEVEL7 ); + } + else if ( string_equal( command, "Level 8" ) ) { + filter_level( CONTENTS_LEVEL8 ); + } + else if ( string_equal( command, "StepOn" ) ) { + filter_stepon(); + } + else if ( string_equal( command, "ActorClip" ) ) { + filter_actorclip(); } + else if ( string_equal( command, "WeaponClip" ) ) { + filter_weaponclip(); + } + else if ( string_equal( command, "NoDraw" ) ) { + filter_nodraw(); + } + + if ( message != NULL ) { + GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( g_mainwnd ), + message, "Note", + eMB_OK, eMB_ICONDEFAULT ); + } + SceneChangeNotify(); +} } // namespace class UFOAIModule : public TypeSystemRef { - _QERPluginTable m_plugin; +_QERPluginTable m_plugin; public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "UFO:AI"); - - UFOAIModule() - { - m_plugin.m_pfnQERPlug_Init = &UFOAI::init; - m_plugin.m_pfnQERPlug_GetName = &UFOAI::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &UFOAI::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &UFOAI::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &UFOAI::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } +typedef _QERPluginTable Type; +STRING_CONSTANT( Name, "UFO:AI" ); + +UFOAIModule(){ + m_plugin.m_pfnQERPlug_Init = &UFOAI::init; + m_plugin.m_pfnQERPlug_GetName = &UFOAI::getName; + m_plugin.m_pfnQERPlug_GetCommandList = &UFOAI::getCommandList; + m_plugin.m_pfnQERPlug_GetCommandTitleList = &UFOAI::getCommandTitleList; + m_plugin.m_pfnQERPlug_Dispatch = &UFOAI::dispatch; +} +_QERPluginTable* getTable(){ + return &m_plugin; +} }; typedef SingletonModule SingletonUFOAIModule; @@ -190,34 +165,31 @@ SingletonUFOAIModule g_UFOAIModule; class UFOAIToolbarDependencies : public ModuleRef<_QERPluginTable> { public: - UFOAIToolbarDependencies() : ModuleRef<_QERPluginTable>("UFO:AI") - { - } +UFOAIToolbarDependencies() : ModuleRef<_QERPluginTable>( "UFO:AI" ){ +} }; class UFOAIToolbarModule : public TypeSystemRef { - _QERPlugToolbarTable m_table; +_QERPlugToolbarTable m_table; public: - typedef _QERPlugToolbarTable Type; - STRING_CONSTANT(Name, "UFO:AI"); +typedef _QERPlugToolbarTable Type; +STRING_CONSTANT( Name, "UFO:AI" ); - UFOAIToolbarModule() - { - if (!strcmp(GlobalRadiant().getGameDescriptionKeyValue("name"), "UFO:Alien Invasion")) { - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; - } - else - { - m_table.m_pfnToolbarButtonCount = ToolbarNoButtons; - m_table.m_pfnGetToolbarButton = GetToolbarNoButton; - } - } - _QERPlugToolbarTable* getTable() +UFOAIToolbarModule(){ + if ( !strcmp( GlobalRadiant().getGameDescriptionKeyValue( "name" ), "UFO:Alien Invasion" ) ) { + m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; + m_table.m_pfnGetToolbarButton = GetToolbarButton; + } + else { - return &m_table; + m_table.m_pfnToolbarButtonCount = ToolbarNoButtons; + m_table.m_pfnGetToolbarButton = GetToolbarNoButton; } +} +_QERPlugToolbarTable* getTable(){ + return &m_table; +} }; typedef SingletonModule SingletonUFOAIToolbarModule; @@ -225,9 +197,8 @@ typedef SingletonModule SingletonU SingletonUFOAIToolbarModule g_UFOAIToolbarModule; -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules( ModuleServer& server ){ + initialiseModule( server ); g_UFOAIModule.selfRegister(); g_UFOAIToolbarModule.selfRegister(); diff --git a/contrib/ufoaiplug/ufoai.h b/contrib/ufoaiplug/ufoai.h index 7193fa0c..38ad4ccf 100644 --- a/contrib/ufoaiplug/ufoai.h +++ b/contrib/ufoaiplug/ufoai.h @@ -1,22 +1,22 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_UFOAI_H) +#if !defined( INCLUDED_UFOAI_H ) #define INCLUDED_UFOAI_H #endif diff --git a/contrib/ufoaiplug/ufoai_filters.cpp b/contrib/ufoaiplug/ufoai_filters.cpp index 869c4eb8..84a96652 100644 --- a/contrib/ufoaiplug/ufoai_filters.cpp +++ b/contrib/ufoaiplug/ufoai_filters.cpp @@ -1,20 +1,20 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ufoai_filters.h" @@ -38,158 +38,143 @@ int level_active = 0; // TODO: This should be added to ibrush.h // like already done for Node_getEntity in ientity.h // FIXME: Doesn't belong here -inline Brush* Node_getBrush(scene::Node& node) -{ - return NodeTypeCast::cast(node); +inline Brush* Node_getBrush( scene::Node& node ){ + return NodeTypeCast::cast( node ); } -void hide_node(scene::Node& node, bool hide) -{ +void hide_node( scene::Node& node, bool hide ){ hide - ? node.enable(scene::Node::eHidden) - : node.disable(scene::Node::eHidden); + ? node.enable( scene::Node::eHidden ) + : node.disable( scene::Node::eHidden ); } typedef std::list entitylist_t; class EntityFindByName : public scene::Graph::Walker { - const char* m_name; - entitylist_t& m_entitylist; - /* this starts at 1 << level */ - int m_flag; - int m_hide; +const char* m_name; +entitylist_t& m_entitylist; +/* this starts at 1 << level */ +int m_flag; +int m_hide; public: - EntityFindByName(const char* name, entitylist_t& entitylist, int flag, bool hide) - : m_name(name), m_entitylist(entitylist), m_flag(flag), m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - int spawnflagsInt; - Entity* entity = Node_getEntity(path.top()); - if (entity != 0) - { - if (string_equal(m_name, entity->getKeyValue("classname"))) - { - const char *spawnflags = entity->getKeyValue("spawnflags"); - globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n"; - - if (!string_empty(spawnflags)) { - spawnflagsInt = atoi(spawnflags); - if (!(spawnflagsInt & m_flag)) - { - hide_node(path.top(), m_hide); // hide/unhide - m_entitylist.push_back(entity); - } - } - else - { - globalOutputStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n"; +EntityFindByName( const char* name, entitylist_t& entitylist, int flag, bool hide ) + : m_name( name ), m_entitylist( entitylist ), m_flag( flag ), m_hide( hide ){ +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + int spawnflagsInt; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 ) { + if ( string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + const char *spawnflags = entity->getKeyValue( "spawnflags" ); + globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n"; + + if ( !string_empty( spawnflags ) ) { + spawnflagsInt = atoi( spawnflags ); + if ( !( spawnflagsInt & m_flag ) ) { + hide_node( path.top(), m_hide ); // hide/unhide + m_entitylist.push_back( entity ); } } + else + { + globalOutputStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n"; + } } - return true; } + return true; +} }; class ForEachFace : public BrushVisitor { - Brush &m_brush; +Brush &m_brush; public: - mutable int m_contentFlagsVis; - mutable int m_surfaceFlagsVis; +mutable int m_contentFlagsVis; +mutable int m_surfaceFlagsVis; - ForEachFace(Brush& brush) - : m_brush(brush) - { - m_contentFlagsVis = -1; - m_surfaceFlagsVis = -1; - } +ForEachFace( Brush& brush ) + : m_brush( brush ){ + m_contentFlagsVis = -1; + m_surfaceFlagsVis = -1; +} - void visit(Face& face) const - { +void visit( Face& face ) const { #if _DEBUG - if (m_surfaceFlagsVis < 0) - m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; - else if (m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags) - globalOutputStream() << "Faces with different surfaceflags at brush\n"; - if (m_contentFlagsVis < 0) - m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; - else if (m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags) - globalOutputStream() << "Faces with different contentflags at brush\n"; -#else + if ( m_surfaceFlagsVis < 0 ) { m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; + } + else if ( m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags ) { + globalOutputStream() << "Faces with different surfaceflags at brush\n"; + } + if ( m_contentFlagsVis < 0 ) { m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; -#endif } + else if ( m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags ) { + globalOutputStream() << "Faces with different contentflags at brush\n"; + } +#else + m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; + m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; +#endif +} }; typedef std::list brushlist_t; class BrushGetLevel : public scene::Graph::Walker { - brushlist_t& m_brushlist; - int m_flag; - bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags - mutable bool m_notset; - mutable bool m_hide; +brushlist_t& m_brushlist; +int m_flag; +bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags +mutable bool m_notset; +mutable bool m_hide; public: - BrushGetLevel(brushlist_t& brushlist, int flag, bool content, bool notset, bool hide) - : m_brushlist(brushlist), m_flag(flag), m_content(content), m_notset(notset), m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Brush* brush = Node_getBrush(path.top()); - if (brush != 0) - { - ForEachFace faces(*brush); - brush->forEachFace(faces); - // contentflags? - if (m_content) - { - // are any flags set? - if (faces.m_contentFlagsVis > 0) - { - // flag should not be set - if (m_notset && (!(faces.m_contentFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - // check whether flag is set - else if (!m_notset && ((faces.m_contentFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } +BrushGetLevel( brushlist_t& brushlist, int flag, bool content, bool notset, bool hide ) + : m_brushlist( brushlist ), m_flag( flag ), m_content( content ), m_notset( notset ), m_hide( hide ){ +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + Brush* brush = Node_getBrush( path.top() ); + if ( brush != 0 ) { + ForEachFace faces( *brush ); + brush->forEachFace( faces ); + // contentflags? + if ( m_content ) { + // are any flags set? + if ( faces.m_contentFlagsVis > 0 ) { + // flag should not be set + if ( m_notset && ( !( faces.m_contentFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + // check whether flag is set + else if ( !m_notset && ( ( faces.m_contentFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); } } - // surfaceflags? - else - { - // are any flags set? - if (faces.m_surfaceFlagsVis > 0) - { - // flag should not be set - if (m_notset && (!(faces.m_surfaceFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - // check whether flag is set - else if (!m_notset && ((faces.m_surfaceFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } + } + // surfaceflags? + else + { + // are any flags set? + if ( faces.m_surfaceFlagsVis > 0 ) { + // flag should not be set + if ( m_notset && ( !( faces.m_surfaceFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); + } + // check whether flag is set + else if ( !m_notset && ( ( faces.m_surfaceFlagsVis & m_flag ) ) ) { + hide_node( path.top(), m_hide ); + m_brushlist.push_back( brush ); } } - } - return true; + } + return true; +} }; /** @@ -197,25 +182,22 @@ public: * @param[in] level Which level to show? * @todo Entities */ -void filter_level(int flag) -{ +void filter_level( int flag ){ int level; brushlist_t brushes; entitylist_t entities; - level = (flag >> 8); - - if (level_active) - { - GlobalSceneGraph().traverse(BrushGetLevel(brushes, (level_active << 8), true, true, false)); - GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level_active, false)); - entities.erase(entities.begin(), entities.end()); - brushes.erase(brushes.begin(), brushes.end()); - if (level_active == level) - { + level = ( flag >> 8 ); + + if ( level_active ) { + GlobalSceneGraph().traverse( BrushGetLevel( brushes, ( level_active << 8 ), true, true, false ) ); + GlobalSceneGraph().traverse( EntityFindByName( "func_door", entities, level_active, false ) ); + GlobalSceneGraph().traverse( EntityFindByName( "func_breakable", entities, level_active, false ) ); + GlobalSceneGraph().traverse( EntityFindByName( "misc_model", entities, level_active, false ) ); + GlobalSceneGraph().traverse( EntityFindByName( "misc_particle", entities, level_active, false ) ); + entities.erase( entities.begin(), entities.end() ); + brushes.erase( brushes.begin(), brushes.end() ); + if ( level_active == level ) { level_active = 0; // just disabĺe level filter return; @@ -225,118 +207,112 @@ void filter_level(int flag) globalOutputStream() << "UFO:AI: level_active: " << level_active << ", flag: " << flag << ".\n"; // first all brushes - GlobalSceneGraph().traverse(BrushGetLevel(brushes, flag, true, true, true)); + GlobalSceneGraph().traverse( BrushGetLevel( brushes, flag, true, true, true ) ); // now all entities - GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level, true)); + GlobalSceneGraph().traverse( EntityFindByName( "func_door", entities, level, true ) ); + GlobalSceneGraph().traverse( EntityFindByName( "func_breakable", entities, level, true ) ); + GlobalSceneGraph().traverse( EntityFindByName( "misc_model", entities, level, true ) ); + GlobalSceneGraph().traverse( EntityFindByName( "misc_particle", entities, level, true ) ); #ifdef _DEBUG - if (brushes.empty()) - { + if ( brushes.empty() ) { globalOutputStream() << "UFO:AI: No brushes.\n"; } else { - globalOutputStream() << "UFO:AI: Found " << Unsigned(brushes.size()) << " brushes.\n"; + globalOutputStream() << "UFO:AI: Found " << Unsigned( brushes.size() ) << " brushes.\n"; } // now let's filter all entities like misc_model, func_breakable and func_door that have the spawnflags set - if (entities.empty()) - { + if ( entities.empty() ) { globalOutputStream() << "UFO:AI: No entities.\n"; } else { - globalOutputStream() << "UFO:AI: Found " << Unsigned(entities.size()) << " entities.\n"; + globalOutputStream() << "UFO:AI: Found " << Unsigned( entities.size() ) << " entities.\n"; } #endif } -void filter_stepon (void) -{ - if (stepon_active) { +void filter_stepon( void ){ + if ( stepon_active ) { stepon_active = false; - } else { + } + else { stepon_active = true; } brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_STEPON, true, false, stepon_active)); + GlobalSceneGraph().traverse( BrushGetLevel( brushes, CONTENTS_STEPON, true, false, stepon_active ) ); - if (brushes.empty()) - { + if ( brushes.empty() ) { globalOutputStream() << "UFO:AI: No brushes.\n"; } else { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " stepon brushes.\n"; + globalOutputStream() << "UFO:AI: Hiding " << Unsigned( brushes.size() ) << " stepon brushes.\n"; } } -void filter_nodraw (void) -{ - if (nodraw_active) { +void filter_nodraw( void ){ + if ( nodraw_active ) { nodraw_active = false; - } else { + } + else { nodraw_active = true; } brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, SURF_NODRAW, false, false, nodraw_active)); + GlobalSceneGraph().traverse( BrushGetLevel( brushes, SURF_NODRAW, false, false, nodraw_active ) ); #ifdef _DEBUG - if (brushes.empty()) - { + if ( brushes.empty() ) { globalOutputStream() << "UFO:AI: No brushes.\n"; } else { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " nodraw brushes.\n"; + globalOutputStream() << "UFO:AI: Hiding " << Unsigned( brushes.size() ) << " nodraw brushes.\n"; } #endif } -void filter_actorclip (void) -{ - if (actorclip_active) { +void filter_actorclip( void ){ + if ( actorclip_active ) { actorclip_active = false; - } else { + } + else { actorclip_active = true; } brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_ACTORCLIP, true, false, actorclip_active)); + GlobalSceneGraph().traverse( BrushGetLevel( brushes, CONTENTS_ACTORCLIP, true, false, actorclip_active ) ); #ifdef _DEBUG - if (brushes.empty()) - { + if ( brushes.empty() ) { globalOutputStream() << "UFO:AI: No brushes.\n"; } else { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " actorclip brushes.\n"; + globalOutputStream() << "UFO:AI: Hiding " << Unsigned( brushes.size() ) << " actorclip brushes.\n"; } #endif } -void filter_weaponclip (void) -{ - if (weaponclip_active) { +void filter_weaponclip( void ){ + if ( weaponclip_active ) { weaponclip_active = false; - } else { + } + else { weaponclip_active = true; } brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_WEAPONCLIP, true, false, weaponclip_active)); + GlobalSceneGraph().traverse( BrushGetLevel( brushes, CONTENTS_WEAPONCLIP, true, false, weaponclip_active ) ); #ifdef _DEBUG - if (brushes.empty()) - { + if ( brushes.empty() ) { globalOutputStream() << "UFO:AI: No brushes.\n"; } else { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " weaponclip brushes.\n"; + globalOutputStream() << "UFO:AI: Hiding " << Unsigned( brushes.size() ) << " weaponclip brushes.\n"; } #endif } diff --git a/contrib/ufoaiplug/ufoai_filters.h b/contrib/ufoaiplug/ufoai_filters.h index 7d581140..840c45bc 100644 --- a/contrib/ufoaiplug/ufoai_filters.h +++ b/contrib/ufoaiplug/ufoai_filters.h @@ -1,29 +1,29 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_FILTERS_H) +#if !defined( INCLUDED_FILTERS_H ) #define INCLUDED_FILTERS_H -void filter_level(int flag); -void filter_stepon(void); -void filter_actorclip(void); -void filter_weaponclip(void); -void filter_nodraw(void); +void filter_level( int flag ); +void filter_stepon( void ); +void filter_actorclip( void ); +void filter_weaponclip( void ); +void filter_nodraw( void ); #define SURF_NODRAW 0x80 diff --git a/contrib/ufoaiplug/ufoai_gtk.cpp b/contrib/ufoaiplug/ufoai_gtk.cpp index afadc7ad..c01a31fe 100644 --- a/contrib/ufoaiplug/ufoai_gtk.cpp +++ b/contrib/ufoaiplug/ufoai_gtk.cpp @@ -1,20 +1,20 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ufoai_gtk.h" #include "ufoai_filters.h" @@ -30,11 +30,10 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class UFOAIGtk { - GtkWindow* m_gtk_window; +GtkWindow* m_gtk_window; public: - UFOAIGtk(void* gtk_window) : m_gtk_window((GtkWindow*)gtk_window) - { - } +UFOAIGtk( void* gtk_window ) : m_gtk_window( ( GtkWindow* )gtk_window ){ +} }; /** @@ -44,25 +43,22 @@ public: * This is useful for popping up 'are you sure you want to quit?' * type dialogs. */ -static gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) -{ +static gboolean delete_event( GtkWidget *widget, GdkEvent *event, gpointer data ){ return FALSE; } /** * @brief destroy widget if destroy signal is passed to widget */ -static void destroy(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(widget); +static void destroy( GtkWidget *widget, gpointer data ){ + gtk_widget_destroy( widget ); } /** * @brief function for close button to destroy the toplevel widget */ -static void close_window(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(gtk_widget_get_toplevel(widget)); +static void close_window( GtkWidget *widget, gpointer data ){ + gtk_widget_destroy( gtk_widget_get_toplevel( widget ) ); } /* =============================== */ @@ -72,16 +68,14 @@ static void close_window(GtkWidget *widget, gpointer data) /** * @brief */ -std::size_t ToolbarButtonCount(void) -{ +std::size_t ToolbarButtonCount( void ){ return NUM_TOOLBARBUTTONS; } /** * @brief Used if the ufo plugin should not be visible (at least the toolbar stuff) */ -std::size_t ToolbarNoButtons (void) -{ +std::size_t ToolbarNoButtons( void ){ return 0; } @@ -91,97 +85,92 @@ std::size_t ToolbarNoButtons (void) class CUFOAIToolbarButton : public IToolbarButton { public: - virtual const char* getImage() const +virtual const char* getImage() const { + switch ( mIndex ) { - switch( mIndex ) - { - case 0: return "ufoai_level1.bmp"; - case 1: return "ufoai_level2.bmp"; - case 2: return "ufoai_level3.bmp"; - case 3: return "ufoai_level4.bmp"; - case 4: return "ufoai_level5.bmp"; - case 5: return "ufoai_level6.bmp"; - case 6: return "ufoai_level7.bmp"; - case 7: return "ufoai_level8.bmp"; - case 8: return "ufoai_stepon.bmp"; - case 9: return "ufoai_actorclip.bmp"; - case 10: return "ufoai_weaponclip.bmp"; - case 11: return "ufoai_nodraw.bmp"; - } - return NULL; + case 0: return "ufoai_level1.bmp"; + case 1: return "ufoai_level2.bmp"; + case 2: return "ufoai_level3.bmp"; + case 3: return "ufoai_level4.bmp"; + case 4: return "ufoai_level5.bmp"; + case 5: return "ufoai_level6.bmp"; + case 6: return "ufoai_level7.bmp"; + case 7: return "ufoai_level8.bmp"; + case 8: return "ufoai_stepon.bmp"; + case 9: return "ufoai_actorclip.bmp"; + case 10: return "ufoai_weaponclip.bmp"; + case 11: return "ufoai_nodraw.bmp"; } - virtual EType getType() const + return NULL; +} +virtual EType getType() const { + switch ( mIndex ) { - switch( mIndex ) - { /* case 3: return eButton;*/ - case 8: return eToggleButton; - case 9: return eToggleButton; - case 10: return eToggleButton; - case 11: return eToggleButton; - default: return eButton; - } + case 8: return eToggleButton; + case 9: return eToggleButton; + case 10: return eToggleButton; + case 11: return eToggleButton; + default: return eButton; } - virtual const char* getText() const +} +virtual const char* getText() const { + switch ( mIndex ) { - switch( mIndex ) - { - case 0: return "Level 1"; - case 1: return "Level 2"; - case 2: return "Level 3"; - case 3: return "Level 4"; - case 4: return "Level 5"; - case 5: return "Level 6"; - case 6: return "Level 7"; - case 7: return "Level 8"; - case 8: return "Stepon"; - case 9: return "Actorclip"; - case 10: return "Weaponclip"; - case 11: return "Nodraw"; - } - return NULL; + case 0: return "Level 1"; + case 1: return "Level 2"; + case 2: return "Level 3"; + case 3: return "Level 4"; + case 4: return "Level 5"; + case 5: return "Level 6"; + case 6: return "Level 7"; + case 7: return "Level 8"; + case 8: return "Stepon"; + case 9: return "Actorclip"; + case 10: return "Weaponclip"; + case 11: return "Nodraw"; } - virtual const char* getTooltip() const + return NULL; +} +virtual const char* getTooltip() const { + switch ( mIndex ) { - switch( mIndex ) - { - case 0: return "Show only level 1"; - case 1: return "Show only level 2"; - case 2: return "Show only level 3"; - case 3: return "Show only level 4"; - case 4: return "Show only level 5"; - case 5: return "Show only level 6"; - case 6: return "Show only level 7"; - case 7: return "Show only level 8"; - case 8: return "Hide stepon brushes"; - case 9: return "Hide actorclip brushes"; - case 10: return "Hide weaponclip brushes"; - case 11: return "Hide nodraw brushes"; - } - return NULL; + case 0: return "Show only level 1"; + case 1: return "Show only level 2"; + case 2: return "Show only level 3"; + case 3: return "Show only level 4"; + case 4: return "Show only level 5"; + case 5: return "Show only level 6"; + case 6: return "Show only level 7"; + case 7: return "Show only level 8"; + case 8: return "Hide stepon brushes"; + case 9: return "Hide actorclip brushes"; + case 10: return "Hide weaponclip brushes"; + case 11: return "Hide nodraw brushes"; } + return NULL; +} - virtual void activate() const +virtual void activate() const { + switch ( mIndex ) { - switch( mIndex ) - { - case 0: filter_level(CONTENTS_LEVEL1); break; - case 1: filter_level(CONTENTS_LEVEL2); break; - case 2: filter_level(CONTENTS_LEVEL3); break; - case 3: filter_level(CONTENTS_LEVEL4); break; - case 4: filter_level(CONTENTS_LEVEL5); break; - case 5: filter_level(CONTENTS_LEVEL6); break; - case 6: filter_level(CONTENTS_LEVEL7); break; - case 7: filter_level(CONTENTS_LEVEL8); break; - case 8: filter_stepon(); break; - case 9: filter_actorclip(); break; - case 10: filter_weaponclip(); break; - case 11: filter_nodraw(); break; - } - SceneChangeNotify(); + case 0: filter_level( CONTENTS_LEVEL1 ); break; + case 1: filter_level( CONTENTS_LEVEL2 ); break; + case 2: filter_level( CONTENTS_LEVEL3 ); break; + case 3: filter_level( CONTENTS_LEVEL4 ); break; + case 4: filter_level( CONTENTS_LEVEL5 ); break; + case 5: filter_level( CONTENTS_LEVEL6 ); break; + case 6: filter_level( CONTENTS_LEVEL7 ); break; + case 7: filter_level( CONTENTS_LEVEL8 ); break; + case 8: filter_stepon(); break; + case 9: filter_actorclip(); break; + case 10: filter_weaponclip(); break; + case 11: filter_nodraw(); break; } + SceneChangeNotify(); +} - std::size_t mIndex; +std::size_t mIndex; }; /** @@ -192,8 +181,7 @@ CUFOAIToolbarButton g_ufoaiToolbarButtons[NUM_TOOLBARBUTTONS]; /** * @brief */ -const IToolbarButton* GetToolbarButton(std::size_t index) -{ +const IToolbarButton* GetToolbarButton( std::size_t index ){ g_ufoaiToolbarButtons[index].mIndex = index; return &g_ufoaiToolbarButtons[index]; } @@ -201,7 +189,6 @@ const IToolbarButton* GetToolbarButton(std::size_t index) /** * @brief */ -const IToolbarButton* GetToolbarNoButton(std::size_t index) -{ +const IToolbarButton* GetToolbarNoButton( std::size_t index ){ return NULL; } diff --git a/contrib/ufoaiplug/ufoai_gtk.h b/contrib/ufoaiplug/ufoai_gtk.h index ef2ae3c3..0254f7d6 100644 --- a/contrib/ufoaiplug/ufoai_gtk.h +++ b/contrib/ufoaiplug/ufoai_gtk.h @@ -1,30 +1,30 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_UFOAI_GTK_H) +#if !defined( INCLUDED_UFOAI_GTK_H ) #define INCLUDED_UFOAI_GTK_H #include "itoolbar.h" #include -const IToolbarButton* GetToolbarButton(std::size_t index); -const IToolbarButton* GetToolbarNoButton(std::size_t index); -std::size_t ToolbarButtonCount(void); -std::size_t ToolbarNoButtons(void); +const IToolbarButton* GetToolbarButton( std::size_t index ); +const IToolbarButton* GetToolbarNoButton( std::size_t index ); +std::size_t ToolbarButtonCount( void ); +std::size_t ToolbarNoButtons( void ); #endif diff --git a/contrib/ufoaiplug/ufoai_level.cpp b/contrib/ufoaiplug/ufoai_level.cpp index 3a36b258..c7554e4d 100644 --- a/contrib/ufoaiplug/ufoai_level.cpp +++ b/contrib/ufoaiplug/ufoai_level.cpp @@ -1,20 +1,20 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ufoai_level.h" #include "ufoai_filters.h" @@ -34,34 +34,29 @@ class Level; */ class EntityFindByClassname : public scene::Graph::Walker { - const char* m_name; - Entity*& m_entity; +const char* m_name; +Entity*& m_entity; public: - EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) - { - m_entity = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(m_entity == 0) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_name, entity->getKeyValue("classname"))) - { - m_entity = entity; - } +EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){ + m_entity = 0; +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + if ( m_entity == 0 ) { + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_name, entity->getKeyValue( "classname" ) ) ) { + m_entity = entity; } - return true; } + return true; +} }; /** * @brief */ -Entity* Scene_FindEntityByClass(const char* name) -{ +Entity* Scene_FindEntityByClass( const char* name ){ Entity* entity = NULL; - GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); + GlobalSceneGraph().traverse( EntityFindByClassname( name, entity ) ); return entity; } @@ -70,28 +65,24 @@ Entity* Scene_FindEntityByClass(const char* name) */ class EntityFindFlags : public scene::Graph::Walker { - const char *m_classname; - const char *m_flag; - int *m_count; +const char *m_classname; +const char *m_flag; +int *m_count; - public: - EntityFindFlags(const char *classname, const char *flag, int *count) : m_classname(classname), m_flag(flag), m_count(count) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - const char *str; - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_classname, entity->getKeyValue("classname"))) - { - str = entity->getKeyValue(m_flag); - if (string_empty(str)) - { - (*m_count)++; - } - } - return true; +public: +EntityFindFlags( const char *classname, const char *flag, int *count ) : m_classname( classname ), m_flag( flag ), m_count( count ){ +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + const char *str; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { + str = entity->getKeyValue( m_flag ); + if ( string_empty( str ) ) { + ( *m_count )++; } + } + return true; +} }; @@ -100,60 +91,54 @@ class EntityFindFlags : public scene::Graph::Walker */ class EntityFindTeams : public scene::Graph::Walker { - const char *m_classname; - int *m_count; - int *m_team; +const char *m_classname; +int *m_count; +int *m_team; public: - EntityFindTeams(const char *classname, int *count, int *team) : m_classname(classname), m_count(count), m_team(team) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - const char *str; - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_classname, entity->getKeyValue("classname"))) - { - if (m_count) - (*m_count)++; - // now get the highest teamnum - if (m_team) - { - str = entity->getKeyValue("team"); - if (!string_empty(str)) - { - if (atoi(str) > *m_team) - (*m_team) = atoi(str); +EntityFindTeams( const char *classname, int *count, int *team ) : m_classname( classname ), m_count( count ), m_team( team ){ +} +bool pre( const scene::Path& path, scene::Instance& instance ) const { + const char *str; + Entity* entity = Node_getEntity( path.top() ); + if ( entity != 0 && string_equal( m_classname, entity->getKeyValue( "classname" ) ) ) { + if ( m_count ) { + ( *m_count )++; + } + // now get the highest teamnum + if ( m_team ) { + str = entity->getKeyValue( "team" ); + if ( !string_empty( str ) ) { + if ( atoi( str ) > *m_team ) { + ( *m_team ) = atoi( str ); } } } - return true; } + return true; +} }; /** * @brief */ -void get_team_count (const char *classname, int *count, int *team) -{ - GlobalSceneGraph().traverse(EntityFindTeams(classname, count, team)); - globalOutputStream() << "UFO:AI: classname: " << classname << ": #" << (*count) << "\n"; +void get_team_count( const char *classname, int *count, int *team ){ + GlobalSceneGraph().traverse( EntityFindTeams( classname, count, team ) ); + globalOutputStream() << "UFO:AI: classname: " << classname << ": #" << ( *count ) << "\n"; } /** * @brief Some default values to worldspawn like maxlevel and so on */ -void assign_default_values_to_worldspawn (bool override, char **returnMsg) -{ +void assign_default_values_to_worldspawn( bool override, char **returnMsg ){ static char message[1024]; Entity* worldspawn; int teams = 0; int count = 0; char str[64]; - worldspawn = Scene_FindEntityByClass("worldspawn"); - if (!worldspawn) - { + worldspawn = Scene_FindEntityByClass( "worldspawn" ); + if ( !worldspawn ) { globalOutputStream() << "UFO:AI: Could not find worldspawn.\n"; *returnMsg = "Could not find worldspawn"; return; @@ -162,31 +147,28 @@ void assign_default_values_to_worldspawn (bool override, char **returnMsg) *message = '\0'; *str = '\0'; - if (override || string_empty(worldspawn->getKeyValue("maxlevel"))) - { + if ( override || string_empty( worldspawn->getKeyValue( "maxlevel" ) ) ) { // TODO: Get highest brush - a level has 64 units - worldspawn->setKeyValue("maxlevel", "5"); - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Set maxlevel to: %s", worldspawn->getKeyValue("maxlevel")); + worldspawn->setKeyValue( "maxlevel", "5" ); + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Set maxlevel to: %s", worldspawn->getKeyValue( "maxlevel" ) ); } - if (override || string_empty(worldspawn->getKeyValue("maxteams"))) - { - get_team_count("info_player_start", &count, &teams); - if (teams) - { - snprintf(str, sizeof(str) - 1, "%i", teams); - worldspawn->setKeyValue("maxteams", str); - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Set maxteams to: %s", worldspawn->getKeyValue("maxteams")); + if ( override || string_empty( worldspawn->getKeyValue( "maxteams" ) ) ) { + get_team_count( "info_player_start", &count, &teams ); + if ( teams ) { + snprintf( str, sizeof( str ) - 1, "%i", teams ); + worldspawn->setKeyValue( "maxteams", str ); + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Set maxteams to: %s", worldspawn->getKeyValue( "maxteams" ) ); } - if (count < 16) - { - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "You should at least place 16 info_player_start"); + if ( count < 16 ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "You should at least place 16 info_player_start" ); } } // no errors - no warnings - if (!strlen(message)) + if ( !strlen( message ) ) { return; + } *returnMsg = message; } @@ -194,14 +176,13 @@ void assign_default_values_to_worldspawn (bool override, char **returnMsg) /** * @brief */ -int check_entity_flags (const char *classname, const char *flag) -{ +int check_entity_flags( const char *classname, const char *flag ){ int count; /* init this with 0 every time we browse the tree */ count = 0; - GlobalSceneGraph().traverse(EntityFindFlags(classname, flag, &count)); + GlobalSceneGraph().traverse( EntityFindFlags( classname, flag, &count ) ); return count; } @@ -209,8 +190,7 @@ int check_entity_flags (const char *classname, const char *flag) * @brief Will check e.g. the map entities for valid values * @todo: check for maxlevel */ -void check_map_values (char **returnMsg) -{ +void check_map_values( char **returnMsg ){ static char message[1024]; int count = 0; int teams = 0; @@ -218,9 +198,8 @@ void check_map_values (char **returnMsg) Entity* worldspawn; char str[64]; - worldspawn = Scene_FindEntityByClass("worldspawn"); - if (!worldspawn) - { + worldspawn = Scene_FindEntityByClass( "worldspawn" ); + if ( !worldspawn ) { globalOutputStream() << "UFO:AI: Could not find worldspawn.\n"; *returnMsg = "Could not find worldspawn"; return; @@ -230,63 +209,74 @@ void check_map_values (char **returnMsg) *str = '\0'; // multiplayer start positions - get_team_count("info_player_start", &count, &teams); - if (!count) - strncat(message, "No multiplayer start positions (info_player_start)\n", sizeof(message) - 1); + get_team_count( "info_player_start", &count, &teams ); + if ( !count ) { + strncat( message, "No multiplayer start positions (info_player_start)\n", sizeof( message ) - 1 ); + } // singleplayer map? count = 0; - get_team_count("info_human_start", &count, NULL); - if (!count) - strncat(message, "No singleplayer start positions (info_human_start)\n", sizeof(message) - 1); + get_team_count( "info_human_start", &count, NULL ); + if ( !count ) { + strncat( message, "No singleplayer start positions (info_human_start)\n", sizeof( message ) - 1 ); + } // singleplayer map? count = 0; - get_team_count("info_2x2_start", &count, NULL); - if (!count) - strncat(message, "No singleplayer start positions for 2x2 units (info_2x2_start)\n", sizeof(message) - 1); + get_team_count( "info_2x2_start", &count, NULL ); + if ( !count ) { + strncat( message, "No singleplayer start positions for 2x2 units (info_2x2_start)\n", sizeof( message ) - 1 ); + } // search for civilians count = 0; - get_team_count("info_civilian_start", &count, NULL); - if (!count) - strncat(message, "No civilian start positions (info_civilian_start)\n", sizeof(message) - 1); + get_team_count( "info_civilian_start", &count, NULL ); + if ( !count ) { + strncat( message, "No civilian start positions (info_civilian_start)\n", sizeof( message ) - 1 ); + } // check maxlevel - if (string_empty(worldspawn->getKeyValue("maxlevel"))) - strncat(message, "Worldspawn: No maxlevel defined\n", sizeof(message) - 1); - else if (atoi(worldspawn->getKeyValue("maxlevel")) > 8) - { - strncat(message, "Worldspawn: Highest maxlevel is 8\n", sizeof(message) - 1); - worldspawn->setKeyValue("maxlevel", "8"); + if ( string_empty( worldspawn->getKeyValue( "maxlevel" ) ) ) { + strncat( message, "Worldspawn: No maxlevel defined\n", sizeof( message ) - 1 ); + } + else if ( atoi( worldspawn->getKeyValue( "maxlevel" ) ) > 8 ) { + strncat( message, "Worldspawn: Highest maxlevel is 8\n", sizeof( message ) - 1 ); + worldspawn->setKeyValue( "maxlevel", "8" ); } - ent_flags = check_entity_flags("func_door", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i func_door with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("func_breakable", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i func_breakable with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_sound", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_sound with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_model", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_model with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_particle", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_particle with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("info_player_start", "team"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i info_player_start with no team assigned\n!!Teamcount may change after you've fixed this\n", ent_flags); - ent_flags = check_entity_flags("light", "color"); - ent_flags = check_entity_flags("light", "_color"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i lights with no color value\n", ent_flags); + ent_flags = check_entity_flags( "func_door", "spawnflags" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i func_door with no spawnflags\n", ent_flags ); + } + ent_flags = check_entity_flags( "func_breakable", "spawnflags" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i func_breakable with no spawnflags\n", ent_flags ); + } + ent_flags = check_entity_flags( "misc_sound", "spawnflags" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i misc_sound with no spawnflags\n", ent_flags ); + } + ent_flags = check_entity_flags( "misc_model", "spawnflags" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i misc_model with no spawnflags\n", ent_flags ); + } + ent_flags = check_entity_flags( "misc_particle", "spawnflags" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i misc_particle with no spawnflags\n", ent_flags ); + } + ent_flags = check_entity_flags( "info_player_start", "team" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i info_player_start with no team assigned\n!!Teamcount may change after you've fixed this\n", ent_flags ); + } + ent_flags = check_entity_flags( "light", "color" ); + ent_flags = check_entity_flags( "light", "_color" ); + if ( ent_flags ) { + snprintf( &message[strlen( message )], sizeof( message ) - 1 - strlen( message ), "Found %i lights with no color value\n", ent_flags ); + } // no errors found - if (!strlen(message)) { - snprintf(message, sizeof(message) - 1, "No errors found - you are ready to compile the map now\n"); + if ( !strlen( message ) ) { + snprintf( message, sizeof( message ) - 1, "No errors found - you are ready to compile the map now\n" ); } *returnMsg = message; diff --git a/contrib/ufoaiplug/ufoai_level.h b/contrib/ufoaiplug/ufoai_level.h index ba75bd45..e9d5e176 100644 --- a/contrib/ufoaiplug/ufoai_level.h +++ b/contrib/ufoaiplug/ufoai_level.h @@ -1,26 +1,26 @@ /* -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_UFOAI_LEVEL_H) +#if !defined( INCLUDED_UFOAI_LEVEL_H ) #define INCLUDED_UFOAI_LEVEL_H -void assign_default_values_to_worldspawn (bool override, char **returnMsg); -void check_map_values (char **returnMsg); -void get_team_count (const char *classname, int *count, int *team); +void assign_default_values_to_worldspawn( bool override, char **returnMsg ); +void check_map_values( char **returnMsg ); +void get_team_count( const char *classname, int *count, int *team ); #endif diff --git a/include/cullable.cpp b/include/cullable.cpp index 352ea5d6..395d3e1c 100644 --- a/include/cullable.cpp +++ b/include/cullable.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "cullable.h" - diff --git a/include/cullable.h b/include/cullable.h index 8e3c71bc..299af2e2 100644 --- a/include/cullable.h +++ b/include/cullable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CULLABLE_H) +#if !defined( INCLUDED_CULLABLE_H ) #define INCLUDED_CULLABLE_H #include "generic/constant.h" @@ -39,32 +39,32 @@ class VolumeTest { public: - /// \brief Returns true if \p point intersects volume. - virtual bool TestPoint(const Vector3& point) const = 0; - /// \brief Returns true if \p segment intersects volume. - virtual bool TestLine(const Segment& segment) const = 0; - /// \brief Returns true if \p plane faces towards volume. - virtual bool TestPlane(const Plane3& plane) const = 0; - /// \brief Returns true if \p plane transformed by \p localToWorld faces the viewer. - virtual bool TestPlane(const Plane3& plane, const Matrix4& localToWorld) const = 0; - /// \brief Returns the intersection of \p aabb and volume. - virtual VolumeIntersectionValue TestAABB(const AABB& aabb) const = 0; - /// \brief Returns the intersection of \p aabb transformed by \p localToWorld and volume. - virtual VolumeIntersectionValue TestAABB(const AABB& aabb, const Matrix4& localToWorld) const = 0; - - virtual bool fill() const = 0; - - virtual const Matrix4& GetViewport() const = 0; - virtual const Matrix4& GetProjection() const = 0; - virtual const Matrix4& GetModelview() const = 0; +/// \brief Returns true if \p point intersects volume. +virtual bool TestPoint( const Vector3& point ) const = 0; +/// \brief Returns true if \p segment intersects volume. +virtual bool TestLine( const Segment& segment ) const = 0; +/// \brief Returns true if \p plane faces towards volume. +virtual bool TestPlane( const Plane3& plane ) const = 0; +/// \brief Returns true if \p plane transformed by \p localToWorld faces the viewer. +virtual bool TestPlane( const Plane3& plane, const Matrix4& localToWorld ) const = 0; +/// \brief Returns the intersection of \p aabb and volume. +virtual VolumeIntersectionValue TestAABB( const AABB& aabb ) const = 0; +/// \brief Returns the intersection of \p aabb transformed by \p localToWorld and volume. +virtual VolumeIntersectionValue TestAABB( const AABB& aabb, const Matrix4& localToWorld ) const = 0; + +virtual bool fill() const = 0; + +virtual const Matrix4& GetViewport() const = 0; +virtual const Matrix4& GetProjection() const = 0; +virtual const Matrix4& GetModelview() const = 0; }; class Cullable { public: - STRING_CONSTANT(Name, "Cullable"); +STRING_CONSTANT( Name, "Cullable" ); - virtual VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const = 0; +virtual VolumeIntersectionValue intersectVolume( const VolumeTest& test, const Matrix4& localToWorld ) const = 0; }; diff --git a/include/editable.cpp b/include/editable.cpp index bcd04d8a..63314dc1 100644 --- a/include/editable.cpp +++ b/include/editable.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "editable.h" - diff --git a/include/editable.h b/include/editable.h index 9e9bac04..39e1174d 100644 --- a/include/editable.h +++ b/include/editable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_EDITABLE_H) +#if !defined( INCLUDED_EDITABLE_H ) #define INCLUDED_EDITABLE_H template class BasicVector3; @@ -34,27 +34,25 @@ typedef Vector4 Quaternion; class Editable { public: - STRING_CONSTANT(Name, "Editable"); +STRING_CONSTANT( Name, "Editable" ); - virtual const Matrix4& getLocalPivot() const = 0; +virtual const Matrix4& getLocalPivot() const = 0; }; -inline Editable* Node_getEditable(scene::Node& node) -{ - return NodeTypeCast::cast(node); +inline Editable* Node_getEditable( scene::Node& node ){ + return NodeTypeCast::cast( node ); } class Snappable { public: - STRING_CONSTANT(Name, "Snappable"); +STRING_CONSTANT( Name, "Snappable" ); - virtual void snapto(float snap) = 0; +virtual void snapto( float snap ) = 0; }; -inline Snappable* Node_getSnappable(scene::Node& node) -{ - return NodeTypeCast::cast(node); +inline Snappable* Node_getSnappable( scene::Node& node ){ + return NodeTypeCast::cast( node ); } #endif diff --git a/include/iarchive.cpp b/include/iarchive.cpp index b975bf05..1cf00055 100644 --- a/include/iarchive.cpp +++ b/include/iarchive.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iarchive.h" - diff --git a/include/iarchive.h b/include/iarchive.h index b3f21016..dddf5579 100644 --- a/include/iarchive.h +++ b/include/iarchive.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IARCHIVE_H) +#if !defined( INCLUDED_IARCHIVE_H ) #define INCLUDED_IARCHIVE_H #include @@ -31,17 +31,17 @@ class InputStream; class ArchiveFile { public: - /// \brief Destroys the file object. - virtual void release() = 0; - /// \brief Returns the size of the file data in bytes. - virtual std::size_t size() const = 0; - /// \brief Returns the path to this file (relative to the filesystem root) - virtual const char* getName() const = 0; - /// \brief Returns the stream associated with this file. - /// Subsequent calls return the same stream. - /// The stream may be read forwards until it is exhausted. - /// The stream remains valid for the lifetime of the file. - virtual InputStream& getInputStream() = 0; +/// \brief Destroys the file object. +virtual void release() = 0; +/// \brief Returns the size of the file data in bytes. +virtual std::size_t size() const = 0; +/// \brief Returns the path to this file (relative to the filesystem root) +virtual const char* getName() const = 0; +/// \brief Returns the stream associated with this file. +/// Subsequent calls return the same stream. +/// The stream may be read forwards until it is exhausted. +/// The stream remains valid for the lifetime of the file. +virtual InputStream& getInputStream() = 0; }; class TextInputStream; @@ -50,26 +50,24 @@ class TextInputStream; class ArchiveTextFile { public: - /// \brief Destroys the file object. - virtual void release() = 0; - /// \brief Returns the stream associated with this file. - /// Subsequent calls return the same stream. - /// The stream may be read forwards until it is exhausted. - /// The stream remains valid for the lifetime of the file. - virtual TextInputStream& getInputStream() = 0; +/// \brief Destroys the file object. +virtual void release() = 0; +/// \brief Returns the stream associated with this file. +/// Subsequent calls return the same stream. +/// The stream may be read forwards until it is exhausted. +/// The stream remains valid for the lifetime of the file. +virtual TextInputStream& getInputStream() = 0; }; class ScopedArchiveFile { - ArchiveFile& m_file; +ArchiveFile& m_file; public: - ScopedArchiveFile(ArchiveFile& file) : m_file(file) - { - } - ~ScopedArchiveFile() - { - m_file.release(); - } +ScopedArchiveFile( ArchiveFile& file ) : m_file( file ){ +} +~ScopedArchiveFile(){ + m_file.release(); +} }; class CustomArchiveVisitor; @@ -78,77 +76,77 @@ class Archive { public: - class Visitor - { - public: - virtual void visit(const char* name) = 0; - }; - - typedef CustomArchiveVisitor VisitorFunc; - - enum EMode - { - eFiles = 0x01, - eDirectories = 0x02, - eFilesAndDirectories = 0x03, - }; - - /// \brief Destroys the archive object. - /// Any unreleased file object associated with the archive remains valid. */ - virtual void release() = 0; - /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. - /// Name comparisons are case-insensitive. - virtual ArchiveFile* openFile(const char* name) = 0; - /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. - /// Name comparisons are case-insensitive. - virtual ArchiveTextFile* openTextFile(const char* name) = 0; - /// Returns true if the file identified by \p name can be opened. - /// Name comparisons are case-insensitive. - virtual bool containsFile(const char* name) = 0; - /// \brief Performs a depth-first traversal of the archive tree starting at \p root. - /// Traverses the entire tree if \p root is "". - /// When a file is encountered, calls \c visitor.file passing the file name. - /// When a directory is encountered, calls \c visitor.directory passing the directory name. - /// Skips the directory if \c visitor.directory returned true. - /// Root comparisons are case-insensitive. - /// Names are mixed-case. - virtual void forEachFile(VisitorFunc visitor, const char* root) = 0; +class Visitor +{ +public: +virtual void visit( const char* name ) = 0; +}; + +typedef CustomArchiveVisitor VisitorFunc; + +enum EMode +{ + eFiles = 0x01, + eDirectories = 0x02, + eFilesAndDirectories = 0x03, +}; + +/// \brief Destroys the archive object. +/// Any unreleased file object associated with the archive remains valid. */ +virtual void release() = 0; +/// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. +/// Name comparisons are case-insensitive. +virtual ArchiveFile* openFile( const char* name ) = 0; +/// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. +/// Name comparisons are case-insensitive. +virtual ArchiveTextFile* openTextFile( const char* name ) = 0; +/// Returns true if the file identified by \p name can be opened. +/// Name comparisons are case-insensitive. +virtual bool containsFile( const char* name ) = 0; +/// \brief Performs a depth-first traversal of the archive tree starting at \p root. +/// Traverses the entire tree if \p root is "". +/// When a file is encountered, calls \c visitor.file passing the file name. +/// When a directory is encountered, calls \c visitor.directory passing the directory name. +/// Skips the directory if \c visitor.directory returned true. +/// Root comparisons are case-insensitive. +/// Names are mixed-case. +virtual void forEachFile( VisitorFunc visitor, const char* root ) = 0; }; class CustomArchiveVisitor { - Archive::Visitor* m_visitor; - Archive::EMode m_mode; - std::size_t m_depth; +Archive::Visitor* m_visitor; +Archive::EMode m_mode; +std::size_t m_depth; public: - CustomArchiveVisitor(Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth) - : m_visitor(&visitor), m_mode(mode), m_depth(depth) - { - } - void file(const char* name) - { - if((m_mode & Archive::eFiles) != 0) - m_visitor->visit(name); - } - bool directory(const char* name, std::size_t depth) - { - if((m_mode & Archive::eDirectories) != 0) - m_visitor->visit(name); - if(depth == m_depth) - return true; - return false; - } +CustomArchiveVisitor( Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth ) + : m_visitor( &visitor ), m_mode( mode ), m_depth( depth ){ +} +void file( const char* name ){ + if ( ( m_mode & Archive::eFiles ) != 0 ) { + m_visitor->visit( name ); + } +} +bool directory( const char* name, std::size_t depth ){ + if ( ( m_mode & Archive::eDirectories ) != 0 ) { + m_visitor->visit( name ); + } + if ( depth == m_depth ) { + return true; + } + return false; +} }; -typedef Archive* (*PFN_OPENARCHIVE) (const char* name); +typedef Archive* ( *PFN_OPENARCHIVE )( const char* name ); class _QERArchiveTable { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "archive"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "archive" ); - PFN_OPENARCHIVE m_pfnOpenArchive; +PFN_OPENARCHIVE m_pfnOpenArchive; }; template diff --git a/include/ibrush.cpp b/include/ibrush.cpp index 05dc91ef..f075783b 100644 --- a/include/ibrush.cpp +++ b/include/ibrush.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ibrush.h" - diff --git a/include/ibrush.h b/include/ibrush.h index ddc82559..1171f8a7 100644 --- a/include/ibrush.h +++ b/include/ibrush.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IBRUSH_H) +#if !defined( INCLUDED_IBRUSH_H ) #define INCLUDED_IBRUSH_H #include "generic/constant.h" @@ -29,71 +29,70 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA namespace scene { - class Node; +class Node; } #if 0 class IBrushFace { public: - virtual const char* GetShader() const = 0; - virtual void SetShader(const char* name) = 0; - virtual const TextureProjection& GetTexdef() const = 0; - virtual void GetTexdef(TextureProjection& projection) const = 0; - virtual void SetTexdef(const TextureProjection& projection) = 0; - virtual void GetFlags(ContentsFlagsValue& flags) const = 0; - virtual void SetFlags(const ContentsFlagsValue& flags) = 0; - virtual void ShiftTexdef(float s, float t) = 0; - virtual void ScaleTexdef(float s, float t) = 0; - virtual void RotateTexdef(float angle) = 0; - virtual void FitTexture(float s_repeat, float t_repeat) = 0; - virtual bool isDetail() const = 0; - virtual void setDetail(bool detail) = 0; +virtual const char* GetShader() const = 0; +virtual void SetShader( const char* name ) = 0; +virtual const TextureProjection& GetTexdef() const = 0; +virtual void GetTexdef( TextureProjection& projection ) const = 0; +virtual void SetTexdef( const TextureProjection& projection ) = 0; +virtual void GetFlags( ContentsFlagsValue& flags ) const = 0; +virtual void SetFlags( const ContentsFlagsValue& flags ) = 0; +virtual void ShiftTexdef( float s, float t ) = 0; +virtual void ScaleTexdef( float s, float t ) = 0; +virtual void RotateTexdef( float angle ) = 0; +virtual void FitTexture( float s_repeat, float t_repeat ) = 0; +virtual bool isDetail() const = 0; +virtual void setDetail( bool detail ) = 0; }; class IBrush { public: - STRING_CONSTANT(Name, "IBrush"); - virtual void reserve(std::size_t count) = 0; - virtual void clear() = 0; - virtual void copy(const IBrush& other) = 0; - virtual IBrushFace* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection) = 0; - virtual const AABB& localAABB() const = 0; - virtual void removeEmptyFaces() = 0; +STRING_CONSTANT( Name, "IBrush" ); +virtual void reserve( std::size_t count ) = 0; +virtual void clear() = 0; +virtual void copy( const IBrush& other ) = 0; +virtual IBrushFace* addPlane( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection ) = 0; +virtual const AABB& localAABB() const = 0; +virtual void removeEmptyFaces() = 0; }; class IBrushFaceInstance { public: - virtual IBrushFace& getFace() = 0; - virtual const IBrushFace& getFace() const = 0; - virtual bool isSelected() const = 0; - virtual void setSelected(SelectionSystem::EComponentMode mode, bool select) const = 0; +virtual IBrushFace& getFace() = 0; +virtual const IBrushFace& getFace() const = 0; +virtual bool isSelected() const = 0; +virtual void setSelected( SelectionSystem::EComponentMode mode, bool select ) const = 0; }; class IBrushInstance { public: - STRING_CONSTANT(Name, "IBrushInstance"); - virtual void forEachFaceInstance(const BrushInstanceVisitor& visitor) = 0; +STRING_CONSTANT( Name, "IBrushInstance" ); +virtual void forEachFaceInstance( const BrushInstanceVisitor& visitor ) = 0; }; #endif class _QERFaceData { public: - _QERFaceData() : m_shader(""), contents(0), flags(0), value(0) - { - } - Vector3 m_p0; - Vector3 m_p1; - Vector3 m_p2; - texdef_t m_texdef; - const char* m_shader; - int contents; - int flags; - int value; +_QERFaceData() : m_shader( "" ), contents( 0 ), flags( 0 ), value( 0 ){ +} +Vector3 m_p0; +Vector3 m_p1; +Vector3 m_p2; +texdef_t m_texdef; +const char* m_shader; +int contents; +int flags; +int value; }; typedef Callback1 BrushFaceDataCallback; @@ -101,12 +100,12 @@ typedef Callback1 BrushFaceDataCallback; class BrushCreator { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "brush"); - virtual scene::Node& createBrush() = 0; - virtual bool useAlternativeTextureProjection() const = 0; - virtual void Brush_forEachFace(scene::Node& brush, const BrushFaceDataCallback& callback) = 0; - virtual bool Brush_addFace(scene::Node& brush, const _QERFaceData& faceData) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "brush" ); +virtual scene::Node& createBrush() = 0; +virtual bool useAlternativeTextureProjection() const = 0; +virtual void Brush_forEachFace( scene::Node& brush, const BrushFaceDataCallback& callback ) = 0; +virtual bool Brush_addFace( scene::Node& brush, const _QERFaceData& faceData ) = 0; }; #include "modulesystem.h" @@ -119,9 +118,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalBrushModuleRef; -inline BrushCreator& GlobalBrushCreator() -{ - return GlobalBrushModule::getTable(); +inline BrushCreator& GlobalBrushCreator(){ + return GlobalBrushModule::getTable(); } #endif diff --git a/include/icamera.cpp b/include/icamera.cpp index 436e93a9..bad7cacf 100644 --- a/include/icamera.cpp +++ b/include/icamera.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "icamera.h" - diff --git a/include/icamera.h b/include/icamera.h index c98fdc06..e9becbae 100644 --- a/include/icamera.h +++ b/include/icamera.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //----------------------------------------------------------------------------- // @@ -25,7 +25,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // camera interface // -#if !defined(INCLUDED_ICAMERA_H) +#if !defined( INCLUDED_ICAMERA_H ) #define INCLUDED_ICAMERA_H #include "generic/constant.h" @@ -36,32 +36,32 @@ class Matrix4; class CameraView { public: - virtual void setModelview(const Matrix4& modelview) = 0; - virtual void setFieldOfView(float fieldOfView) = 0; +virtual void setModelview( const Matrix4& modelview ) = 0; +virtual void setFieldOfView( float fieldOfView ) = 0; }; class CameraModel { public: - STRING_CONSTANT(Name, "CameraModel"); - virtual void setCameraView(CameraView* view, const Callback& disconnect) = 0; +STRING_CONSTANT( Name, "CameraModel" ); +virtual void setCameraView( CameraView* view, const Callback& disconnect ) = 0; }; template class BasicVector3; typedef BasicVector3 Vector3; -typedef void (* PFN_GETCAMERA) ( Vector3& origin, Vector3& angles ); -typedef void (* PFN_SETCAMERA) ( const Vector3& origin, const Vector3& angles ); -typedef void (* PFN_GETCAMWINDOWEXTENTS) ( int *x, int *y, int *width, int *height ); +typedef void ( *PFN_GETCAMERA )( Vector3& origin, Vector3& angles ); +typedef void ( *PFN_SETCAMERA )( const Vector3& origin, const Vector3& angles ); +typedef void ( *PFN_GETCAMWINDOWEXTENTS )( int *x, int *y, int *width, int *height ); struct _QERCameraTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "camera"); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "camera" ); - PFN_GETCAMERA m_pfnGetCamera; - PFN_SETCAMERA m_pfnSetCamera; - PFN_GETCAMWINDOWEXTENTS m_pfnGetCamWindowExtents; + PFN_GETCAMERA m_pfnGetCamera; + PFN_SETCAMERA m_pfnSetCamera; + PFN_GETCAMWINDOWEXTENTS m_pfnGetCamWindowExtents; }; #endif diff --git a/include/idatastream.cpp b/include/idatastream.cpp index fff02b57..e6ef881e 100644 --- a/include/idatastream.cpp +++ b/include/idatastream.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "idatastream.h" - diff --git a/include/idatastream.h b/include/idatastream.h index c5a28a25..674c9fa9 100644 --- a/include/idatastream.h +++ b/include/idatastream.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IDATASTREAM_H) +#if !defined( INCLUDED_IDATASTREAM_H ) #define INCLUDED_IDATASTREAM_H #include @@ -27,47 +27,47 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class StreamBase { public: - typedef std::size_t size_type; - typedef unsigned char byte_type; +typedef std::size_t size_type; +typedef unsigned char byte_type; }; /// \brief A read-only byte-stream. class InputStream : public StreamBase { public: - /// \brief Attempts to read the next \p length bytes from the stream to \p buffer. - /// Returns the number of bytes actually stored in \p buffer. - virtual size_type read(byte_type* buffer, size_type length) = 0; +/// \brief Attempts to read the next \p length bytes from the stream to \p buffer. +/// Returns the number of bytes actually stored in \p buffer. +virtual size_type read( byte_type* buffer, size_type length ) = 0; }; /// \brief A write-only byte-stream. class OutputStream : public StreamBase { public: - /// \brief Attempts to write \p length bytes to the stream from \p buffer. - /// Returns the number of bytes actually read from \p buffer. - virtual size_type write(const byte_type* buffer, size_type length) = 0; +/// \brief Attempts to write \p length bytes to the stream from \p buffer. +/// Returns the number of bytes actually read from \p buffer. +virtual size_type write( const byte_type* buffer, size_type length ) = 0; }; class SeekableStream { public: - typedef int offset_type; - typedef std::size_t position_type; +typedef int offset_type; +typedef std::size_t position_type; - enum seekdir - { - beg, - cur, - end, - }; +enum seekdir +{ + beg, + cur, + end, +}; - /// \brief Sets the current \p position of the stream relative to the start. - virtual position_type seek(position_type position) = 0; - /// \brief Sets the current \p position of the stream relative to either the start, end or current position. - virtual position_type seek(offset_type offset, seekdir direction) = 0; - /// \brief Returns the current position of the stream. - virtual position_type tell() const = 0; +/// \brief Sets the current \p position of the stream relative to the start. +virtual position_type seek( position_type position ) = 0; +/// \brief Sets the current \p position of the stream relative to either the start, end or current position. +virtual position_type seek( offset_type offset, seekdir direction ) = 0; +/// \brief Returns the current position of the stream. +virtual position_type tell() const = 0; }; /// \brief A seekable read-only byte-stream. diff --git a/include/ieclass.cpp b/include/ieclass.cpp index 461edd53..5fd59c3a 100644 --- a/include/ieclass.cpp +++ b/include/ieclass.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ieclass.h" - diff --git a/include/ieclass.h b/include/ieclass.h index 89b86ca9..a50b74a8 100644 --- a/include/ieclass.h +++ b/include/ieclass.h @@ -1,34 +1,34 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /// \file ieclass.h /// \brief Entity Class definition loader API. -#if !defined(INCLUDED_IECLASS_H) +#if !defined( INCLUDED_IECLASS_H ) #define INCLUDED_IECLASS_H #include "generic/constant.h" -#define MAX_FLAGS 16 +#define MAX_FLAGS 16 // eclass show flags @@ -45,19 +45,18 @@ class ListAttributeType; class EntityClassCollector { public: - virtual void insert(EntityClass* eclass) = 0; - virtual void insert(const char* name, const ListAttributeType& list) - { - } +virtual void insert( EntityClass* eclass ) = 0; +virtual void insert( const char* name, const ListAttributeType& list ){ +} }; struct EntityClassScanner { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "eclass"); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "eclass" ); - void (*scanFile)(EntityClassCollector& collector, const char* filename); - const char* (*getExtension)(); + void ( *scanFile )( EntityClassCollector& collector, const char* filename ); + const char* ( *getExtension )( ); }; #include "modulesystem.h" @@ -82,7 +81,7 @@ typedef ModulesRef EClassModulesRef; class EntityClassVisitor { public: - virtual void visit(EntityClass* eclass) = 0; +virtual void visit( EntityClass* eclass ) = 0; }; class ModuleObserver; @@ -90,16 +89,16 @@ class ModuleObserver; struct EntityClassManager { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "eclassmanager"); - - EntityClass* (*findOrInsert)(const char* name, bool has_brushes); - const ListAttributeType* (*findListType)(const char* name); - void (*forEach)(EntityClassVisitor& visitor); - void (*attach)(ModuleObserver& observer); - void (*detach)(ModuleObserver& observer); - void (*realise)(); - void (*unrealise)(); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "eclassmanager" ); + + EntityClass* ( *findOrInsert )( const char* name, bool has_brushes ); + const ListAttributeType* ( *findListType )(const char* name); + void ( *forEach )( EntityClassVisitor& visitor ); + void ( *attach )( ModuleObserver& observer ); + void ( *detach )( ModuleObserver& observer ); + void ( *realise )(); + void ( *unrealise )(); }; template @@ -110,9 +109,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalEntityClassManagerModuleRef; -inline EntityClassManager& GlobalEntityClassManager() -{ - return GlobalEntityClassManagerModule::getTable(); +inline EntityClassManager& GlobalEntityClassManager(){ + return GlobalEntityClassManagerModule::getTable(); } #endif diff --git a/include/ientity.cpp b/include/ientity.cpp index 0a2eef32..88dd59eb 100644 --- a/include/ientity.cpp +++ b/include/ientity.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ientity.h" - diff --git a/include/ientity.h b/include/ientity.h index c74ed7c6..c315b3ab 100644 --- a/include/ientity.h +++ b/include/ientity.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IENTITY_H) +#if !defined( INCLUDED_IENTITY_H ) #define INCLUDED_IENTITY_H #include "generic/constant.h" @@ -34,61 +34,57 @@ typedef Callback1 KeyObserver; class EntityKeyValue { public: - virtual const char* c_str() const = 0; - virtual void assign(const char* other) = 0; - virtual void attach(const KeyObserver& observer) = 0; - virtual void detach(const KeyObserver& observer) = 0; +virtual const char* c_str() const = 0; +virtual void assign( const char* other ) = 0; +virtual void attach( const KeyObserver& observer ) = 0; +virtual void detach( const KeyObserver& observer ) = 0; }; class Entity { public: - STRING_CONSTANT(Name, "Entity"); - - class Observer - { - public: - virtual void insert(const char* key, EntityKeyValue& value) = 0; - virtual void erase(const char* key, EntityKeyValue& value) = 0; - virtual void clear() { }; - }; - - class Visitor - { - public: - virtual void visit(const char* key, const char* value) = 0; - }; - - virtual const EntityClass& getEntityClass() const = 0; - virtual void forEachKeyValue(Visitor& visitor) const = 0; - virtual void setKeyValue(const char* key, const char* value) = 0; - virtual const char* getKeyValue(const char* key) const = 0; - virtual bool isContainer() const = 0; - virtual void attach(Observer& observer) = 0; - virtual void detach(Observer& observer) = 0; +STRING_CONSTANT( Name, "Entity" ); + +class Observer +{ +public: +virtual void insert( const char* key, EntityKeyValue& value ) = 0; +virtual void erase( const char* key, EntityKeyValue& value ) = 0; +virtual void clear() { }; }; -class EntityCopyingVisitor : public Entity::Visitor +class Visitor { - Entity& m_entity; public: - EntityCopyingVisitor(Entity& entity) - : m_entity(entity) - { - } - - void visit(const char* key, const char* value) - { - if(!string_equal(key, "classname")) - { - m_entity.setKeyValue(key, value); - } - } +virtual void visit( const char* key, const char* value ) = 0; }; -inline Entity* Node_getEntity(scene::Node& node) +virtual const EntityClass& getEntityClass() const = 0; +virtual void forEachKeyValue( Visitor& visitor ) const = 0; +virtual void setKeyValue( const char* key, const char* value ) = 0; +virtual const char* getKeyValue( const char* key ) const = 0; +virtual bool isContainer() const = 0; +virtual void attach( Observer& observer ) = 0; +virtual void detach( Observer& observer ) = 0; +}; + +class EntityCopyingVisitor : public Entity::Visitor { - return NodeTypeCast::cast(node); +Entity& m_entity; +public: +EntityCopyingVisitor( Entity& entity ) + : m_entity( entity ){ +} + +void visit( const char* key, const char* value ){ + if ( !string_equal( key, "classname" ) ) { + m_entity.setKeyValue( key, value ); + } +} +}; + +inline Entity* Node_getEntity( scene::Node& node ){ + return NodeTypeCast::cast( node ); } @@ -99,14 +95,14 @@ class Reference; namespace scene { - class Node; +class Node; } typedef Reference NodeReference; namespace scene { - typedef Stack Path; +typedef Stack Path; } class Counter; @@ -114,26 +110,26 @@ class Counter; class EntityCreator { public: - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "entity"); +INTEGER_CONSTANT( Version, 2 ); +STRING_CONSTANT( Name, "entity" ); - virtual scene::Node& createEntity(EntityClass* eclass) = 0; +virtual scene::Node& createEntity( EntityClass* eclass ) = 0; - typedef void (*KeyValueChangedFunc)(); - virtual void setKeyValueChangedFunc(KeyValueChangedFunc func) = 0; +typedef void ( *KeyValueChangedFunc )(); +virtual void setKeyValueChangedFunc( KeyValueChangedFunc func ) = 0; - virtual void setCounter(Counter* counter) = 0; +virtual void setCounter( Counter* counter ) = 0; - virtual void connectEntities(const scene::Path& e1, const scene::Path& e2, int index) = 0; +virtual void connectEntities( const scene::Path& e1, const scene::Path& e2, int index ) = 0; - virtual void setLightRadii(bool lightRadii) = 0; - virtual bool getLightRadii() = 0; - virtual void setShowNames(bool showNames) = 0; - virtual bool getShowNames() = 0; - virtual void setShowAngles(bool showAngles) = 0; - virtual bool getShowAngles() = 0; +virtual void setLightRadii( bool lightRadii ) = 0; +virtual bool getLightRadii() = 0; +virtual void setShowNames( bool showNames ) = 0; +virtual bool getShowNames() = 0; +virtual void setShowAngles( bool showAngles ) = 0; +virtual bool getShowAngles() = 0; - virtual void printStatistics() const = 0; +virtual void printStatistics() const = 0; }; #include "modulesystem.h" @@ -146,9 +142,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalEntityModuleRef; -inline EntityCreator& GlobalEntityCreator() -{ - return GlobalEntityModule::getTable(); +inline EntityCreator& GlobalEntityCreator(){ + return GlobalEntityModule::getTable(); } #endif diff --git a/include/ifilesystem.cpp b/include/ifilesystem.cpp index d941113c..154f9065 100644 --- a/include/ifilesystem.cpp +++ b/include/ifilesystem.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ifilesystem.h" - diff --git a/include/ifilesystem.h b/include/ifilesystem.h index ed9e99fd..6bbc0db2 100644 --- a/include/ifilesystem.h +++ b/include/ifilesystem.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IFILESYSTEM_H) +#if !defined( INCLUDED_IFILESYSTEM_H ) #define INCLUDED_IFILESYSTEM_H #include @@ -41,65 +41,65 @@ typedef struct _GSList GSList; class VirtualFileSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "VFS"); - - /// \brief Adds a root search \p path. - /// Called before \c initialise. - virtual void initDirectory(const char *path) = 0; - /// \brief Initialises the filesystem. - /// Called after all root search paths have been added. - virtual void initialise() = 0; - /// \brief Shuts down the filesystem. - virtual void shutdown() = 0; - - /// \brief Returns the file identified by \p filename opened in binary mode, or 0 if not found. - /// The caller must \c release() the file returned if it is not 0. - virtual ArchiveFile* openFile(const char* filename) = 0; - /// \brief Returns the file identified by \p filename opened in text mode, or 0 if not found. - /// The caller must \c release() the file returned if it is not 0. - virtual ArchiveTextFile* openTextFile(const char* filename) = 0; - - /// \brief Opens the file identified by \p filename and reads it into \p buffer, or sets *\p buffer to 0 if not found. - /// Returns the size of the buffer allocated, or undefined value if *\p buffer is 0; - /// The caller must free the allocated buffer by calling \c freeFile - /// \deprecated Deprecated - use \c openFile. - virtual std::size_t loadFile(const char *filename, void **buffer) = 0; - /// \brief Frees the buffer returned by \c loadFile. - /// \deprecated Deprecated. - virtual void freeFile(void *p) = 0; - - /// \brief Calls \p callback for each directory under \p basedir. - virtual void forEachDirectory(const char* basedir, const FileNameCallback& callback, std::size_t depth = 1) = 0; - /// \brief Calls \p callback for each file under \p basedir matching \p extension. - /// Use "*" as \p extension to match all file extensions. - virtual void forEachFile(const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1) = 0; - - /// \brief Returns a list containing the relative names of all the directories under \p basedir. - /// The caller must free the returned list by calling \c clearFileDirList; - /// \deprecated Deprecated - use \c forEachDirectory. - virtual GSList* getDirList(const char *basedir) = 0; - /// \brief Returns a list containing the relative names of the files under \p basedir (\p extension can be "*" for all files). - /// The caller must free the returned list by calling \c clearFileDirList. - /// \deprecated Deprecated - use \c forEachFile. - virtual GSList* getFileList(const char *basedir, const char *extension) = 0; - /// \brief Frees the \p list returned from \c getDirList or \c getFileList. - /// \deprecated Deprecated. - virtual void clearFileDirList(GSList **list) = 0; - - /// \brief Returns the absolute filename for a relative \p name, or "" if not found. - virtual const char* findFile(const char* name) = 0; - /// \brief Returns the filesystem root for an absolute \p name, or "" if not found. - /// This can be used to convert an absolute name to a relative name. - virtual const char* findRoot(const char* name) = 0; - - /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the filesystem is initialised or shut down. - virtual void attach(ModuleObserver& observer) = 0; - /// \brief Detach an \p observer previously-attached by calling \c attach. - virtual void detach(ModuleObserver& observer) = 0; - - virtual Archive* getArchive(const char* archiveName, bool pakonly=true) = 0; - virtual void forEachArchive(const ArchiveNameCallback& callback, bool pakonly=true, bool reverse=false) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "VFS" ); + +/// \brief Adds a root search \p path. +/// Called before \c initialise. +virtual void initDirectory( const char *path ) = 0; +/// \brief Initialises the filesystem. +/// Called after all root search paths have been added. +virtual void initialise() = 0; +/// \brief Shuts down the filesystem. +virtual void shutdown() = 0; + +/// \brief Returns the file identified by \p filename opened in binary mode, or 0 if not found. +/// The caller must \c release() the file returned if it is not 0. +virtual ArchiveFile* openFile( const char* filename ) = 0; +/// \brief Returns the file identified by \p filename opened in text mode, or 0 if not found. +/// The caller must \c release() the file returned if it is not 0. +virtual ArchiveTextFile* openTextFile( const char* filename ) = 0; + +/// \brief Opens the file identified by \p filename and reads it into \p buffer, or sets *\p buffer to 0 if not found. +/// Returns the size of the buffer allocated, or undefined value if *\p buffer is 0; +/// The caller must free the allocated buffer by calling \c freeFile +/// \deprecated Deprecated - use \c openFile. +virtual std::size_t loadFile( const char *filename, void **buffer ) = 0; +/// \brief Frees the buffer returned by \c loadFile. +/// \deprecated Deprecated. +virtual void freeFile( void *p ) = 0; + +/// \brief Calls \p callback for each directory under \p basedir. +virtual void forEachDirectory( const char* basedir, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; +/// \brief Calls \p callback for each file under \p basedir matching \p extension. +/// Use "*" as \p extension to match all file extensions. +virtual void forEachFile( const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1 ) = 0; + +/// \brief Returns a list containing the relative names of all the directories under \p basedir. +/// The caller must free the returned list by calling \c clearFileDirList; +/// \deprecated Deprecated - use \c forEachDirectory. +virtual GSList* getDirList( const char *basedir ) = 0; +/// \brief Returns a list containing the relative names of the files under \p basedir (\p extension can be "*" for all files). +/// The caller must free the returned list by calling \c clearFileDirList. +/// \deprecated Deprecated - use \c forEachFile. +virtual GSList* getFileList( const char *basedir, const char *extension ) = 0; +/// \brief Frees the \p list returned from \c getDirList or \c getFileList. +/// \deprecated Deprecated. +virtual void clearFileDirList( GSList **list ) = 0; + +/// \brief Returns the absolute filename for a relative \p name, or "" if not found. +virtual const char* findFile( const char* name ) = 0; +/// \brief Returns the filesystem root for an absolute \p name, or "" if not found. +/// This can be used to convert an absolute name to a relative name. +virtual const char* findRoot( const char* name ) = 0; + +/// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the filesystem is initialised or shut down. +virtual void attach( ModuleObserver& observer ) = 0; +/// \brief Detach an \p observer previously-attached by calling \c attach. +virtual void detach( ModuleObserver& observer ) = 0; + +virtual Archive* getArchive( const char* archiveName, bool pakonly = true ) = 0; +virtual void forEachArchive( const ArchiveNameCallback& callback, bool pakonly = true, bool reverse = false ) = 0; }; #include "modulesystem.h" @@ -112,22 +112,19 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalFileSystemModuleRef; -inline VirtualFileSystem& GlobalFileSystem() -{ - return GlobalFileSystemModule::getTable(); +inline VirtualFileSystem& GlobalFileSystem(){ + return GlobalFileSystemModule::getTable(); } /// \deprecated Use \c openFile. -inline int vfsLoadFile(const char* filename, void** buffer, int index = 0) -{ - return static_cast(GlobalFileSystem().loadFile(filename, buffer)); +inline int vfsLoadFile( const char* filename, void** buffer, int index = 0 ){ + return static_cast( GlobalFileSystem().loadFile( filename, buffer ) ); }; /// \deprecated Deprecated. -inline void vfsFreeFile(void* p) -{ - GlobalFileSystem().freeFile(p); +inline void vfsFreeFile( void* p ){ + GlobalFileSystem().freeFile( p ); } #endif diff --git a/include/ifiletypes.cpp b/include/ifiletypes.cpp index 1d151586..b4e55668 100644 --- a/include/ifiletypes.cpp +++ b/include/ifiletypes.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ifiletypes.h" - diff --git a/include/ifiletypes.h b/include/ifiletypes.h index 0d061d2b..25d2cac9 100644 --- a/include/ifiletypes.h +++ b/include/ifiletypes.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IFILETYPES_H) +#if !defined( INCLUDED_IFILETYPES_H ) #define INCLUDED_IFILETYPES_H #include "generic/constant.h" @@ -27,36 +27,34 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class filetype_t { public: - filetype_t() - : name(""), pattern("") - { - } - filetype_t(const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true) - : name(_name), pattern(_pattern), can_load(_can_load), can_import(_can_import), can_save(_can_save) - { - } - const char* name; - const char* pattern; - bool can_load; - bool can_import; - bool can_save; +filetype_t() + : name( "" ), pattern( "" ){ +} +filetype_t( const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true ) + : name( _name ), pattern( _pattern ), can_load( _can_load ), can_import( _can_import ), can_save( _can_save ){ +} +const char* name; +const char* pattern; +bool can_load; +bool can_import; +bool can_save; }; class IFileTypeList { public: - virtual void addType(const char* moduleName, filetype_t type) = 0; +virtual void addType( const char* moduleName, filetype_t type ) = 0; }; class IFileTypeRegistry { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "filetypes"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "filetypes" ); - virtual void addType(const char* moduleType, const char* moduleName, filetype_t type) = 0; - virtual void getTypeList(const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false) = 0; +virtual void addType( const char* moduleType, const char* moduleName, filetype_t type ) = 0; +virtual void getTypeList( const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false ) = 0; }; #include "modulesystem.h" @@ -69,9 +67,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalFiletypesModuleRef; -inline IFileTypeRegistry& GlobalFiletypes() -{ - return GlobalFiletypesModule::getTable(); +inline IFileTypeRegistry& GlobalFiletypes(){ + return GlobalFiletypesModule::getTable(); } diff --git a/include/ifilter.cpp b/include/ifilter.cpp index 1472a935..a5e732f4 100644 --- a/include/ifilter.cpp +++ b/include/ifilter.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ifilter.h" - diff --git a/include/ifilter.h b/include/ifilter.h index 3da2f1d6..7efbb8a9 100644 --- a/include/ifilter.h +++ b/include/ifilter.h @@ -1,74 +1,74 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IFILTER_H) +#if !defined( INCLUDED_IFILTER_H ) #define INCLUDED_IFILTER_H #include "generic/constant.h" enum { - EXCLUDE_WORLD = 0x00000001, - EXCLUDE_ENT = 0x00000002, - EXCLUDE_CURVES = 0x00000004, - EXCLUDE_TRANSLUCENT = 0x00000008, - EXCLUDE_LIQUIDS = 0x00000010, - EXCLUDE_CAULK = 0x00000020, - EXCLUDE_CLIP = 0x00000040, - EXCLUDE_PATHS = 0x00000080, - EXCLUDE_LIGHTS = 0x00000100, - EXCLUDE_DETAILS = 0x00000200, - EXCLUDE_HINTSSKIPS = 0x00000400, - EXCLUDE_MODELS = 0x00000800, - EXCLUDE_AREAPORTALS = 0x00001000, - EXCLUDE_TRIGGERS = 0x00002000, - EXCLUDE_CLUSTERPORTALS = 0x00004000, - EXCLUDE_TERRAIN = 0x00008000, - EXCLUDE_LIGHTGRID = 0x00010000, - EXCLUDE_STRUCTURAL = 0x00020000, - EXCLUDE_BOTCLIP = 0x00040000, - EXCLUDE_VISPORTALS = 0x00080000, - EXCLUDE_DECALS = 0x00100000, + EXCLUDE_WORLD = 0x00000001, + EXCLUDE_ENT = 0x00000002, + EXCLUDE_CURVES = 0x00000004, + EXCLUDE_TRANSLUCENT = 0x00000008, + EXCLUDE_LIQUIDS = 0x00000010, + EXCLUDE_CAULK = 0x00000020, + EXCLUDE_CLIP = 0x00000040, + EXCLUDE_PATHS = 0x00000080, + EXCLUDE_LIGHTS = 0x00000100, + EXCLUDE_DETAILS = 0x00000200, + EXCLUDE_HINTSSKIPS = 0x00000400, + EXCLUDE_MODELS = 0x00000800, + EXCLUDE_AREAPORTALS = 0x00001000, + EXCLUDE_TRIGGERS = 0x00002000, + EXCLUDE_CLUSTERPORTALS = 0x00004000, + EXCLUDE_TERRAIN = 0x00008000, + EXCLUDE_LIGHTGRID = 0x00010000, + EXCLUDE_STRUCTURAL = 0x00020000, + EXCLUDE_BOTCLIP = 0x00040000, + EXCLUDE_VISPORTALS = 0x00080000, + EXCLUDE_DECALS = 0x00100000, }; class Filter { public: - virtual void setActive(bool active) = 0; +virtual void setActive( bool active ) = 0; }; class Filterable { public: - virtual void updateFiltered() = 0; +virtual void updateFiltered() = 0; }; class FilterSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "filters"); - virtual void addFilter(Filter& filter, int mask) = 0; - virtual void registerFilterable(Filterable& filterable) = 0; - virtual void unregisterFilterable(Filterable& filterable) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "filters" ); +virtual void addFilter( Filter& filter, int mask ) = 0; +virtual void registerFilterable( Filterable& filterable ) = 0; +virtual void unregisterFilterable( Filterable& filterable ) = 0; }; #include "modulesystem.h" @@ -81,9 +81,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalFilterModuleRef; -inline FilterSystem& GlobalFilterSystem() -{ - return GlobalFilterModule::getTable(); +inline FilterSystem& GlobalFilterSystem(){ + return GlobalFilterModule::getTable(); } #endif diff --git a/include/igl.cpp b/include/igl.cpp index 170022ee..41781a49 100644 --- a/include/igl.cpp +++ b/include/igl.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "igl.h" - diff --git a/include/igl.h b/include/igl.h index 35174967..eca09ae7 100644 --- a/include/igl.h +++ b/include/igl.h @@ -1,32 +1,32 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IGL_H) +#if !defined( INCLUDED_IGL_H ) #define INCLUDED_IGL_H #include #include #include "generic/constant.h" -#if defined(WIN32) +#if defined( WIN32 ) #define QGL_DLLEXPORT __stdcall #else #define QGL_DLLEXPORT @@ -48,7 +48,7 @@ typedef double GLdouble; typedef double GLclampd; typedef void GLvoid; -#if !defined(GL_VERSION_1_1) +#if !defined( GL_VERSION_1_1 ) #define GL_VERSION_1_1 1 #define GL_ZERO 0 @@ -918,7 +918,7 @@ typedef void GLvoid; #endif -#if !defined(GL_EXT_vertex_array) +#if !defined( GL_EXT_vertex_array ) #define GL_EXT_vertex_array 1 #define GL_VERTEX_ARRAY_EXT 0x8074 @@ -958,7 +958,7 @@ typedef void GLvoid; #endif -#if !defined(GL_EXT_bgra) +#if !defined( GL_EXT_bgra ) #define GL_EXT_bgra 1 #define GL_BGR_EXT 0x80E0 @@ -967,7 +967,7 @@ typedef void GLvoid; #endif -#if !defined(GL_EXT_paletted_texture) +#if !defined( GL_EXT_paletted_texture ) #define GL_EXT_paletted_texture 1 #define GL_COLOR_TABLE_FORMAT_EXT 0x80D8 @@ -991,7 +991,7 @@ typedef void GLvoid; #endif -#if !defined(GL_ARB_multitexture) +#if !defined( GL_ARB_multitexture ) #define GL_ARB_multitexture 1 #define GL_TEXTURE0_ARB 0x84C0 @@ -1069,7 +1069,7 @@ typedef void GLvoid; // EXT_texture_compression_s3tc -#if !defined(GL_EXT_texture_compression_s3tc) +#if !defined( GL_EXT_texture_compression_s3tc ) #define GL_EXT_texture_compression_s3tc 1 #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 @@ -1081,7 +1081,7 @@ typedef void GLvoid; // ARB_texture_compression -#if !defined(GL_ARB_texture_compression) +#if !defined( GL_ARB_texture_compression ) #define GL_ARB_texture_compression 1 #define GL_COMPRESSED_ALPHA_ARB 0x84E9 @@ -1109,7 +1109,7 @@ typedef void GLvoid; // GL 1.2 -#if !defined(GL_VERSION_1_2) +#if !defined( GL_VERSION_1_2 ) #define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 #define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 @@ -1163,7 +1163,7 @@ typedef void GLvoid; // GL 1.3 -#if !defined(GL_VERSION_1_3) +#if !defined( GL_VERSION_1_3 ) #define GL_VERSION_1_3 1 #define GL_MULTISAMPLE 0x809D @@ -1314,7 +1314,7 @@ typedef void GLvoid; // GL 1.4 -#if !defined(GL_VERSION_1_4) +#if !defined( GL_VERSION_1_4 ) #define GL_VERSION_1_4 1 #define GL_BLEND_DST_RGB 0x80C8 @@ -1409,7 +1409,7 @@ typedef void GLvoid; // GL 1.5 -#if !defined(GL_VERSION_1_5) +#if !defined( GL_VERSION_1_5 ) #define GL_VERSION_1_5 1 #define GL_FOG_COORD GL_FOG_COORDINATE @@ -1490,7 +1490,7 @@ typedef std::ptrdiff_t GLintptr; // GL_ARB_vertex_program -#if !defined(GL_ARB_vertex_program) +#if !defined( GL_ARB_vertex_program ) #define GL_ARB_vertex_program #define GL_VERTEX_PROGRAM_ARB 0x8620 @@ -1640,7 +1640,7 @@ typedef std::ptrdiff_t GLintptr; // GL_ARB_fragment_program -#if !defined(GL_ARB_fragment_program) +#if !defined( GL_ARB_fragment_program ) #define GL_ARB_fragment_program 1 #define GL_FRAGMENT_PROGRAM_ARB 0x8804 @@ -1663,7 +1663,7 @@ typedef std::ptrdiff_t GLintptr; // GL_ARB_shader_objects -#if !defined(GL_ARB_shader_objects) +#if !defined( GL_ARB_shader_objects ) #define GL_ARB_shader_objects 1 #define GL_PROGRAM_OBJECT_ARB 0x8B40 @@ -1747,7 +1747,7 @@ typedef unsigned int GLhandleARB; #endif // GL_ARB_vertex_shader -#if !defined(GL_ARB_vertex_shader) +#if !defined( GL_ARB_vertex_shader ) #define GL_ARB_vertex_shader 1 #define GL_VERTEX_SHADER_ARB 0x8B31 @@ -1813,7 +1813,7 @@ typedef unsigned int GLhandleARB; // GL_ARB_fragment_shader -#if !defined(GL_ARB_fragment_shader) +#if !defined( GL_ARB_fragment_shader ) #define GL_ARB_fragment_shader 1 #define GL_FRAGMENT_SHADER_ARB 0x8B30 @@ -1824,7 +1824,7 @@ typedef unsigned int GLhandleARB; // GL_ARB_shading_language_100 -#if !defined(GL_ARB_shading_language_100) +#if !defined( GL_ARB_shading_language_100 ) #define GL_ARB_shading_language_100 1 #define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C @@ -1833,7 +1833,7 @@ typedef unsigned int GLhandleARB; // GL_NV_vertex_program2 -#if !defined(GL_NV_vertex_program) +#if !defined( GL_NV_vertex_program ) #define GL_NV_vertex_program 1 #define GL_VERTEX_PROGRAM_NV 0x8620 @@ -1959,7 +1959,7 @@ typedef unsigned int GLhandleARB; // GL_NV_fragment_program -#if !defined(GL_NV_fragment_program) +#if !defined( GL_NV_fragment_program ) #define GL_NV_fragment_program 1 @@ -1982,831 +1982,813 @@ typedef unsigned int GLhandleARB; /// Provides convenience functions for querying availabiliy of extensions, rendering text and error-checking. struct OpenGLBinding { - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "qgl"); - - /// \brief OpenGL version, extracted from the GL_VERSION string. - int major_version, minor_version; - - /// \brief Is true if the global shared OpenGL context is valid. - bool contextValid; - - OpenGLBinding() : contextValid(false) - { - } - - /// \brief Asserts that there no OpenGL errors have occurred since the last call to glGetError. - void (*assertNoErrors)(const char *file, int line); - - GLFont *m_font; // MUST be set! - - /// \brief Renders \p string at the current raster-position of the current context. - void drawString(const char* string) const - { - m_font->printString(string); - } - - /// \brief Renders \p character at the current raster-position of the current context. - void drawChar(char character) const - { - char s[2]; - s[0] = character; - s[1] = 0; - drawString(s); - } - - - // GL 1.1 - void (QGL_DLLEXPORT *m_glAccum)(GLenum op, GLfloat value); - void (QGL_DLLEXPORT *m_glAlphaFunc)(GLenum func, GLclampf ref); - GLboolean (QGL_DLLEXPORT *m_glAreTexturesResident)(GLsizei n, const GLuint *textures, GLboolean *residences); - void (QGL_DLLEXPORT *m_glArrayElement)(GLint i); - void (QGL_DLLEXPORT *m_glBegin)(GLenum mode); - void (QGL_DLLEXPORT *m_glBindTexture)(GLenum target, GLuint texture); - void (QGL_DLLEXPORT *m_glBitmap)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); - void (QGL_DLLEXPORT *m_glBlendFunc)(GLenum sfactor, GLenum dfactor); - void (QGL_DLLEXPORT *m_glCallList)(GLuint list); - void (QGL_DLLEXPORT *m_glCallLists)(GLsizei n, GLenum type, const GLvoid *lists); - void (QGL_DLLEXPORT *m_glClear)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glClearAccum)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); - void (QGL_DLLEXPORT *m_glClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - void (QGL_DLLEXPORT *m_glClearDepth)(GLclampd depth); - void (QGL_DLLEXPORT *m_glClearIndex)(GLfloat c); - void (QGL_DLLEXPORT *m_glClearStencil)(GLint s); - void (QGL_DLLEXPORT *m_glClipPlane)(GLenum plane, const GLdouble *equation); - void (QGL_DLLEXPORT *m_glColor3b)(GLbyte red, GLbyte green, GLbyte blue); - void (QGL_DLLEXPORT *m_glColor3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glColor3d)(GLdouble red, GLdouble green, GLdouble blue); - void (QGL_DLLEXPORT *m_glColor3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glColor3f)(GLfloat red, GLfloat green, GLfloat blue); - void (QGL_DLLEXPORT *m_glColor3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glColor3i)(GLint red, GLint green, GLint blue); - void (QGL_DLLEXPORT *m_glColor3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glColor3s)(GLshort red, GLshort green, GLshort blue); - void (QGL_DLLEXPORT *m_glColor3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glColor3ub)(GLubyte red, GLubyte green, GLubyte blue); - void (QGL_DLLEXPORT *m_glColor3ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glColor3ui)(GLuint red, GLuint green, GLuint blue); - void (QGL_DLLEXPORT *m_glColor3uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glColor3us)(GLushort red, GLushort green, GLushort blue); - void (QGL_DLLEXPORT *m_glColor3usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glColor4b)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); - void (QGL_DLLEXPORT *m_glColor4bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glColor4d)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); - void (QGL_DLLEXPORT *m_glColor4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); - void (QGL_DLLEXPORT *m_glColor4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glColor4i)(GLint red, GLint green, GLint blue, GLint alpha); - void (QGL_DLLEXPORT *m_glColor4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glColor4s)(GLshort red, GLshort green, GLshort blue, GLshort alpha); - void (QGL_DLLEXPORT *m_glColor4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glColor4ub)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); - void (QGL_DLLEXPORT *m_glColor4ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glColor4ui)(GLuint red, GLuint green, GLuint blue, GLuint alpha); - void (QGL_DLLEXPORT *m_glColor4uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glColor4us)(GLushort red, GLushort green, GLushort blue, GLushort alpha); - void (QGL_DLLEXPORT *m_glColor4usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - void (QGL_DLLEXPORT *m_glColorMaterial)(GLenum face, GLenum mode); - void (QGL_DLLEXPORT *m_glColorPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glCopyPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); - void (QGL_DLLEXPORT *m_glCopyTexImage1D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border); - void (QGL_DLLEXPORT *m_glCopyTexImage2D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); - void (QGL_DLLEXPORT *m_glCopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); - void (QGL_DLLEXPORT *m_glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glCullFace)(GLenum mode); - void (QGL_DLLEXPORT *m_glDeleteLists)(GLuint list, GLsizei range); - void (QGL_DLLEXPORT *m_glDeleteTextures)(GLsizei n, const GLuint *textures); - void (QGL_DLLEXPORT *m_glDepthFunc)(GLenum func); - void (QGL_DLLEXPORT *m_glDepthMask)(GLboolean flag); - void (QGL_DLLEXPORT *m_glDepthRange)(GLclampd zNear, GLclampd zFar); - void (QGL_DLLEXPORT *m_glDisable)(GLenum cap); - void (QGL_DLLEXPORT *m_glDisableClientState)(GLenum array); - void (QGL_DLLEXPORT *m_glDrawArrays)(GLenum mode, GLint first, GLsizei count); - void (QGL_DLLEXPORT *m_glDrawBuffer)(GLenum mode); - void (QGL_DLLEXPORT *m_glDrawElements)(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices); - void (QGL_DLLEXPORT *m_glDrawPixels)(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glEdgeFlag)(GLboolean flag); - void (QGL_DLLEXPORT *m_glEdgeFlagPointer)(GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEdgeFlagv)(const GLboolean *flag); - void (QGL_DLLEXPORT *m_glEnable)(GLenum cap); - void (QGL_DLLEXPORT *m_glEnableClientState)(GLenum array); - void (QGL_DLLEXPORT *m_glEnd)(void); - void (QGL_DLLEXPORT *m_glEndList)(void); - void (QGL_DLLEXPORT *m_glEvalCoord1d)(GLdouble u); - void (QGL_DLLEXPORT *m_glEvalCoord1dv)(const GLdouble *u); - void (QGL_DLLEXPORT *m_glEvalCoord1f)(GLfloat u); - void (QGL_DLLEXPORT *m_glEvalCoord1fv)(const GLfloat *u); - void (QGL_DLLEXPORT *m_glEvalCoord2d)(GLdouble u, GLdouble v); - void (QGL_DLLEXPORT *m_glEvalCoord2dv)(const GLdouble *u); - void (QGL_DLLEXPORT *m_glEvalCoord2f)(GLfloat u, GLfloat v); - void (QGL_DLLEXPORT *m_glEvalCoord2fv)(const GLfloat *u); - void (QGL_DLLEXPORT *m_glEvalMesh1)(GLenum mode, GLint i1, GLint i2); - void (QGL_DLLEXPORT *m_glEvalMesh2)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); - void (QGL_DLLEXPORT *m_glEvalPoint1)(GLint i); - void (QGL_DLLEXPORT *m_glEvalPoint2)(GLint i, GLint j); - void (QGL_DLLEXPORT *m_glFeedbackBuffer)(GLsizei size, GLenum type, GLfloat *buffer); - void (QGL_DLLEXPORT *m_glFinish)(void); - void (QGL_DLLEXPORT *m_glFlush)(void); - void (QGL_DLLEXPORT *m_glFogf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glFogfv)(GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glFogi)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glFogiv)(GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glFrontFace)(GLenum mode); - void (QGL_DLLEXPORT *m_glFrustum)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); - GLuint (QGL_DLLEXPORT *m_glGenLists)(GLsizei range); - void (QGL_DLLEXPORT *m_glGenTextures)(GLsizei n, GLuint *textures); - void (QGL_DLLEXPORT *m_glGetBooleanv)(GLenum pname, GLboolean *params); - void (QGL_DLLEXPORT *m_glGetClipPlane)(GLenum plane, GLdouble *equation); - void (QGL_DLLEXPORT *m_glGetDoublev)(GLenum pname, GLdouble *params); - GLenum (QGL_DLLEXPORT *m_glGetError)(void); - void (QGL_DLLEXPORT *m_glGetFloatv)(GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetIntegerv)(GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetLightfv)(GLenum light, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetLightiv)(GLenum light, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetMapdv)(GLenum target, GLenum query, GLdouble *v); - void (QGL_DLLEXPORT *m_glGetMapfv)(GLenum target, GLenum query, GLfloat *v); - void (QGL_DLLEXPORT *m_glGetMapiv)(GLenum target, GLenum query, GLint *v); - void (QGL_DLLEXPORT *m_glGetMaterialfv)(GLenum face, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetMaterialiv)(GLenum face, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetPixelMapfv)(GLenum map, GLfloat *values); - void (QGL_DLLEXPORT *m_glGetPixelMapuiv)(GLenum map, GLuint *values); - void (QGL_DLLEXPORT *m_glGetPixelMapusv)(GLenum map, GLushort *values); - void (QGL_DLLEXPORT *m_glGetPointerv)(GLenum pname, GLvoid* *params); - void (QGL_DLLEXPORT *m_glGetPolygonStipple)(GLubyte *mask); - const GLubyte * (QGL_DLLEXPORT *m_glGetString)(GLenum name); - void (QGL_DLLEXPORT *m_glGetTexEnvfv)(GLenum target, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexEnviv)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexGendv)(GLenum coord, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetTexGenfv)(GLenum coord, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexGeniv)(GLenum coord, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels); - void (QGL_DLLEXPORT *m_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexParameteriv)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glHint)(GLenum target, GLenum mode); - void (QGL_DLLEXPORT *m_glIndexMask)(GLuint mask); - void (QGL_DLLEXPORT *m_glIndexPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glIndexd)(GLdouble c); - void (QGL_DLLEXPORT *m_glIndexdv)(const GLdouble *c); - void (QGL_DLLEXPORT *m_glIndexf)(GLfloat c); - void (QGL_DLLEXPORT *m_glIndexfv)(const GLfloat *c); - void (QGL_DLLEXPORT *m_glIndexi)(GLint c); - void (QGL_DLLEXPORT *m_glIndexiv)(const GLint *c); - void (QGL_DLLEXPORT *m_glIndexs)(GLshort c); - void (QGL_DLLEXPORT *m_glIndexsv)(const GLshort *c); - void (QGL_DLLEXPORT *m_glIndexub)(GLubyte c); - void (QGL_DLLEXPORT *m_glIndexubv)(const GLubyte *c); - void (QGL_DLLEXPORT *m_glInitNames)(void); - void (QGL_DLLEXPORT *m_glInterleavedArrays)(GLenum format, GLsizei stride, const GLvoid *pointer); - GLboolean (QGL_DLLEXPORT *m_glIsEnabled)(GLenum cap); - GLboolean (QGL_DLLEXPORT *m_glIsList)(GLuint list); - GLboolean (QGL_DLLEXPORT *m_glIsTexture)(GLuint texture); - void (QGL_DLLEXPORT *m_glLightModelf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glLightModelfv)(GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glLightModeli)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glLightModeliv)(GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glLightf)(GLenum light, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glLightfv)(GLenum light, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glLighti)(GLenum light, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glLightiv)(GLenum light, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glLineStipple)(GLint factor, GLushort pattern); - void (QGL_DLLEXPORT *m_glLineWidth)(GLfloat width); - void (QGL_DLLEXPORT *m_glListBase)(GLuint base); - void (QGL_DLLEXPORT *m_glLoadIdentity)(void); - void (QGL_DLLEXPORT *m_glLoadMatrixd)(const GLdouble *m); - void (QGL_DLLEXPORT *m_glLoadMatrixf)(const GLfloat *m); - void (QGL_DLLEXPORT *m_glLoadName)(GLuint name); - void (QGL_DLLEXPORT *m_glLogicOp)(GLenum opcode); - void (QGL_DLLEXPORT *m_glMap1d)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); - void (QGL_DLLEXPORT *m_glMap1f)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); - void (QGL_DLLEXPORT *m_glMap2d)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); - void (QGL_DLLEXPORT *m_glMap2f)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); - void (QGL_DLLEXPORT *m_glMapGrid1d)(GLint un, GLdouble u1, GLdouble u2); - void (QGL_DLLEXPORT *m_glMapGrid1f)(GLint un, GLfloat u1, GLfloat u2); - void (QGL_DLLEXPORT *m_glMapGrid2d)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); - void (QGL_DLLEXPORT *m_glMapGrid2f)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glMaterialf)(GLenum face, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glMaterialfv)(GLenum face, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glMateriali)(GLenum face, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glMaterialiv)(GLenum face, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glMatrixMode)(GLenum mode); - void (QGL_DLLEXPORT *m_glMultMatrixd)(const GLdouble *m); - void (QGL_DLLEXPORT *m_glMultMatrixf)(const GLfloat *m); - void (QGL_DLLEXPORT *m_glNewList)(GLuint list, GLenum mode); - void (QGL_DLLEXPORT *m_glNormal3b)(GLbyte nx, GLbyte ny, GLbyte nz); - void (QGL_DLLEXPORT *m_glNormal3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glNormal3d)(GLdouble nx, GLdouble ny, GLdouble nz); - void (QGL_DLLEXPORT *m_glNormal3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glNormal3f)(GLfloat nx, GLfloat ny, GLfloat nz); - void (QGL_DLLEXPORT *m_glNormal3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glNormal3i)(GLint nx, GLint ny, GLint nz); - void (QGL_DLLEXPORT *m_glNormal3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glNormal3s)(GLshort nx, GLshort ny, GLshort nz); - void (QGL_DLLEXPORT *m_glNormal3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glNormalPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glOrtho)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); - void (QGL_DLLEXPORT *m_glPassThrough)(GLfloat token); - void (QGL_DLLEXPORT *m_glPixelMapfv)(GLenum map, GLsizei mapsize, const GLfloat *values); - void (QGL_DLLEXPORT *m_glPixelMapuiv)(GLenum map, GLsizei mapsize, const GLuint *values); - void (QGL_DLLEXPORT *m_glPixelMapusv)(GLenum map, GLsizei mapsize, const GLushort *values); - void (QGL_DLLEXPORT *m_glPixelStoref)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPixelStorei)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glPixelTransferf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPixelTransferi)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glPixelZoom)(GLfloat xfactor, GLfloat yfactor); - void (QGL_DLLEXPORT *m_glPointSize)(GLfloat size); - void (QGL_DLLEXPORT *m_glPolygonMode)(GLenum face, GLenum mode); - void (QGL_DLLEXPORT *m_glPolygonOffset)(GLfloat factor, GLfloat units); - void (QGL_DLLEXPORT *m_glPolygonStipple)(const GLubyte *mask); - void (QGL_DLLEXPORT *m_glPopAttrib)(void); - void (QGL_DLLEXPORT *m_glPopClientAttrib)(void); - void (QGL_DLLEXPORT *m_glPopMatrix)(void); - void (QGL_DLLEXPORT *m_glPopName)(void); - void (QGL_DLLEXPORT *m_glPrioritizeTextures)(GLsizei n, const GLuint *textures, const GLclampf *priorities); - void (QGL_DLLEXPORT *m_glPushAttrib)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glPushClientAttrib)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glPushMatrix)(void); - void (QGL_DLLEXPORT *m_glPushName)(GLuint name); - void (QGL_DLLEXPORT *m_glRasterPos2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glRasterPos2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glRasterPos2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glRasterPos2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glRasterPos2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glRasterPos3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glRasterPos3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glRasterPos3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glRasterPos3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glRasterPos3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glRasterPos4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glRasterPos4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glRasterPos4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos4i)(GLint x, GLint y, GLint z, GLint w); - void (QGL_DLLEXPORT *m_glRasterPos4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos4s)(GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glRasterPos4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glReadBuffer)(GLenum mode); - void (QGL_DLLEXPORT *m_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels); - void (QGL_DLLEXPORT *m_glRectd)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); - void (QGL_DLLEXPORT *m_glRectdv)(const GLdouble *v1, const GLdouble *v2); - void (QGL_DLLEXPORT *m_glRectf)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); - void (QGL_DLLEXPORT *m_glRectfv)(const GLfloat *v1, const GLfloat *v2); - void (QGL_DLLEXPORT *m_glRecti)(GLint x1, GLint y1, GLint x2, GLint y2); - void (QGL_DLLEXPORT *m_glRectiv)(const GLint *v1, const GLint *v2); - void (QGL_DLLEXPORT *m_glRects)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); - void (QGL_DLLEXPORT *m_glRectsv)(const GLshort *v1, const GLshort *v2); - GLint (QGL_DLLEXPORT *m_glRenderMode)(GLenum mode); - void (QGL_DLLEXPORT *m_glRotated)(GLdouble anm_gle, GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glRotatef)(GLfloat anm_gle, GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glScaled)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glScalef)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glSelectBuffer)(GLsizei size, GLuint *buffer); - void (QGL_DLLEXPORT *m_glShadeModel)(GLenum mode); - void (QGL_DLLEXPORT *m_glStencilFunc)(GLenum func, GLint ref, GLuint mask); - void (QGL_DLLEXPORT *m_glStencilMask)(GLuint mask); - void (QGL_DLLEXPORT *m_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass); - void (QGL_DLLEXPORT *m_glTexCoord1d)(GLdouble s); - void (QGL_DLLEXPORT *m_glTexCoord1dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord1f)(GLfloat s); - void (QGL_DLLEXPORT *m_glTexCoord1fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord1i)(GLint s); - void (QGL_DLLEXPORT *m_glTexCoord1iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord1s)(GLshort s); - void (QGL_DLLEXPORT *m_glTexCoord1sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord2d)(GLdouble s, GLdouble t); - void (QGL_DLLEXPORT *m_glTexCoord2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord2f)(GLfloat s, GLfloat t); - void (QGL_DLLEXPORT *m_glTexCoord2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord2i)(GLint s, GLint t); - void (QGL_DLLEXPORT *m_glTexCoord2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord2s)(GLshort s, GLshort t); - void (QGL_DLLEXPORT *m_glTexCoord2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord3d)(GLdouble s, GLdouble t, GLdouble r); - void (QGL_DLLEXPORT *m_glTexCoord3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord3f)(GLfloat s, GLfloat t, GLfloat r); - void (QGL_DLLEXPORT *m_glTexCoord3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord3i)(GLint s, GLint t, GLint r); - void (QGL_DLLEXPORT *m_glTexCoord3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord3s)(GLshort s, GLshort t, GLshort r); - void (QGL_DLLEXPORT *m_glTexCoord3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord4d)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); - void (QGL_DLLEXPORT *m_glTexCoord4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord4f)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); - void (QGL_DLLEXPORT *m_glTexCoord4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord4i)(GLint s, GLint t, GLint r, GLint q); - void (QGL_DLLEXPORT *m_glTexCoord4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord4s)(GLshort s, GLshort t, GLshort r, GLshort q); - void (QGL_DLLEXPORT *m_glTexCoord4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glTexEnvf)(GLenum target, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexEnvfv)(GLenum target, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexEnvi)(GLenum target, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexEnviv)(GLenum target, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glTexGend)(GLenum coord, GLenum pname, GLdouble param); - void (QGL_DLLEXPORT *m_glTexGendv)(GLenum coord, GLenum pname, const GLdouble *params); - void (QGL_DLLEXPORT *m_glTexGenf)(GLenum coord, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexGenfv)(GLenum coord, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexGeni)(GLenum coord, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexGeniv)(GLenum coord, GLenum pname, const GLint *params); -#if defined(MACVERSION) && MACVERSION > 15 - //Snow Leopard 16, Leopard 15, Tiger 14, Panther 13, ... - void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + INTEGER_CONSTANT( Version, 2 ); + STRING_CONSTANT( Name, "qgl" ); + + /// \brief OpenGL version, extracted from the GL_VERSION string. + int major_version, minor_version; + + /// \brief Is true if the global shared OpenGL context is valid. + bool contextValid; + + OpenGLBinding() : contextValid( false ){ + } + + /// \brief Asserts that there no OpenGL errors have occurred since the last call to glGetError. + void ( *assertNoErrors )( const char *file, int line ); + + GLFont *m_font; // MUST be set! + + /// \brief Renders \p string at the current raster-position of the current context. + void drawString( const char* string ) const { + m_font->printString( string ); + } + + /// \brief Renders \p character at the current raster-position of the current context. + void drawChar( char character ) const { + char s[2]; + s[0] = character; + s[1] = 0; + drawString( s ); + } + + + // GL 1.1 + void ( QGL_DLLEXPORT *m_glAccum )( GLenum op, GLfloat value ); + void ( QGL_DLLEXPORT *m_glAlphaFunc )( GLenum func, GLclampf ref ); + GLboolean ( QGL_DLLEXPORT *m_glAreTexturesResident )( GLsizei n, const GLuint *textures, GLboolean *residences ); + void ( QGL_DLLEXPORT *m_glArrayElement )( GLint i ); + void ( QGL_DLLEXPORT *m_glBegin )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glBindTexture )( GLenum target, GLuint texture ); + void ( QGL_DLLEXPORT *m_glBitmap )( GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap ); + void ( QGL_DLLEXPORT *m_glBlendFunc )( GLenum sfactor, GLenum dfactor ); + void ( QGL_DLLEXPORT *m_glCallList )( GLuint list ); + void ( QGL_DLLEXPORT *m_glCallLists )( GLsizei n, GLenum type, const GLvoid *lists ); + void ( QGL_DLLEXPORT *m_glClear )( GLbitfield mask ); + void ( QGL_DLLEXPORT *m_glClearAccum )( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha ); + void ( QGL_DLLEXPORT *m_glClearColor )( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha ); + void ( QGL_DLLEXPORT *m_glClearDepth )( GLclampd depth ); + void ( QGL_DLLEXPORT *m_glClearIndex )( GLfloat c ); + void ( QGL_DLLEXPORT *m_glClearStencil )( GLint s ); + void ( QGL_DLLEXPORT *m_glClipPlane )( GLenum plane, const GLdouble *equation ); + void ( QGL_DLLEXPORT *m_glColor3b )( GLbyte red, GLbyte green, GLbyte blue ); + void ( QGL_DLLEXPORT *m_glColor3bv )( const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glColor3d )( GLdouble red, GLdouble green, GLdouble blue ); + void ( QGL_DLLEXPORT *m_glColor3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glColor3f )( GLfloat red, GLfloat green, GLfloat blue ); + void ( QGL_DLLEXPORT *m_glColor3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glColor3i )( GLint red, GLint green, GLint blue ); + void ( QGL_DLLEXPORT *m_glColor3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glColor3s )( GLshort red, GLshort green, GLshort blue ); + void ( QGL_DLLEXPORT *m_glColor3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glColor3ub )( GLubyte red, GLubyte green, GLubyte blue ); + void ( QGL_DLLEXPORT *m_glColor3ubv )( const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glColor3ui )( GLuint red, GLuint green, GLuint blue ); + void ( QGL_DLLEXPORT *m_glColor3uiv )( const GLuint *v ); + void ( QGL_DLLEXPORT *m_glColor3us )( GLushort red, GLushort green, GLushort blue ); + void ( QGL_DLLEXPORT *m_glColor3usv )( const GLushort *v ); + void ( QGL_DLLEXPORT *m_glColor4b )( GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha ); + void ( QGL_DLLEXPORT *m_glColor4bv )( const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glColor4d )( GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha ); + void ( QGL_DLLEXPORT *m_glColor4dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glColor4f )( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha ); + void ( QGL_DLLEXPORT *m_glColor4fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glColor4i )( GLint red, GLint green, GLint blue, GLint alpha ); + void ( QGL_DLLEXPORT *m_glColor4iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glColor4s )( GLshort red, GLshort green, GLshort blue, GLshort alpha ); + void ( QGL_DLLEXPORT *m_glColor4sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glColor4ub )( GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha ); + void ( QGL_DLLEXPORT *m_glColor4ubv )( const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glColor4ui )( GLuint red, GLuint green, GLuint blue, GLuint alpha ); + void ( QGL_DLLEXPORT *m_glColor4uiv )( const GLuint *v ); + void ( QGL_DLLEXPORT *m_glColor4us )( GLushort red, GLushort green, GLushort blue, GLushort alpha ); + void ( QGL_DLLEXPORT *m_glColor4usv )( const GLushort *v ); + void ( QGL_DLLEXPORT *m_glColorMask )( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha ); + void ( QGL_DLLEXPORT *m_glColorMaterial )( GLenum face, GLenum mode ); + void ( QGL_DLLEXPORT *m_glColorPointer )( GLint size, GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glCopyPixels )( GLint x, GLint y, GLsizei width, GLsizei height, GLenum type ); + void ( QGL_DLLEXPORT *m_glCopyTexImage1D )( GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border ); + void ( QGL_DLLEXPORT *m_glCopyTexImage2D )( GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border ); + void ( QGL_DLLEXPORT *m_glCopyTexSubImage1D )( GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width ); + void ( QGL_DLLEXPORT *m_glCopyTexSubImage2D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height ); + void ( QGL_DLLEXPORT *m_glCullFace )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glDeleteLists )( GLuint list, GLsizei range ); + void ( QGL_DLLEXPORT *m_glDeleteTextures )( GLsizei n, const GLuint *textures ); + void ( QGL_DLLEXPORT *m_glDepthFunc )( GLenum func ); + void ( QGL_DLLEXPORT *m_glDepthMask )( GLboolean flag ); + void ( QGL_DLLEXPORT *m_glDepthRange )( GLclampd zNear, GLclampd zFar ); + void ( QGL_DLLEXPORT *m_glDisable )( GLenum cap ); + void ( QGL_DLLEXPORT *m_glDisableClientState )( GLenum array ); + void ( QGL_DLLEXPORT *m_glDrawArrays )( GLenum mode, GLint first, GLsizei count ); + void ( QGL_DLLEXPORT *m_glDrawBuffer )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glDrawElements )( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ); + void ( QGL_DLLEXPORT *m_glDrawPixels )( GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glEdgeFlag )( GLboolean flag ); + void ( QGL_DLLEXPORT *m_glEdgeFlagPointer )( GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glEdgeFlagv )( const GLboolean *flag ); + void ( QGL_DLLEXPORT *m_glEnable )( GLenum cap ); + void ( QGL_DLLEXPORT *m_glEnableClientState )( GLenum array ); + void ( QGL_DLLEXPORT *m_glEnd )( void ); + void ( QGL_DLLEXPORT *m_glEndList )( void ); + void ( QGL_DLLEXPORT *m_glEvalCoord1d )( GLdouble u ); + void ( QGL_DLLEXPORT *m_glEvalCoord1dv )( const GLdouble *u ); + void ( QGL_DLLEXPORT *m_glEvalCoord1f )( GLfloat u ); + void ( QGL_DLLEXPORT *m_glEvalCoord1fv )( const GLfloat *u ); + void ( QGL_DLLEXPORT *m_glEvalCoord2d )( GLdouble u, GLdouble v ); + void ( QGL_DLLEXPORT *m_glEvalCoord2dv )( const GLdouble *u ); + void ( QGL_DLLEXPORT *m_glEvalCoord2f )( GLfloat u, GLfloat v ); + void ( QGL_DLLEXPORT *m_glEvalCoord2fv )( const GLfloat *u ); + void ( QGL_DLLEXPORT *m_glEvalMesh1 )( GLenum mode, GLint i1, GLint i2 ); + void ( QGL_DLLEXPORT *m_glEvalMesh2 )( GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2 ); + void ( QGL_DLLEXPORT *m_glEvalPoint1 )( GLint i ); + void ( QGL_DLLEXPORT *m_glEvalPoint2 )( GLint i, GLint j ); + void ( QGL_DLLEXPORT *m_glFeedbackBuffer )( GLsizei size, GLenum type, GLfloat *buffer ); + void ( QGL_DLLEXPORT *m_glFinish )( void ); + void ( QGL_DLLEXPORT *m_glFlush )( void ); + void ( QGL_DLLEXPORT *m_glFogf )( GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glFogfv )( GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glFogi )( GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glFogiv )( GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glFrontFace )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glFrustum )( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar ); + GLuint ( QGL_DLLEXPORT *m_glGenLists )( GLsizei range ); + void ( QGL_DLLEXPORT *m_glGenTextures )( GLsizei n, GLuint *textures ); + void ( QGL_DLLEXPORT *m_glGetBooleanv )( GLenum pname, GLboolean *params ); + void ( QGL_DLLEXPORT *m_glGetClipPlane )( GLenum plane, GLdouble *equation ); + void ( QGL_DLLEXPORT *m_glGetDoublev )( GLenum pname, GLdouble *params ); + GLenum ( QGL_DLLEXPORT *m_glGetError )( void ); + void ( QGL_DLLEXPORT *m_glGetFloatv )( GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetIntegerv )( GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetLightfv )( GLenum light, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetLightiv )( GLenum light, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetMapdv )( GLenum target, GLenum query, GLdouble *v ); + void ( QGL_DLLEXPORT *m_glGetMapfv )( GLenum target, GLenum query, GLfloat *v ); + void ( QGL_DLLEXPORT *m_glGetMapiv )( GLenum target, GLenum query, GLint *v ); + void ( QGL_DLLEXPORT *m_glGetMaterialfv )( GLenum face, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetMaterialiv )( GLenum face, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetPixelMapfv )( GLenum map, GLfloat *values ); + void ( QGL_DLLEXPORT *m_glGetPixelMapuiv )( GLenum map, GLuint *values ); + void ( QGL_DLLEXPORT *m_glGetPixelMapusv )( GLenum map, GLushort *values ); + void ( QGL_DLLEXPORT *m_glGetPointerv )( GLenum pname, GLvoid* *params ); + void ( QGL_DLLEXPORT *m_glGetPolygonStipple )( GLubyte *mask ); + const GLubyte * ( QGL_DLLEXPORT * m_glGetString )(GLenum name); + void ( QGL_DLLEXPORT *m_glGetTexEnvfv )( GLenum target, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetTexEnviv )( GLenum target, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetTexGendv )( GLenum coord, GLenum pname, GLdouble *params ); + void ( QGL_DLLEXPORT *m_glGetTexGenfv )( GLenum coord, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetTexGeniv )( GLenum coord, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetTexImage )( GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glGetTexLevelParameterfv )( GLenum target, GLint level, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetTexLevelParameteriv )( GLenum target, GLint level, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetTexParameterfv )( GLenum target, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetTexParameteriv )( GLenum target, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glHint )( GLenum target, GLenum mode ); + void ( QGL_DLLEXPORT *m_glIndexMask )( GLuint mask ); + void ( QGL_DLLEXPORT *m_glIndexPointer )( GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glIndexd )( GLdouble c ); + void ( QGL_DLLEXPORT *m_glIndexdv )( const GLdouble *c ); + void ( QGL_DLLEXPORT *m_glIndexf )( GLfloat c ); + void ( QGL_DLLEXPORT *m_glIndexfv )( const GLfloat *c ); + void ( QGL_DLLEXPORT *m_glIndexi )( GLint c ); + void ( QGL_DLLEXPORT *m_glIndexiv )( const GLint *c ); + void ( QGL_DLLEXPORT *m_glIndexs )( GLshort c ); + void ( QGL_DLLEXPORT *m_glIndexsv )( const GLshort *c ); + void ( QGL_DLLEXPORT *m_glIndexub )( GLubyte c ); + void ( QGL_DLLEXPORT *m_glIndexubv )( const GLubyte *c ); + void ( QGL_DLLEXPORT *m_glInitNames )( void ); + void ( QGL_DLLEXPORT *m_glInterleavedArrays )( GLenum format, GLsizei stride, const GLvoid *pointer ); + GLboolean ( QGL_DLLEXPORT *m_glIsEnabled )( GLenum cap ); + GLboolean ( QGL_DLLEXPORT *m_glIsList )( GLuint list ); + GLboolean ( QGL_DLLEXPORT *m_glIsTexture )( GLuint texture ); + void ( QGL_DLLEXPORT *m_glLightModelf )( GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glLightModelfv )( GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glLightModeli )( GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glLightModeliv )( GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glLightf )( GLenum light, GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glLightfv )( GLenum light, GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glLighti )( GLenum light, GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glLightiv )( GLenum light, GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glLineStipple )( GLint factor, GLushort pattern ); + void ( QGL_DLLEXPORT *m_glLineWidth )( GLfloat width ); + void ( QGL_DLLEXPORT *m_glListBase )( GLuint base ); + void ( QGL_DLLEXPORT *m_glLoadIdentity )( void ); + void ( QGL_DLLEXPORT *m_glLoadMatrixd )( const GLdouble *m ); + void ( QGL_DLLEXPORT *m_glLoadMatrixf )( const GLfloat *m ); + void ( QGL_DLLEXPORT *m_glLoadName )( GLuint name ); + void ( QGL_DLLEXPORT *m_glLogicOp )( GLenum opcode ); + void ( QGL_DLLEXPORT *m_glMap1d )( GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points ); + void ( QGL_DLLEXPORT *m_glMap1f )( GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points ); + void ( QGL_DLLEXPORT *m_glMap2d )( GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points ); + void ( QGL_DLLEXPORT *m_glMap2f )( GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points ); + void ( QGL_DLLEXPORT *m_glMapGrid1d )( GLint un, GLdouble u1, GLdouble u2 ); + void ( QGL_DLLEXPORT *m_glMapGrid1f )( GLint un, GLfloat u1, GLfloat u2 ); + void ( QGL_DLLEXPORT *m_glMapGrid2d )( GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2 ); + void ( QGL_DLLEXPORT *m_glMapGrid2f )( GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2 ); + void ( QGL_DLLEXPORT *m_glMaterialf )( GLenum face, GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glMaterialfv )( GLenum face, GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glMateriali )( GLenum face, GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glMaterialiv )( GLenum face, GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glMatrixMode )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glMultMatrixd )( const GLdouble *m ); + void ( QGL_DLLEXPORT *m_glMultMatrixf )( const GLfloat *m ); + void ( QGL_DLLEXPORT *m_glNewList )( GLuint list, GLenum mode ); + void ( QGL_DLLEXPORT *m_glNormal3b )( GLbyte nx, GLbyte ny, GLbyte nz ); + void ( QGL_DLLEXPORT *m_glNormal3bv )( const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glNormal3d )( GLdouble nx, GLdouble ny, GLdouble nz ); + void ( QGL_DLLEXPORT *m_glNormal3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glNormal3f )( GLfloat nx, GLfloat ny, GLfloat nz ); + void ( QGL_DLLEXPORT *m_glNormal3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glNormal3i )( GLint nx, GLint ny, GLint nz ); + void ( QGL_DLLEXPORT *m_glNormal3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glNormal3s )( GLshort nx, GLshort ny, GLshort nz ); + void ( QGL_DLLEXPORT *m_glNormal3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glNormalPointer )( GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glOrtho )( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar ); + void ( QGL_DLLEXPORT *m_glPassThrough )( GLfloat token ); + void ( QGL_DLLEXPORT *m_glPixelMapfv )( GLenum map, GLsizei mapsize, const GLfloat *values ); + void ( QGL_DLLEXPORT *m_glPixelMapuiv )( GLenum map, GLsizei mapsize, const GLuint *values ); + void ( QGL_DLLEXPORT *m_glPixelMapusv )( GLenum map, GLsizei mapsize, const GLushort *values ); + void ( QGL_DLLEXPORT *m_glPixelStoref )( GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glPixelStorei )( GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glPixelTransferf )( GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glPixelTransferi )( GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glPixelZoom )( GLfloat xfactor, GLfloat yfactor ); + void ( QGL_DLLEXPORT *m_glPointSize )( GLfloat size ); + void ( QGL_DLLEXPORT *m_glPolygonMode )( GLenum face, GLenum mode ); + void ( QGL_DLLEXPORT *m_glPolygonOffset )( GLfloat factor, GLfloat units ); + void ( QGL_DLLEXPORT *m_glPolygonStipple )( const GLubyte *mask ); + void ( QGL_DLLEXPORT *m_glPopAttrib )( void ); + void ( QGL_DLLEXPORT *m_glPopClientAttrib )( void ); + void ( QGL_DLLEXPORT *m_glPopMatrix )( void ); + void ( QGL_DLLEXPORT *m_glPopName )( void ); + void ( QGL_DLLEXPORT *m_glPrioritizeTextures )( GLsizei n, const GLuint *textures, const GLclampf *priorities ); + void ( QGL_DLLEXPORT *m_glPushAttrib )( GLbitfield mask ); + void ( QGL_DLLEXPORT *m_glPushClientAttrib )( GLbitfield mask ); + void ( QGL_DLLEXPORT *m_glPushMatrix )( void ); + void ( QGL_DLLEXPORT *m_glPushName )( GLuint name ); + void ( QGL_DLLEXPORT *m_glRasterPos2d )( GLdouble x, GLdouble y ); + void ( QGL_DLLEXPORT *m_glRasterPos2dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glRasterPos2f )( GLfloat x, GLfloat y ); + void ( QGL_DLLEXPORT *m_glRasterPos2fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glRasterPos2i )( GLint x, GLint y ); + void ( QGL_DLLEXPORT *m_glRasterPos2iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glRasterPos2s )( GLshort x, GLshort y ); + void ( QGL_DLLEXPORT *m_glRasterPos2sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glRasterPos3d )( GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glRasterPos3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glRasterPos3f )( GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glRasterPos3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glRasterPos3i )( GLint x, GLint y, GLint z ); + void ( QGL_DLLEXPORT *m_glRasterPos3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glRasterPos3s )( GLshort x, GLshort y, GLshort z ); + void ( QGL_DLLEXPORT *m_glRasterPos3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glRasterPos4d )( GLdouble x, GLdouble y, GLdouble z, GLdouble w ); + void ( QGL_DLLEXPORT *m_glRasterPos4dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glRasterPos4f )( GLfloat x, GLfloat y, GLfloat z, GLfloat w ); + void ( QGL_DLLEXPORT *m_glRasterPos4fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glRasterPos4i )( GLint x, GLint y, GLint z, GLint w ); + void ( QGL_DLLEXPORT *m_glRasterPos4iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glRasterPos4s )( GLshort x, GLshort y, GLshort z, GLshort w ); + void ( QGL_DLLEXPORT *m_glRasterPos4sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glReadBuffer )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glReadPixels )( GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glRectd )( GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2 ); + void ( QGL_DLLEXPORT *m_glRectdv )( const GLdouble *v1, const GLdouble *v2 ); + void ( QGL_DLLEXPORT *m_glRectf )( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ); + void ( QGL_DLLEXPORT *m_glRectfv )( const GLfloat *v1, const GLfloat *v2 ); + void ( QGL_DLLEXPORT *m_glRecti )( GLint x1, GLint y1, GLint x2, GLint y2 ); + void ( QGL_DLLEXPORT *m_glRectiv )( const GLint *v1, const GLint *v2 ); + void ( QGL_DLLEXPORT *m_glRects )( GLshort x1, GLshort y1, GLshort x2, GLshort y2 ); + void ( QGL_DLLEXPORT *m_glRectsv )( const GLshort *v1, const GLshort *v2 ); + GLint ( QGL_DLLEXPORT *m_glRenderMode )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glRotated )( GLdouble anm_gle, GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glRotatef )( GLfloat anm_gle, GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glScaled )( GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glScalef )( GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glScissor )( GLint x, GLint y, GLsizei width, GLsizei height ); + void ( QGL_DLLEXPORT *m_glSelectBuffer )( GLsizei size, GLuint *buffer ); + void ( QGL_DLLEXPORT *m_glShadeModel )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glStencilFunc )( GLenum func, GLint ref, GLuint mask ); + void ( QGL_DLLEXPORT *m_glStencilMask )( GLuint mask ); + void ( QGL_DLLEXPORT *m_glStencilOp )( GLenum fail, GLenum zfail, GLenum zpass ); + void ( QGL_DLLEXPORT *m_glTexCoord1d )( GLdouble s ); + void ( QGL_DLLEXPORT *m_glTexCoord1dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glTexCoord1f )( GLfloat s ); + void ( QGL_DLLEXPORT *m_glTexCoord1fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glTexCoord1i )( GLint s ); + void ( QGL_DLLEXPORT *m_glTexCoord1iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glTexCoord1s )( GLshort s ); + void ( QGL_DLLEXPORT *m_glTexCoord1sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glTexCoord2d )( GLdouble s, GLdouble t ); + void ( QGL_DLLEXPORT *m_glTexCoord2dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glTexCoord2f )( GLfloat s, GLfloat t ); + void ( QGL_DLLEXPORT *m_glTexCoord2fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glTexCoord2i )( GLint s, GLint t ); + void ( QGL_DLLEXPORT *m_glTexCoord2iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glTexCoord2s )( GLshort s, GLshort t ); + void ( QGL_DLLEXPORT *m_glTexCoord2sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glTexCoord3d )( GLdouble s, GLdouble t, GLdouble r ); + void ( QGL_DLLEXPORT *m_glTexCoord3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glTexCoord3f )( GLfloat s, GLfloat t, GLfloat r ); + void ( QGL_DLLEXPORT *m_glTexCoord3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glTexCoord3i )( GLint s, GLint t, GLint r ); + void ( QGL_DLLEXPORT *m_glTexCoord3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glTexCoord3s )( GLshort s, GLshort t, GLshort r ); + void ( QGL_DLLEXPORT *m_glTexCoord3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glTexCoord4d )( GLdouble s, GLdouble t, GLdouble r, GLdouble q ); + void ( QGL_DLLEXPORT *m_glTexCoord4dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glTexCoord4f )( GLfloat s, GLfloat t, GLfloat r, GLfloat q ); + void ( QGL_DLLEXPORT *m_glTexCoord4fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glTexCoord4i )( GLint s, GLint t, GLint r, GLint q ); + void ( QGL_DLLEXPORT *m_glTexCoord4iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glTexCoord4s )( GLshort s, GLshort t, GLshort r, GLshort q ); + void ( QGL_DLLEXPORT *m_glTexCoord4sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glTexCoordPointer )( GLint size, GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glTexEnvf )( GLenum target, GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glTexEnvfv )( GLenum target, GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glTexEnvi )( GLenum target, GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glTexEnviv )( GLenum target, GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glTexGend )( GLenum coord, GLenum pname, GLdouble param ); + void ( QGL_DLLEXPORT *m_glTexGendv )( GLenum coord, GLenum pname, const GLdouble *params ); + void ( QGL_DLLEXPORT *m_glTexGenf )( GLenum coord, GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glTexGenfv )( GLenum coord, GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glTexGeni )( GLenum coord, GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glTexGeniv )( GLenum coord, GLenum pname, const GLint *params ); +#if defined( MACVERSION ) && MACVERSION > 15 + //Snow Leopard 16, Leopard 15, Tiger 14, Panther 13, ... + void ( QGL_DLLEXPORT *m_glTexImage1D )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glTexImage2D )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); #else - void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + void ( QGL_DLLEXPORT *m_glTexImage1D )( GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glTexImage2D )( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); #endif - void (QGL_DLLEXPORT *m_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexParameteri)(GLenum target, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexParameteriv)(GLenum target, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTranslated)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glTranslatef)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertex2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glVertex2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glVertex2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glVertex2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glVertex2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertex3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glVertex3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertex3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glVertex3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glVertex3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertex4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glVertex4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glVertex4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex4i)(GLint x, GLint y, GLint z, GLint w); - void (QGL_DLLEXPORT *m_glVertex4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex4s)(GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glVertex4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); - - // GL_ARB_multitexture - bool support_ARB_multitexture; - bool ARB_multitexture() - { - return support_ARB_multitexture; - } - void (QGL_DLLEXPORT *m_glActiveTextureARB)(GLenum texture); - void (QGL_DLLEXPORT *m_glClientActiveTextureARB)(GLenum texture); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4svARB)(GLenum target, const GLshort *v); - - // ARB_texture_compression - bool support_ARB_texture_compression; - bool ARB_texture_compression() - { - return support_ARB_texture_compression; - } - void (QGL_DLLEXPORT *m_glCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glGetCompressedTexImageARB)(GLenum target, GLint lod, GLvoid* img); - - // EXT_texture_compression_s3tc - bool support_EXT_texture_compression_s3tc; - bool EXT_texture_compression_s3tc() - { - return support_EXT_texture_compression_s3tc; - } - - // GL 1.2 - bool support_GL_1_2; - bool GL_1_2() - { - return support_GL_1_2; - } - void (QGL_DLLEXPORT *m_glCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glDrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); - void (QGL_DLLEXPORT *m_glTexImage3D)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); - - // GL 1.3 - bool support_GL_1_3; - bool GL_1_3() - { - return support_GL_1_3; - } - void (QGL_DLLEXPORT *m_glActiveTexture)(GLenum texture); - void (QGL_DLLEXPORT *m_glClientActiveTexture)(GLenum texture); - void (QGL_DLLEXPORT *m_glCompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glGetCompressedTexImage)(GLenum target, GLint lod, GLvoid *img); - void (QGL_DLLEXPORT *m_glLoadTransposeMatrixd)(const GLdouble m[16]); - void (QGL_DLLEXPORT *m_glLoadTransposeMatrixf)(const GLfloat m[16]); - void (QGL_DLLEXPORT *m_glMultTransposeMatrixd)(const GLdouble m[16]); - void (QGL_DLLEXPORT *m_glMultTransposeMatrixf)(const GLfloat m[16]); - void (QGL_DLLEXPORT *m_glMultiTexCoord1d)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1f)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1i)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1s)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2i)(GLenum target, GLint s, GLint t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glSampleCoverage)(GLclampf value, GLboolean invert); - - // GL 1.4 - bool support_GL_1_4; - bool GL_1_4() - { - return support_GL_1_4; - } - void (QGL_DLLEXPORT *m_glBlendColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - void (QGL_DLLEXPORT *m_glBlendEquation)(GLenum mode); - void (QGL_DLLEXPORT *m_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); - void (QGL_DLLEXPORT *m_glFogCoordPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glFogCoordd)(GLdouble coord); - void (QGL_DLLEXPORT *m_glFogCoorddv)(const GLdouble *coord); - void (QGL_DLLEXPORT *m_glFogCoordf)(GLfloat coord); - void (QGL_DLLEXPORT *m_glFogCoordfv)(const GLfloat *coord); - void (QGL_DLLEXPORT *m_glMultiDrawArrays)(GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); - void (QGL_DLLEXPORT *m_glMultiDrawElements)(GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount); - void (QGL_DLLEXPORT *m_glPointParameterf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPointParameterfv)(GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glSecondaryColor3b)(GLbyte red, GLbyte green, GLbyte blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3d)(GLdouble red, GLdouble green, GLdouble blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3f)(GLfloat red, GLfloat green, GLfloat blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3i)(GLint red, GLint green, GLint blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3s)(GLshort red, GLshort green, GLshort blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3ub)(GLubyte red, GLubyte green, GLubyte blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3ui)(GLuint red, GLuint green, GLuint blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3us)(GLushort red, GLushort green, GLushort blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glSecondaryColorPointer)(GLint size, GLenum type, GLsizei stride, GLvoid *pointer); - void (QGL_DLLEXPORT *m_glWindowPos2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glWindowPos2dv)(const GLdouble *p); - void (QGL_DLLEXPORT *m_glWindowPos2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glWindowPos2fv)(const GLfloat *p); - void (QGL_DLLEXPORT *m_glWindowPos2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glWindowPos2iv)(const GLint *p); - void (QGL_DLLEXPORT *m_glWindowPos2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glWindowPos2sv)(const GLshort *p); - void (QGL_DLLEXPORT *m_glWindowPos3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glWindowPos3dv)(const GLdouble *p); - void (QGL_DLLEXPORT *m_glWindowPos3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glWindowPos3fv)(const GLfloat *p); - void (QGL_DLLEXPORT *m_glWindowPos3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glWindowPos3iv)(const GLint *p); - void (QGL_DLLEXPORT *m_glWindowPos3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glWindowPos3sv)(const GLshort *p); - - // GL 1.5 - bool support_GL_1_5; - bool GL_1_5() - { - return support_GL_1_5; - } - void (QGL_DLLEXPORT *m_glBeginQuery)(GLenum target, GLuint id); - void (QGL_DLLEXPORT *m_glBindBuffer)(GLenum target, GLuint buffer); - void (QGL_DLLEXPORT *m_glBufferData)(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); - void (QGL_DLLEXPORT *m_glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); - void (QGL_DLLEXPORT *m_glDeleteBuffers)(GLsizei n, const GLuint* buffers); - void (QGL_DLLEXPORT *m_glDeleteQueries)(GLsizei n, const GLuint* ids); - void (QGL_DLLEXPORT *m_glEndQuery)(GLenum target); - void (QGL_DLLEXPORT *m_glGenBuffers)(GLsizei n, GLuint* buffers); - void (QGL_DLLEXPORT *m_glGenQueries)(GLsizei n, GLuint* ids); - void (QGL_DLLEXPORT *m_glGetBufferParameteriv)(GLenum target, GLenum pname, GLint* params); - void (QGL_DLLEXPORT *m_glGetBufferPointerv)(GLenum target, GLenum pname, GLvoid** params); - void (QGL_DLLEXPORT *m_glGetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data); - void (QGL_DLLEXPORT *m_glGetQueryObjectiv)(GLuint id, GLenum pname, GLint* params); - void (QGL_DLLEXPORT *m_glGetQueryObjectuiv)(GLuint id, GLenum pname, GLuint* params); - void (QGL_DLLEXPORT *m_glGetQueryiv)(GLenum target, GLenum pname, GLint params); - GLboolean (QGL_DLLEXPORT *m_glIsBuffer)(GLuint buffer); - GLboolean (QGL_DLLEXPORT *m_glIsQuery)(GLuint id); - GLvoid* (QGL_DLLEXPORT *m_glMapBuffer)(GLenum target, GLenum access); - GLboolean (QGL_DLLEXPORT *m_glUnmapBuffer)(GLenum target); - - // GL_ARB_vertex_program - bool support_ARB_vertex_program; - bool ARB_vertex_program() - { - return support_ARB_vertex_program; - } - void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort x); - void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat x); - void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble x); - void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); - void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glProgramStringARB)(GLenum target, GLenum format, GLsizei len, const GLvoid *string); - void (QGL_DLLEXPORT *m_glBindProgramARB)(GLenum target, GLuint program); - void (QGL_DLLEXPORT *m_glDeleteProgramsARB)(GLsizei n, const GLuint *programs); - void (QGL_DLLEXPORT *m_glGenProgramsARB)(GLsizei n, GLuint *programs); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramEnvParameterdvARB)(GLenum target, GLuint index, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetProgramEnvParameterfvARB)(GLenum target, GLuint index, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramLocalParameterdvARB)(GLenum target, GLuint index, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetProgramLocalParameterfvARB)(GLenum target, GLuint index, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramivARB)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetProgramStringARB)(GLenum target, GLenum pname, GLvoid *string); - void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); - GLboolean (QGL_DLLEXPORT *m_glIsProgramARB)(GLuint program); - - // GL_ARB_fragment_program - bool support_ARB_fragment_program; - bool ARB_fragment_program() - { - return support_ARB_fragment_program; - } - - // GL_ARB_shader_objects - bool support_ARB_shader_objects; - bool ARB_shader_objects() - { - return support_ARB_shader_objects; - } - void (QGL_DLLEXPORT *m_glDeleteObjectARB)(GLhandleARB obj); - GLhandleARB (QGL_DLLEXPORT *m_glGetHandleARB)(GLenum pname); - void (QGL_DLLEXPORT *m_glDetachObjectARB)(GLhandleARB containerObj, GLhandleARB attachedObj); - GLhandleARB (QGL_DLLEXPORT *m_glCreateShaderObjectARB)(GLenum shaderType); - void (QGL_DLLEXPORT *m_glShaderSourceARB)(GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); - void (QGL_DLLEXPORT *m_glCompileShaderARB)(GLhandleARB shaderObj); - GLhandleARB (QGL_DLLEXPORT *m_glCreateProgramObjectARB)(void); - void (QGL_DLLEXPORT *m_glAttachObjectARB)(GLhandleARB containerObj, GLhandleARB obj); - void (QGL_DLLEXPORT *m_glLinkProgramARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glUseProgramObjectARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glValidateProgramARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glUniform1fARB)(GLint location, GLfloat v0); - void (QGL_DLLEXPORT *m_glUniform2fARB)(GLint location, GLfloat v0, GLfloat v1); - void (QGL_DLLEXPORT *m_glUniform3fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glUniform4fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); - void (QGL_DLLEXPORT *m_glUniform1iARB)(GLint location, GLint v0); - void (QGL_DLLEXPORT *m_glUniform2iARB)(GLint location, GLint v0, GLint v1); - void (QGL_DLLEXPORT *m_glUniform3iARB)(GLint location, GLint v0, GLint v1, GLint v2); - void (QGL_DLLEXPORT *m_glUniform4iARB)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); - void (QGL_DLLEXPORT *m_glUniform1fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform2fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform3fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform4fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform1ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform2ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform3ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform4ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniformMatrix2fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniformMatrix3fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniformMatrix4fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glGetObjectParameterfvARB)(GLhandleARB obj, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetObjectParameterivARB)(GLhandleARB obj, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetInfoLogARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); - void (QGL_DLLEXPORT *m_glGetAttachedObjectsARB)(GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); - GLint (QGL_DLLEXPORT *m_glGetUniformLocationARB)(GLhandleARB programObj, const GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetActiveUniformARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetUniformfvARB)(GLhandleARB programObj, GLint location, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetUniformivARB)(GLhandleARB programObj, GLint location, GLint *params); - void (QGL_DLLEXPORT *m_glGetShaderSourceARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); - - // GL_ARB_vertex_shader - bool support_ARB_vertex_shader; - bool ARB_vertex_shader() - { - return support_ARB_vertex_shader; - } + void ( QGL_DLLEXPORT *m_glTexParameterf )( GLenum target, GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glTexParameterfv )( GLenum target, GLenum pname, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glTexParameteri )( GLenum target, GLenum pname, GLint param ); + void ( QGL_DLLEXPORT *m_glTexParameteriv )( GLenum target, GLenum pname, const GLint *params ); + void ( QGL_DLLEXPORT *m_glTexSubImage1D )( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glTexSubImage2D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glTranslated )( GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glTranslatef )( GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glVertex2d )( GLdouble x, GLdouble y ); + void ( QGL_DLLEXPORT *m_glVertex2dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertex2f )( GLfloat x, GLfloat y ); + void ( QGL_DLLEXPORT *m_glVertex2fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertex2i )( GLint x, GLint y ); + void ( QGL_DLLEXPORT *m_glVertex2iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertex2s )( GLshort x, GLshort y ); + void ( QGL_DLLEXPORT *m_glVertex2sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertex3d )( GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glVertex3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertex3f )( GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glVertex3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertex3i )( GLint x, GLint y, GLint z ); + void ( QGL_DLLEXPORT *m_glVertex3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertex3s )( GLshort x, GLshort y, GLshort z ); + void ( QGL_DLLEXPORT *m_glVertex3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertex4d )( GLdouble x, GLdouble y, GLdouble z, GLdouble w ); + void ( QGL_DLLEXPORT *m_glVertex4dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertex4f )( GLfloat x, GLfloat y, GLfloat z, GLfloat w ); + void ( QGL_DLLEXPORT *m_glVertex4fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertex4i )( GLint x, GLint y, GLint z, GLint w ); + void ( QGL_DLLEXPORT *m_glVertex4iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertex4s )( GLshort x, GLshort y, GLshort z, GLshort w ); + void ( QGL_DLLEXPORT *m_glVertex4sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexPointer )( GLint size, GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glViewport )( GLint x, GLint y, GLsizei width, GLsizei height ); + + // GL_ARB_multitexture + bool support_ARB_multitexture; + bool ARB_multitexture(){ + return support_ARB_multitexture; + } + void ( QGL_DLLEXPORT *m_glActiveTextureARB )( GLenum texture ); + void ( QGL_DLLEXPORT *m_glClientActiveTextureARB )( GLenum texture ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1dARB )( GLenum target, GLdouble s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1dvARB )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1fARB )( GLenum target, GLfloat s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1fvARB )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1iARB )( GLenum target, GLint s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1ivARB )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1sARB )( GLenum target, GLshort s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1svARB )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2dARB )( GLenum target, GLdouble s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2dvARB )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2fARB )( GLenum target, GLfloat s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2fvARB )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2iARB )( GLenum target, GLint s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2ivARB )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2sARB )( GLenum target, GLshort s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2svARB )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3dARB )( GLenum target, GLdouble s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3dvARB )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3fARB )( GLenum target, GLfloat s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3fvARB )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3iARB )( GLenum target, GLint s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3ivARB )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3sARB )( GLenum target, GLshort s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3svARB )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4dARB )( GLenum target, GLdouble s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4dvARB )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4fARB )( GLenum target, GLfloat s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4fvARB )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4iARB )( GLenum target, GLint s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4ivARB )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4sARB )( GLenum target, GLshort s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4svARB )( GLenum target, const GLshort *v ); + + // ARB_texture_compression + bool support_ARB_texture_compression; + bool ARB_texture_compression(){ + return support_ARB_texture_compression; + } + void ( QGL_DLLEXPORT *m_glCompressedTexImage3DARB )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glCompressedTexImage2DARB )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glCompressedTexImage1DARB )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage3DARB )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage2DARB )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage1DARB )( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glGetCompressedTexImageARB )( GLenum target, GLint lod, GLvoid* img ); + + // EXT_texture_compression_s3tc + bool support_EXT_texture_compression_s3tc; + bool EXT_texture_compression_s3tc(){ + return support_EXT_texture_compression_s3tc; + } + + // GL 1.2 + bool support_GL_1_2; + bool GL_1_2(){ + return support_GL_1_2; + } + void ( QGL_DLLEXPORT *m_glCopyTexSubImage3D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ); + void ( QGL_DLLEXPORT *m_glDrawRangeElements )( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices ); + void ( QGL_DLLEXPORT *m_glTexImage3D )( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); + void ( QGL_DLLEXPORT *m_glTexSubImage3D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels ); + + // GL 1.3 + bool support_GL_1_3; + bool GL_1_3(){ + return support_GL_1_3; + } + void ( QGL_DLLEXPORT *m_glActiveTexture )( GLenum texture ); + void ( QGL_DLLEXPORT *m_glClientActiveTexture )( GLenum texture ); + void ( QGL_DLLEXPORT *m_glCompressedTexImage1D )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glCompressedTexImage2D )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glCompressedTexImage3D )( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage1D )( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage2D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glCompressedTexSubImage3D )( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data ); + void ( QGL_DLLEXPORT *m_glGetCompressedTexImage )( GLenum target, GLint lod, GLvoid *img ); + void ( QGL_DLLEXPORT *m_glLoadTransposeMatrixd )( const GLdouble m[16] ); + void ( QGL_DLLEXPORT *m_glLoadTransposeMatrixf )( const GLfloat m[16] ); + void ( QGL_DLLEXPORT *m_glMultTransposeMatrixd )( const GLdouble m[16] ); + void ( QGL_DLLEXPORT *m_glMultTransposeMatrixf )( const GLfloat m[16] ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1d )( GLenum target, GLdouble s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1dv )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1f )( GLenum target, GLfloat s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1fv )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1i )( GLenum target, GLint s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1iv )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1s )( GLenum target, GLshort s ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord1sv )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2d )( GLenum target, GLdouble s, GLdouble t ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2dv )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2f )( GLenum target, GLfloat s, GLfloat t ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2fv )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2i )( GLenum target, GLint s, GLint t ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2iv )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2s )( GLenum target, GLshort s, GLshort t ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord2sv )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3d )( GLenum target, GLdouble s, GLdouble t, GLdouble r ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3dv )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3f )( GLenum target, GLfloat s, GLfloat t, GLfloat r ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3fv )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3i )( GLenum target, GLint s, GLint t, GLint r ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3iv )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3s )( GLenum target, GLshort s, GLshort t, GLshort r ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord3sv )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4d )( GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4dv )( GLenum target, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4f )( GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4fv )( GLenum target, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4i )( GLenum target, GLint s, GLint t, GLint r, GLint q ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4iv )( GLenum target, const GLint *v ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4s )( GLenum target, GLshort s, GLshort t, GLshort r, GLshort q ); + void ( QGL_DLLEXPORT *m_glMultiTexCoord4sv )( GLenum target, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glSampleCoverage )( GLclampf value, GLboolean invert ); + + // GL 1.4 + bool support_GL_1_4; + bool GL_1_4(){ + return support_GL_1_4; + } + void ( QGL_DLLEXPORT *m_glBlendColor )( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha ); + void ( QGL_DLLEXPORT *m_glBlendEquation )( GLenum mode ); + void ( QGL_DLLEXPORT *m_glBlendFuncSeparate )( GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha ); + void ( QGL_DLLEXPORT *m_glFogCoordPointer )( GLenum type, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glFogCoordd )( GLdouble coord ); + void ( QGL_DLLEXPORT *m_glFogCoorddv )( const GLdouble *coord ); + void ( QGL_DLLEXPORT *m_glFogCoordf )( GLfloat coord ); + void ( QGL_DLLEXPORT *m_glFogCoordfv )( const GLfloat *coord ); + void ( QGL_DLLEXPORT *m_glMultiDrawArrays )( GLenum mode, GLint *first, GLsizei *count, GLsizei primcount ); + void ( QGL_DLLEXPORT *m_glMultiDrawElements )( GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount ); + void ( QGL_DLLEXPORT *m_glPointParameterf )( GLenum pname, GLfloat param ); + void ( QGL_DLLEXPORT *m_glPointParameterfv )( GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3b )( GLbyte red, GLbyte green, GLbyte blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3bv )( const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3d )( GLdouble red, GLdouble green, GLdouble blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3dv )( const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3f )( GLfloat red, GLfloat green, GLfloat blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3fv )( const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3i )( GLint red, GLint green, GLint blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3iv )( const GLint *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3s )( GLshort red, GLshort green, GLshort blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3sv )( const GLshort *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3ub )( GLubyte red, GLubyte green, GLubyte blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3ubv )( const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3ui )( GLuint red, GLuint green, GLuint blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3uiv )( const GLuint *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3us )( GLushort red, GLushort green, GLushort blue ); + void ( QGL_DLLEXPORT *m_glSecondaryColor3usv )( const GLushort *v ); + void ( QGL_DLLEXPORT *m_glSecondaryColorPointer )( GLint size, GLenum type, GLsizei stride, GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glWindowPos2d )( GLdouble x, GLdouble y ); + void ( QGL_DLLEXPORT *m_glWindowPos2dv )( const GLdouble *p ); + void ( QGL_DLLEXPORT *m_glWindowPos2f )( GLfloat x, GLfloat y ); + void ( QGL_DLLEXPORT *m_glWindowPos2fv )( const GLfloat *p ); + void ( QGL_DLLEXPORT *m_glWindowPos2i )( GLint x, GLint y ); + void ( QGL_DLLEXPORT *m_glWindowPos2iv )( const GLint *p ); + void ( QGL_DLLEXPORT *m_glWindowPos2s )( GLshort x, GLshort y ); + void ( QGL_DLLEXPORT *m_glWindowPos2sv )( const GLshort *p ); + void ( QGL_DLLEXPORT *m_glWindowPos3d )( GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glWindowPos3dv )( const GLdouble *p ); + void ( QGL_DLLEXPORT *m_glWindowPos3f )( GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glWindowPos3fv )( const GLfloat *p ); + void ( QGL_DLLEXPORT *m_glWindowPos3i )( GLint x, GLint y, GLint z ); + void ( QGL_DLLEXPORT *m_glWindowPos3iv )( const GLint *p ); + void ( QGL_DLLEXPORT *m_glWindowPos3s )( GLshort x, GLshort y, GLshort z ); + void ( QGL_DLLEXPORT *m_glWindowPos3sv )( const GLshort *p ); + + // GL 1.5 + bool support_GL_1_5; + bool GL_1_5(){ + return support_GL_1_5; + } + void ( QGL_DLLEXPORT *m_glBeginQuery )( GLenum target, GLuint id ); + void ( QGL_DLLEXPORT *m_glBindBuffer )( GLenum target, GLuint buffer ); + void ( QGL_DLLEXPORT *m_glBufferData )( GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage ); + void ( QGL_DLLEXPORT *m_glBufferSubData )( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data ); + void ( QGL_DLLEXPORT *m_glDeleteBuffers )( GLsizei n, const GLuint* buffers ); + void ( QGL_DLLEXPORT *m_glDeleteQueries )( GLsizei n, const GLuint* ids ); + void ( QGL_DLLEXPORT *m_glEndQuery )( GLenum target ); + void ( QGL_DLLEXPORT *m_glGenBuffers )( GLsizei n, GLuint* buffers ); + void ( QGL_DLLEXPORT *m_glGenQueries )( GLsizei n, GLuint* ids ); + void ( QGL_DLLEXPORT *m_glGetBufferParameteriv )( GLenum target, GLenum pname, GLint* params ); + void ( QGL_DLLEXPORT *m_glGetBufferPointerv )( GLenum target, GLenum pname, GLvoid** params ); + void ( QGL_DLLEXPORT *m_glGetBufferSubData )( GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data ); + void ( QGL_DLLEXPORT *m_glGetQueryObjectiv )( GLuint id, GLenum pname, GLint* params ); + void ( QGL_DLLEXPORT *m_glGetQueryObjectuiv )( GLuint id, GLenum pname, GLuint* params ); + void ( QGL_DLLEXPORT *m_glGetQueryiv )( GLenum target, GLenum pname, GLint params ); + GLboolean ( QGL_DLLEXPORT *m_glIsBuffer )( GLuint buffer ); + GLboolean ( QGL_DLLEXPORT *m_glIsQuery )( GLuint id ); + GLvoid* ( QGL_DLLEXPORT * m_glMapBuffer )( GLenum target, GLenum access ); + GLboolean ( QGL_DLLEXPORT *m_glUnmapBuffer )( GLenum target ); + + // GL_ARB_vertex_program + bool support_ARB_vertex_program; + bool ARB_vertex_program(){ + return support_ARB_vertex_program; + } + void ( QGL_DLLEXPORT *m_glVertexAttrib1sARB )( GLuint index, GLshort x ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1fARB )( GLuint index, GLfloat x ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1dARB )( GLuint index, GLdouble x ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2sARB )( GLuint index, GLshort x, GLshort y ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2fARB )( GLuint index, GLfloat x, GLfloat y ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2dARB )( GLuint index, GLdouble x, GLdouble y ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3sARB )( GLuint index, GLshort x, GLshort y, GLshort z ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3fARB )( GLuint index, GLfloat x, GLfloat y, GLfloat z ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3dARB )( GLuint index, GLdouble x, GLdouble y, GLdouble z ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4sARB )( GLuint index, GLshort x, GLshort y, GLshort z, GLshort w ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4fARB )( GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4dARB )( GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NubARB )( GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4bvARB )( GLuint index, const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4ivARB )( GLuint index, const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4ubvARB )( GLuint index, const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4usvARB )( GLuint index, const GLushort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4uivARB )( GLuint index, const GLuint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NbvARB )( GLuint index, const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NsvARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NivARB )( GLuint index, const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NubvARB )( GLuint index, const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NusvARB )( GLuint index, const GLushort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NuivARB )( GLuint index, const GLuint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttribPointerARB )( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB )( GLuint index ); + void ( QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB )( GLuint index ); + void ( QGL_DLLEXPORT *m_glProgramStringARB )( GLenum target, GLenum format, GLsizei len, const GLvoid *string ); + void ( QGL_DLLEXPORT *m_glBindProgramARB )( GLenum target, GLuint program ); + void ( QGL_DLLEXPORT *m_glDeleteProgramsARB )( GLsizei n, const GLuint *programs ); + void ( QGL_DLLEXPORT *m_glGenProgramsARB )( GLsizei n, GLuint *programs ); + void ( QGL_DLLEXPORT *m_glProgramEnvParameter4dARB )( GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w ); + void ( QGL_DLLEXPORT *m_glProgramEnvParameter4dvARB )( GLenum target, GLuint index, const GLdouble *params ); + void ( QGL_DLLEXPORT *m_glProgramEnvParameter4fARB )( GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w ); + void ( QGL_DLLEXPORT *m_glProgramEnvParameter4fvARB )( GLenum target, GLuint index, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glProgramLocalParameter4dARB )( GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w ); + void ( QGL_DLLEXPORT *m_glProgramLocalParameter4dvARB )( GLenum target, GLuint index, const GLdouble *params ); + void ( QGL_DLLEXPORT *m_glProgramLocalParameter4fARB )( GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w ); + void ( QGL_DLLEXPORT *m_glProgramLocalParameter4fvARB )( GLenum target, GLuint index, const GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetProgramEnvParameterdvARB )( GLenum target, GLuint index, GLdouble *params ); + void ( QGL_DLLEXPORT *m_glGetProgramEnvParameterfvARB )( GLenum target, GLuint index, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetProgramLocalParameterdvARB )( GLenum target, GLuint index, GLdouble *params ); + void ( QGL_DLLEXPORT *m_glGetProgramLocalParameterfvARB )( GLenum target, GLuint index, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetProgramivARB )( GLenum target, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetProgramStringARB )( GLenum target, GLenum pname, GLvoid *string ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribdvARB )( GLuint index, GLenum pname, GLdouble *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribfvARB )( GLuint index, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribivARB )( GLuint index, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribPointervARB )( GLuint index, GLenum pname, GLvoid **pointer ); + GLboolean ( QGL_DLLEXPORT *m_glIsProgramARB )( GLuint program ); + + // GL_ARB_fragment_program + bool support_ARB_fragment_program; + bool ARB_fragment_program(){ + return support_ARB_fragment_program; + } + + // GL_ARB_shader_objects + bool support_ARB_shader_objects; + bool ARB_shader_objects(){ + return support_ARB_shader_objects; + } + void ( QGL_DLLEXPORT *m_glDeleteObjectARB )( GLhandleARB obj ); + GLhandleARB ( QGL_DLLEXPORT *m_glGetHandleARB )( GLenum pname ); + void ( QGL_DLLEXPORT *m_glDetachObjectARB )( GLhandleARB containerObj, GLhandleARB attachedObj ); + GLhandleARB ( QGL_DLLEXPORT *m_glCreateShaderObjectARB )( GLenum shaderType ); + void ( QGL_DLLEXPORT *m_glShaderSourceARB )( GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length ); + void ( QGL_DLLEXPORT *m_glCompileShaderARB )( GLhandleARB shaderObj ); + GLhandleARB ( QGL_DLLEXPORT *m_glCreateProgramObjectARB )( void ); + void ( QGL_DLLEXPORT *m_glAttachObjectARB )( GLhandleARB containerObj, GLhandleARB obj ); + void ( QGL_DLLEXPORT *m_glLinkProgramARB )( GLhandleARB programObj ); + void ( QGL_DLLEXPORT *m_glUseProgramObjectARB )( GLhandleARB programObj ); + void ( QGL_DLLEXPORT *m_glValidateProgramARB )( GLhandleARB programObj ); + void ( QGL_DLLEXPORT *m_glUniform1fARB )( GLint location, GLfloat v0 ); + void ( QGL_DLLEXPORT *m_glUniform2fARB )( GLint location, GLfloat v0, GLfloat v1 ); + void ( QGL_DLLEXPORT *m_glUniform3fARB )( GLint location, GLfloat v0, GLfloat v1, GLfloat v2 ); + void ( QGL_DLLEXPORT *m_glUniform4fARB )( GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3 ); + void ( QGL_DLLEXPORT *m_glUniform1iARB )( GLint location, GLint v0 ); + void ( QGL_DLLEXPORT *m_glUniform2iARB )( GLint location, GLint v0, GLint v1 ); + void ( QGL_DLLEXPORT *m_glUniform3iARB )( GLint location, GLint v0, GLint v1, GLint v2 ); + void ( QGL_DLLEXPORT *m_glUniform4iARB )( GLint location, GLint v0, GLint v1, GLint v2, GLint v3 ); + void ( QGL_DLLEXPORT *m_glUniform1fvARB )( GLint location, GLsizei count, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniform2fvARB )( GLint location, GLsizei count, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniform3fvARB )( GLint location, GLsizei count, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniform4fvARB )( GLint location, GLsizei count, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniform1ivARB )( GLint location, GLsizei count, const GLint *value ); + void ( QGL_DLLEXPORT *m_glUniform2ivARB )( GLint location, GLsizei count, const GLint *value ); + void ( QGL_DLLEXPORT *m_glUniform3ivARB )( GLint location, GLsizei count, const GLint *value ); + void ( QGL_DLLEXPORT *m_glUniform4ivARB )( GLint location, GLsizei count, const GLint *value ); + void ( QGL_DLLEXPORT *m_glUniformMatrix2fvARB )( GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniformMatrix3fvARB )( GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glUniformMatrix4fvARB )( GLint location, GLsizei count, GLboolean transpose, const GLfloat *value ); + void ( QGL_DLLEXPORT *m_glGetObjectParameterfvARB )( GLhandleARB obj, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetObjectParameterivARB )( GLhandleARB obj, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetInfoLogARB )( GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog ); + void ( QGL_DLLEXPORT *m_glGetAttachedObjectsARB )( GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj ); + GLint ( QGL_DLLEXPORT *m_glGetUniformLocationARB )( GLhandleARB programObj, const GLcharARB *name ); + void ( QGL_DLLEXPORT *m_glGetActiveUniformARB )( GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name ); + void ( QGL_DLLEXPORT *m_glGetUniformfvARB )( GLhandleARB programObj, GLint location, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetUniformivARB )( GLhandleARB programObj, GLint location, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetShaderSourceARB )( GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source ); + + // GL_ARB_vertex_shader + bool support_ARB_vertex_shader; + bool ARB_vertex_shader(){ + return support_ARB_vertex_shader; + } #if 0 - void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat v0); - void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort v0); - void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble v0); - void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat v0, GLfloat v1); - void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort v0, GLshort v1); - void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble v0, GLdouble v1); - void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2); - void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2); - void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); - void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); + void ( QGL_DLLEXPORT *m_glVertexAttrib1fARB )( GLuint index, GLfloat v0 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1sARB )( GLuint index, GLshort v0 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1dARB )( GLuint index, GLdouble v0 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2fARB )( GLuint index, GLfloat v0, GLfloat v1 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2sARB )( GLuint index, GLshort v0, GLshort v1 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2dARB )( GLuint index, GLdouble v0, GLdouble v1 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3fARB )( GLuint index, GLfloat v0, GLfloat v1, GLfloat v2 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3sARB )( GLuint index, GLshort v0, GLshort v1, GLshort v2 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3dARB )( GLuint index, GLdouble v0, GLdouble v1, GLdouble v2 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4fARB )( GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4sARB )( GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4dARB )( GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3 ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NubARB )( GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib1dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib2dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib3dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4fvARB )( GLuint index, const GLfloat *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4svARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4dvARB )( GLuint index, const GLdouble *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4ivARB )( GLuint index, const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4bvARB )( GLuint index, const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4ubvARB )( GLuint index, const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4usvARB )( GLuint index, const GLushort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4uivARB )( GLuint index, const GLuint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NbvARB )( GLuint index, const GLbyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NsvARB )( GLuint index, const GLshort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NivARB )( GLuint index, const GLint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NubvARB )( GLuint index, const GLubyte *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NusvARB )( GLuint index, const GLushort *v ); + void ( QGL_DLLEXPORT *m_glVertexAttrib4NuivARB )( GLuint index, const GLuint *v ); + void ( QGL_DLLEXPORT *m_glVertexAttribPointerARB )( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer ); + void ( QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB )( GLuint index ); + void ( QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB )( GLuint index ); #endif - void (QGL_DLLEXPORT *m_glBindAttribLocationARB)(GLhandleARB programObj, GLuint index, const GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetActiveAttribARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); - GLint (QGL_DLLEXPORT *m_glGetAttribLocationARB)(GLhandleARB programObj, const GLcharARB *name); + void ( QGL_DLLEXPORT *m_glBindAttribLocationARB )( GLhandleARB programObj, GLuint index, const GLcharARB *name ); + void ( QGL_DLLEXPORT *m_glGetActiveAttribARB )( GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name ); + GLint ( QGL_DLLEXPORT *m_glGetAttribLocationARB )( GLhandleARB programObj, const GLcharARB *name ); #if 0 - void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); + void ( QGL_DLLEXPORT *m_glGetVertexAttribdvARB )( GLuint index, GLenum pname, GLdouble *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribfvARB )( GLuint index, GLenum pname, GLfloat *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribivARB )( GLuint index, GLenum pname, GLint *params ); + void ( QGL_DLLEXPORT *m_glGetVertexAttribPointervARB )( GLuint index, GLenum pname, GLvoid **pointer ); #endif - // ARB_fragment_shader - bool support_ARB_fragment_shader; - bool ARB_fragment_shader() - { - return support_ARB_fragment_shader; - } - - // ARB_shading_language_100 - bool support_ARB_shading_language_100; - bool ARB_shading_language_100() - { - return support_ARB_shading_language_100; - } - - // GL_NV_vertex_program2 - bool support_NV_vertex_program2; - bool NV_vertex_program2() - { - return support_NV_vertex_program2; - } - GLboolean (QGL_DLLEXPORT* m_glAreProgramsResidentNV)(GLsizei, const GLuint *, GLboolean *); - void (QGL_DLLEXPORT* m_glBindProgramNV)(GLenum, GLuint); - void (QGL_DLLEXPORT* m_glDeleteProgramsNV)(GLsizei, const GLuint *); - void (QGL_DLLEXPORT* m_glExecuteProgramNV)(GLenum, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glGenProgramsNV)(GLsizei, GLuint *); - void (QGL_DLLEXPORT* m_glGetProgramParameterdvNV)(GLenum, GLuint, GLenum, GLdouble *); - void (QGL_DLLEXPORT* m_glGetProgramParameterfvNV)(GLenum, GLuint, GLenum, GLfloat *); - void (QGL_DLLEXPORT* m_glGetProgramivNV)(GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetProgramStringNV)(GLuint, GLenum, GLubyte *); - void (QGL_DLLEXPORT* m_glGetTrackMatrixivNV)(GLenum, GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetVertexAttribdvNV)(GLuint, GLenum, GLdouble *); - void (QGL_DLLEXPORT* m_glGetVertexAttribfvNV)(GLuint, GLenum, GLfloat *); - void (QGL_DLLEXPORT* m_glGetVertexAttribivNV)(GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetVertexAttribPointervNV)(GLuint, GLenum, GLvoid* *); - GLboolean (QGL_DLLEXPORT* m_glIsProgramNV)(GLuint); - void (QGL_DLLEXPORT* m_glLoadProgramNV)(GLenum, GLuint, GLsizei, const GLubyte *); - void (QGL_DLLEXPORT* m_glProgramParameter4fNV)(GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glProgramParameter4fvNV)(GLenum, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glProgramParameters4fvNV)(GLenum, GLuint, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glRequestResidentProgramsNV)(GLsizei, const GLuint *); - void (QGL_DLLEXPORT* m_glTrackMatrixNV)(GLenum, GLuint, GLenum, GLenum); - void (QGL_DLLEXPORT* m_glVertexAttribPointerNV)(GLuint, GLint, GLenum, GLsizei, const GLvoid *); - void (QGL_DLLEXPORT* m_glVertexAttrib1fNV)(GLuint, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib1fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib2fNV)(GLuint, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib2fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib3fNV)(GLuint, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib3fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib4fNV)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib4fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs1fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs2fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs3fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs4fvNV)(GLuint, GLsizei, const GLfloat *); - - // GL_NV_fragment_program - bool support_NV_fragment_program; - bool NV_fragment_program() - { - return support_NV_fragment_program; - } - void (QGL_DLLEXPORT* m_glProgramNamedParameter4fNV)(GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glProgramNamedParameter4fvNV)(GLuint, GLsizei, const GLubyte *, const GLfloat *); - void (QGL_DLLEXPORT* m_glGetProgramNamedParameterfvNV)(GLuint, GLsizei, const GLubyte *, GLfloat *); + // ARB_fragment_shader + bool support_ARB_fragment_shader; + bool ARB_fragment_shader(){ + return support_ARB_fragment_shader; + } + + // ARB_shading_language_100 + bool support_ARB_shading_language_100; + bool ARB_shading_language_100(){ + return support_ARB_shading_language_100; + } + + // GL_NV_vertex_program2 + bool support_NV_vertex_program2; + bool NV_vertex_program2(){ + return support_NV_vertex_program2; + } + GLboolean ( QGL_DLLEXPORT* m_glAreProgramsResidentNV )( GLsizei, const GLuint *, GLboolean * ); + void ( QGL_DLLEXPORT* m_glBindProgramNV )( GLenum, GLuint ); + void ( QGL_DLLEXPORT* m_glDeleteProgramsNV )( GLsizei, const GLuint * ); + void ( QGL_DLLEXPORT* m_glExecuteProgramNV )( GLenum, GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glGenProgramsNV )( GLsizei, GLuint * ); + void ( QGL_DLLEXPORT* m_glGetProgramParameterdvNV )( GLenum, GLuint, GLenum, GLdouble * ); + void ( QGL_DLLEXPORT* m_glGetProgramParameterfvNV )( GLenum, GLuint, GLenum, GLfloat * ); + void ( QGL_DLLEXPORT* m_glGetProgramivNV )( GLuint, GLenum, GLint * ); + void ( QGL_DLLEXPORT* m_glGetProgramStringNV )( GLuint, GLenum, GLubyte * ); + void ( QGL_DLLEXPORT* m_glGetTrackMatrixivNV )( GLenum, GLuint, GLenum, GLint * ); + void ( QGL_DLLEXPORT* m_glGetVertexAttribdvNV )( GLuint, GLenum, GLdouble * ); + void ( QGL_DLLEXPORT* m_glGetVertexAttribfvNV )( GLuint, GLenum, GLfloat * ); + void ( QGL_DLLEXPORT* m_glGetVertexAttribivNV )( GLuint, GLenum, GLint * ); + void ( QGL_DLLEXPORT* m_glGetVertexAttribPointervNV )( GLuint, GLenum, GLvoid* * ); + GLboolean ( QGL_DLLEXPORT* m_glIsProgramNV )( GLuint ); + void ( QGL_DLLEXPORT* m_glLoadProgramNV )( GLenum, GLuint, GLsizei, const GLubyte * ); + void ( QGL_DLLEXPORT* m_glProgramParameter4fNV )( GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat ); + void ( QGL_DLLEXPORT* m_glProgramParameter4fvNV )( GLenum, GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glProgramParameters4fvNV )( GLenum, GLuint, GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glRequestResidentProgramsNV )( GLsizei, const GLuint * ); + void ( QGL_DLLEXPORT* m_glTrackMatrixNV )( GLenum, GLuint, GLenum, GLenum ); + void ( QGL_DLLEXPORT* m_glVertexAttribPointerNV )( GLuint, GLint, GLenum, GLsizei, const GLvoid * ); + void ( QGL_DLLEXPORT* m_glVertexAttrib1fNV )( GLuint, GLfloat ); + void ( QGL_DLLEXPORT* m_glVertexAttrib1fvNV )( GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttrib2fNV )( GLuint, GLfloat, GLfloat ); + void ( QGL_DLLEXPORT* m_glVertexAttrib2fvNV )( GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttrib3fNV )( GLuint, GLfloat, GLfloat, GLfloat ); + void ( QGL_DLLEXPORT* m_glVertexAttrib3fvNV )( GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttrib4fNV )( GLuint, GLfloat, GLfloat, GLfloat, GLfloat ); + void ( QGL_DLLEXPORT* m_glVertexAttrib4fvNV )( GLuint, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttribs1fvNV )( GLuint, GLsizei, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttribs2fvNV )( GLuint, GLsizei, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttribs3fvNV )( GLuint, GLsizei, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glVertexAttribs4fvNV )( GLuint, GLsizei, const GLfloat * ); + + // GL_NV_fragment_program + bool support_NV_fragment_program; + bool NV_fragment_program(){ + return support_NV_fragment_program; + } + void ( QGL_DLLEXPORT* m_glProgramNamedParameter4fNV )( GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat ); + void ( QGL_DLLEXPORT* m_glProgramNamedParameter4fvNV )( GLuint, GLsizei, const GLubyte *, const GLfloat * ); + void ( QGL_DLLEXPORT* m_glGetProgramNamedParameterfvNV )( GLuint, GLsizei, const GLubyte *, GLfloat * ); }; #include "modulesystem.h" @@ -2819,13 +2801,12 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalOpenGLModuleRef; -inline OpenGLBinding& GlobalOpenGL() -{ - return GlobalOpenGLModule::getTable(); +inline OpenGLBinding& GlobalOpenGL(){ + return GlobalOpenGLModule::getTable(); } -#if defined(_DEBUG) -#define GlobalOpenGL_debugAssertNoErrors() GlobalOpenGL().assertNoErrors(__FILE__, __LINE__) +#if defined( _DEBUG ) +#define GlobalOpenGL_debugAssertNoErrors() GlobalOpenGL().assertNoErrors( __FILE__, __LINE__ ) #else #define GlobalOpenGL_debugAssertNoErrors() #endif diff --git a/include/iglrender.cpp b/include/iglrender.cpp index 26d66ae0..6a9d9a74 100644 --- a/include/iglrender.cpp +++ b/include/iglrender.cpp @@ -1,3 +1,2 @@ #include "iglrender.h" - diff --git a/include/iglrender.h b/include/iglrender.h index 76216026..04b4a807 100644 --- a/include/iglrender.h +++ b/include/iglrender.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IGLRENDER_H) +#if !defined( INCLUDED_IGLRENDER_H ) #define INCLUDED_IGLRENDER_H #include "igl.h" @@ -31,85 +31,83 @@ class Matrix4; class GLProgram { public: - virtual void enable() = 0; - virtual void disable() = 0; - virtual void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) = 0; +virtual void enable() = 0; +virtual void disable() = 0; +virtual void setParameters( const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light ) = 0; }; class OpenGLFogState { public: - OpenGLFogState() : mode(GL_EXP), density(0), start(0), end(0), index(0), colour(1, 1, 1, 1) - { - } - GLenum mode; - GLfloat density; - GLfloat start; - GLfloat end; - GLint index; - Vector4 colour; +OpenGLFogState() : mode( GL_EXP ), density( 0 ), start( 0 ), end( 0 ), index( 0 ), colour( 1, 1, 1, 1 ){ +} +GLenum mode; +GLfloat density; +GLfloat start; +GLfloat end; +GLint index; +Vector4 colour; }; //! A collection of opengl state information. class OpenGLState { public: - enum ESort - { - eSortFirst = 0, - eSortOpaque = 1, - eSortMultiFirst = 2, - eSortMultiLast = 1023, - eSortOverbrighten = 1024, - eSortFullbright = 1025, - eSortHighlight = 1026, - eSortTranslucent = 1027, - eSortOverlayFirst = 1028, - eSortOverlayLast = 2047, - eSortControlFirst = 2048, - eSortControlLast = 3071, - eSortGUI0 = 3072, - eSortGUI1 = 3073, - eSortLast = 4096, - }; - - unsigned int m_state; - std::size_t m_sort; - GLint m_texture; - GLint m_texture1; - GLint m_texture2; - GLint m_texture3; - GLint m_texture4; - GLint m_texture5; - GLint m_texture6; - GLint m_texture7; - Vector4 m_colour; - GLenum m_blend_src, m_blend_dst; - GLenum m_depthfunc; - GLenum m_alphafunc; - GLfloat m_alpharef; - GLfloat m_linewidth; - GLfloat m_pointsize; - GLint m_linestipple_factor; - GLushort m_linestipple_pattern; - OpenGLFogState m_fog; - GLProgram* m_program; - - OpenGLState() : m_program(0) - { - } +enum ESort +{ + eSortFirst = 0, + eSortOpaque = 1, + eSortMultiFirst = 2, + eSortMultiLast = 1023, + eSortOverbrighten = 1024, + eSortFullbright = 1025, + eSortHighlight = 1026, + eSortTranslucent = 1027, + eSortOverlayFirst = 1028, + eSortOverlayLast = 2047, + eSortControlFirst = 2048, + eSortControlLast = 3071, + eSortGUI0 = 3072, + eSortGUI1 = 3073, + eSortLast = 4096, +}; + +unsigned int m_state; +std::size_t m_sort; +GLint m_texture; +GLint m_texture1; +GLint m_texture2; +GLint m_texture3; +GLint m_texture4; +GLint m_texture5; +GLint m_texture6; +GLint m_texture7; +Vector4 m_colour; +GLenum m_blend_src, m_blend_dst; +GLenum m_depthfunc; +GLenum m_alphafunc; +GLfloat m_alpharef; +GLfloat m_linewidth; +GLfloat m_pointsize; +GLint m_linestipple_factor; +GLushort m_linestipple_pattern; +OpenGLFogState m_fog; +GLProgram* m_program; + +OpenGLState() : m_program( 0 ){ +} }; class OpenGLStateLibrary { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "openglshaderlibrary"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "openglshaderlibrary" ); - virtual void getDefaultState(OpenGLState& state) const = 0; +virtual void getDefaultState( OpenGLState& state ) const = 0; - virtual void insert(const char* name, const OpenGLState& state) = 0; - virtual void erase(const char* name) = 0; +virtual void insert( const char* name, const OpenGLState& state ) = 0; +virtual void erase( const char* name ) = 0; }; #include "modulesystem.h" @@ -122,9 +120,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalOpenGLStateLibraryModuleRef; -inline OpenGLStateLibrary& GlobalOpenGLStateLibrary() -{ - return GlobalOpenGLStateLibraryModule::getTable(); +inline OpenGLStateLibrary& GlobalOpenGLStateLibrary(){ + return GlobalOpenGLStateLibraryModule::getTable(); } #endif diff --git a/include/igtkgl.cpp b/include/igtkgl.cpp index 1180d547..d0084a85 100644 --- a/include/igtkgl.cpp +++ b/include/igtkgl.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "igtkgl.h" - diff --git a/include/igtkgl.h b/include/igtkgl.h index 6a0a631f..e6e85254 100644 --- a/include/igtkgl.h +++ b/include/igtkgl.h @@ -1,43 +1,43 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IGTKGL_H) +#if !defined( INCLUDED_IGTKGL_H ) #define INCLUDED_IGTKGL_H #include "generic/constant.h" typedef struct _GtkWidget GtkWidget; -typedef int gint; -typedef gint gboolean; +typedef int gint; +typedef gint gboolean; struct _QERGtkGLTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "gtkgl"); - - GtkWidget* (*glwidget_new)(gboolean zbufffer); - void (*glwidget_swap_buffers)(GtkWidget* widget); - gboolean(*glwidget_make_current)(GtkWidget* widget); - void (*glwidget_destroy_context)(GtkWidget* widget); - void (*glwidget_create_context)(GtkWidget* widget); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "gtkgl" ); + + GtkWidget* ( *glwidget_new )(gboolean zbufffer); + void ( *glwidget_swap_buffers )( GtkWidget* widget ); + gboolean ( *glwidget_make_current )( GtkWidget* widget ); + void ( *glwidget_destroy_context )( GtkWidget* widget ); + void ( *glwidget_create_context )( GtkWidget* widget ); }; #endif diff --git a/include/iimage.cpp b/include/iimage.cpp index a95ab6d3..f438be78 100644 --- a/include/iimage.cpp +++ b/include/iimage.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iimage.h" - diff --git a/include/iimage.h b/include/iimage.h index f6020bd8..c159e657 100644 --- a/include/iimage.h +++ b/include/iimage.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IIMAGE_H) +#if !defined( INCLUDED_IIMAGE_H ) #define INCLUDED_IIMAGE_H #include "generic/constant.h" @@ -29,35 +29,32 @@ typedef unsigned char byte; class Image { public: - virtual void release() = 0; - virtual byte* getRGBAPixels() const = 0; - virtual unsigned int getWidth() const = 0; - virtual unsigned int getHeight() const = 0; - - virtual int getSurfaceFlags() const - { - return 0; - } - virtual int getContentFlags() const - { - return 0; - } - virtual int getValue() const - { - return 0; - } +virtual void release() = 0; +virtual byte* getRGBAPixels() const = 0; +virtual unsigned int getWidth() const = 0; +virtual unsigned int getHeight() const = 0; + +virtual int getSurfaceFlags() const { + return 0; +} +virtual int getContentFlags() const { + return 0; +} +virtual int getValue() const { + return 0; +} }; class ArchiveFile; struct _QERPlugImageTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "image"); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "image" ); - /// Read an image from the file. - /// Returns 0 if the image could not be read. - Image* (*loadImage)(ArchiveFile& file); + /// Read an image from the file. + /// Returns 0 if the image could not be read. + Image* ( *loadImage )( ArchiveFile & file ); }; template diff --git a/include/imap.cpp b/include/imap.cpp index 0b363b5e..a91f14da 100644 --- a/include/imap.cpp +++ b/include/imap.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "imap.h" - diff --git a/include/imap.h b/include/imap.h index c97a2ff2..7af4c472 100644 --- a/include/imap.h +++ b/include/imap.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IMAP_H) +#if !defined( INCLUDED_IMAP_H ) #define INCLUDED_IMAP_H #include "generic/constant.h" @@ -31,18 +31,18 @@ class TokenWriter; class MapImporter { public: - STRING_CONSTANT(Name, "MapImporter"); +STRING_CONSTANT( Name, "MapImporter" ); - virtual bool importTokens(Tokeniser& tokeniser) = 0; +virtual bool importTokens( Tokeniser& tokeniser ) = 0; }; /// \brief A node whose state can be exported to a token stream. class MapExporter { public: - STRING_CONSTANT(Name, "MapExporter"); +STRING_CONSTANT( Name, "MapExporter" ); - virtual void exportTokens(TokenWriter& writer) const = 0; +virtual void exportTokens( TokenWriter& writer ) const = 0; }; #include "iscenegraph.h" @@ -53,20 +53,20 @@ class TextInputStream; class TextOutputStream; -typedef void(*GraphTraversalFunc)(scene::Node& root, const scene::Traversable::Walker& walker); +typedef void ( *GraphTraversalFunc )( scene::Node& root, const scene::Traversable::Walker& walker ); /// \brief A module that reads and writes a map in a specific format. class MapFormat { public: - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "map"); - mutable bool wrongFormat; - - /// \brief Read a map graph into \p root from \p outputStream, using \p entityTable to create entities. - virtual void readGraph(scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable) const = 0; - /// \brief Write the map graph obtained by applying \p traverse to \p root into \p outputStream. - virtual void writeGraph(scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream) const = 0; +INTEGER_CONSTANT( Version, 2 ); +STRING_CONSTANT( Name, "map" ); +mutable bool wrongFormat; + +/// \brief Read a map graph into \p root from \p outputStream, using \p entityTable to create entities. +virtual void readGraph( scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable ) const = 0; +/// \brief Write the map graph obtained by applying \p traverse to \p root into \p outputStream. +virtual void writeGraph( scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream ) const = 0; }; diff --git a/include/imodel.cpp b/include/imodel.cpp index 081dccac..0b932e25 100644 --- a/include/imodel.cpp +++ b/include/imodel.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "imodel.h" - diff --git a/include/imodel.h b/include/imodel.h index aa040d63..d047e90a 100644 --- a/include/imodel.h +++ b/include/imodel.h @@ -1,32 +1,32 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IMODEL_H) +#if !defined( INCLUDED_IMODEL_H ) #define INCLUDED_IMODEL_H #include "generic/constant.h" namespace scene { - class Node; +class Node; } class ArchiveFile; @@ -34,9 +34,9 @@ class ArchiveFile; class ModelLoader { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "model"); - virtual scene::Node& loadModel(ArchiveFile& file) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "model" ); +virtual scene::Node& loadModel( ArchiveFile& file ) = 0; }; template diff --git a/include/ipatch.cpp b/include/ipatch.cpp index 940a1bed..e29029c3 100644 --- a/include/ipatch.cpp +++ b/include/ipatch.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ipatch.h" - diff --git a/include/ipatch.h b/include/ipatch.h index 48ce39b5..e9bee3d7 100644 --- a/include/ipatch.h +++ b/include/ipatch.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IPATCH_H) +#if !defined( INCLUDED_IPATCH_H ) #define INCLUDED_IPATCH_H #include "generic/constant.h" @@ -27,230 +27,193 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA namespace scene { - class Node; +class Node; } template class ArrayReference { - std::size_t m_size; - Element* m_data; +std::size_t m_size; +Element* m_data; public: - typedef Element value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; +typedef Element value_type; +typedef value_type* iterator; +typedef const value_type* const_iterator; - ArrayReference() - : m_size(0), m_data(0) - { - } - ArrayReference(std::size_t size, Element* data) - : m_size(size), m_data(data) - { - } +ArrayReference() + : m_size( 0 ), m_data( 0 ){ +} +ArrayReference( std::size_t size, Element* data ) + : m_size( size ), m_data( data ){ +} - iterator begin() - { - return m_data; - } - const_iterator begin() const - { - return m_data; - } - iterator end() - { - return m_data + m_size; - } - const_iterator end() const - { - return m_data + m_size; - } +iterator begin(){ + return m_data; +} +const_iterator begin() const { + return m_data; +} +iterator end(){ + return m_data + m_size; +} +const_iterator end() const { + return m_data + m_size; +} - value_type& operator[](std::size_t index) - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); +value_type& operator[]( std::size_t index ){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - const value_type& operator[](std::size_t index) const - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); + return m_data[index]; +} +const value_type& operator[]( std::size_t index ) const { +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - value_type* data() - { - return m_data; - } - const value_type* data() const - { - return m_data; - } - std::size_t size() const - { - return m_size; - } - bool empty() const - { - return m_size == 0; - } + return m_data[index]; +} +value_type* data(){ + return m_data; +} +const value_type* data() const { + return m_data; +} +std::size_t size() const { + return m_size; +} +bool empty() const { + return m_size == 0; +} }; #if 0 template class MatrixIterator { - Element* m_position; +Element* m_position; - void increment() - { - ++m_position; - } +void increment(){ + ++m_position; +} public: - typedef std::bidirectional_iterator_tag iterator_category; - typedef std::ptrdiff_t difference_type; - typedef difference_type distance_type; - typedef KeyValue value_type; - typedef value_type* pointer; - typedef value_type& reference; - - MatrixIterator(Element* position) : m_position(position) - { - } +typedef std::bidirectional_iterator_tag iterator_category; +typedef std::ptrdiff_t difference_type; +typedef difference_type distance_type; +typedef KeyValue value_type; +typedef value_type* pointer; +typedef value_type& reference; + +MatrixIterator( Element* position ) : m_position( position ){ +} - Element* position() - { - return m_position; - } +Element* position(){ + return m_position; +} - bool operator==(const MatrixIterator& other) const - { - return m_position == other.m_position; - } - bool operator!=(const MatrixIterator& other) const - { - return !operator==(other); - } - MatrixIterator& operator++() - { - increment(); - return *this; - } - MatrixIterator operator++(int) - { - MatrixIterator tmp = *this; - increment(); - return tmp; - } - value_type& operator*() const - { - return m_position->m_value; - } - value_type* operator->() const - { - return &(operator*()); - } +bool operator==( const MatrixIterator& other ) const { + return m_position == other.m_position; +} +bool operator!=( const MatrixIterator& other ) const { + return !operator==( other ); +} +MatrixIterator& operator++(){ + increment(); + return *this; +} +MatrixIterator operator++( int ){ + MatrixIterator tmp = *this; + increment(); + return tmp; +} +value_type& operator*() const { + return m_position->m_value; +} +value_type* operator->() const { + return &( operator*() ); +} }; #endif template class Matrix { - std::size_t m_x, m_y; - Element* m_data; +std::size_t m_x, m_y; +Element* m_data; public: - typedef Element value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; +typedef Element value_type; +typedef value_type* iterator; +typedef const value_type* const_iterator; - Matrix() - : m_x(0), m_y(0), m_data(0) - { - } - Matrix(std::size_t x, std::size_t y, Element* data) - : m_x(x), m_y(y), m_data(data) - { - } +Matrix() + : m_x( 0 ), m_y( 0 ), m_data( 0 ){ +} +Matrix( std::size_t x, std::size_t y, Element* data ) + : m_x( x ), m_y( y ), m_data( data ){ +} - iterator begin() - { - return m_data; - } - const_iterator begin() const - { - return m_data; - } - iterator end() - { - return m_data + size(); - } - const_iterator end() const - { - return m_data + size(); - } +iterator begin(){ + return m_data; +} +const_iterator begin() const { + return m_data; +} +iterator end(){ + return m_data + size(); +} +const_iterator end() const { + return m_data + size(); +} - value_type& operator[](std::size_t index) - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); +value_type& operator[]( std::size_t index ){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - const value_type& operator[](std::size_t index) const - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); + return m_data[index]; +} +const value_type& operator[]( std::size_t index ) const { +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - value_type& operator()(std::size_t x, std::size_t y) - { -#if defined(_DEBUG) - ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); + return m_data[index]; +} +value_type& operator()( std::size_t x, std::size_t y ){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); #endif - return m_data[x * m_y + y]; - } - const value_type& operator()(std::size_t x, std::size_t y) const - { -#if defined(_DEBUG) - ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); + return m_data[x * m_y + y]; +} +const value_type& operator()( std::size_t x, std::size_t y ) const { +#if defined( _DEBUG ) + ASSERT_MESSAGE( x < m_x && y < m_y, "array index out of bounds" ); #endif - return m_data[x * m_y + y]; - } - value_type* data() - { - return m_data; - } - const value_type* data() const - { - return m_data; - } - std::size_t x() const - { - return m_x; - } - std::size_t y() const - { - return m_y; - } - std::size_t size() const - { - return m_x * m_y; - } - bool empty() const - { - return m_x == 0; - } + return m_data[x * m_y + y]; +} +value_type* data(){ + return m_data; +} +const value_type* data() const { + return m_data; +} +std::size_t x() const { + return m_x; +} +std::size_t y() const { + return m_y; +} +std::size_t size() const { + return m_x * m_y; +} +bool empty() const { + return m_x == 0; +} }; class PatchControl { public: - Vector3 m_vertex; - Vector2 m_texcoord; +Vector3 m_vertex; +Vector2 m_texcoord; }; typedef Matrix PatchControlMatrix; @@ -259,15 +222,15 @@ typedef Matrix PatchControlMatrix; class PatchCreator { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "patch"); - virtual scene::Node& createPatch() = 0; - virtual void Patch_undoSave(scene::Node& patch) const = 0; - virtual void Patch_resize(scene::Node& patch, std::size_t width, std::size_t height) const = 0; - virtual PatchControlMatrix Patch_getControlPoints(scene::Node& patch) const = 0; - virtual void Patch_controlPointsChanged(scene::Node& patch) const = 0; - virtual const char* Patch_getShader(scene::Node& patch) const = 0; - virtual void Patch_setShader(scene::Node& patch, const char* shader) const = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "patch" ); +virtual scene::Node& createPatch() = 0; +virtual void Patch_undoSave( scene::Node& patch ) const = 0; +virtual void Patch_resize( scene::Node& patch, std::size_t width, std::size_t height ) const = 0; +virtual PatchControlMatrix Patch_getControlPoints( scene::Node& patch ) const = 0; +virtual void Patch_controlPointsChanged( scene::Node& patch ) const = 0; +virtual const char* Patch_getShader( scene::Node& patch ) const = 0; +virtual void Patch_setShader( scene::Node& patch, const char* shader ) const = 0; }; #include "modulesystem.h" @@ -284,9 +247,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalPatchModuleRef; -inline PatchCreator& GlobalPatchCreator() -{ - return GlobalPatchModule::getTable(); +inline PatchCreator& GlobalPatchCreator(){ + return GlobalPatchModule::getTable(); } #endif diff --git a/include/iplugin.cpp b/include/iplugin.cpp index ebfc591f..2a7dab9b 100644 --- a/include/iplugin.cpp +++ b/include/iplugin.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iplugin.h" - diff --git a/include/iplugin.h b/include/iplugin.h index af713a7d..a67160be 100644 --- a/include/iplugin.h +++ b/include/iplugin.h @@ -1,45 +1,45 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IPLUGIN_H) +#if !defined( INCLUDED_IPLUGIN_H ) #define INCLUDED_IPLUGIN_H #include "generic/constant.h" -typedef const char* (* PFN_QERPLUG_INIT) (void* hApp, void* pMainWidget); -typedef const char* (* PFN_QERPLUG_GETNAME)(); -typedef const char* (* PFN_QERPLUG_GETCOMMANDLIST)(); -typedef const char* (* PFN_QERPLUG_GETCOMMANDTITLELIST)(); -typedef void (* PFN_QERPLUG_DISPATCH) (const char* p, float* vMin, float* vMax, bool bSingleBrush); +typedef const char* ( *PFN_QERPLUG_INIT )( void* hApp, void* pMainWidget ); +typedef const char* ( *PFN_QERPLUG_GETNAME )(); +typedef const char* ( *PFN_QERPLUG_GETCOMMANDLIST )(); +typedef const char* ( *PFN_QERPLUG_GETCOMMANDTITLELIST )(); +typedef void ( *PFN_QERPLUG_DISPATCH )( const char* p, float* vMin, float* vMax, bool bSingleBrush ); struct _QERPluginTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "plugin"); - - PFN_QERPLUG_INIT m_pfnQERPlug_Init; - PFN_QERPLUG_GETNAME m_pfnQERPlug_GetName; - PFN_QERPLUG_GETCOMMANDLIST m_pfnQERPlug_GetCommandList; - PFN_QERPLUG_GETCOMMANDTITLELIST m_pfnQERPlug_GetCommandTitleList; - PFN_QERPLUG_DISPATCH m_pfnQERPlug_Dispatch; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "plugin" ); + + PFN_QERPLUG_INIT m_pfnQERPlug_Init; + PFN_QERPLUG_GETNAME m_pfnQERPlug_GetName; + PFN_QERPLUG_GETCOMMANDLIST m_pfnQERPlug_GetCommandList; + PFN_QERPLUG_GETCOMMANDTITLELIST m_pfnQERPlug_GetCommandTitleList; + PFN_QERPLUG_DISPATCH m_pfnQERPlug_Dispatch; }; template diff --git a/include/ireference.cpp b/include/ireference.cpp index 844e95be..d2f56c49 100644 --- a/include/ireference.cpp +++ b/include/ireference.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ireference.h" - diff --git a/include/ireference.h b/include/ireference.h index e97df794..359f487c 100644 --- a/include/ireference.h +++ b/include/ireference.h @@ -1,32 +1,32 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IREFERENCE_H) +#if !defined( INCLUDED_IREFERENCE_H ) #define INCLUDED_IREFERENCE_H #include "generic/constant.h" namespace scene { - class Node; +class Node; } class ModuleObserver; @@ -34,16 +34,16 @@ class ModuleObserver; class Resource { public: - virtual bool load() = 0; - virtual bool save() = 0; - virtual void flush() = 0; - virtual void refresh() = 0; - virtual scene::Node* getNode() = 0; - virtual void setNode(scene::Node* node) = 0; - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; - virtual void realise() = 0; - virtual void unrealise() = 0; +virtual bool load() = 0; +virtual bool save() = 0; +virtual void flush() = 0; +virtual void refresh() = 0; +virtual scene::Node* getNode() = 0; +virtual void setNode( scene::Node* node ) = 0; +virtual void attach( ModuleObserver& observer ) = 0; +virtual void detach( ModuleObserver& observer ) = 0; +virtual void realise() = 0; +virtual void unrealise() = 0; }; class EntityCreator; @@ -51,13 +51,13 @@ class EntityCreator; class ReferenceCache { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "reference"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "reference" ); - virtual Resource* capture(const char* path) = 0; - virtual void release(const char* path) = 0; +virtual Resource* capture( const char* path ) = 0; +virtual void release( const char* path ) = 0; - virtual void setEntityCreator(EntityCreator& entityCreator) = 0; +virtual void setEntityCreator( EntityCreator& entityCreator ) = 0; }; #include "modulesystem.h" @@ -70,9 +70,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalReferenceModuleRef; -inline ReferenceCache& GlobalReferenceCache() -{ - return GlobalReferenceModule::getTable(); +inline ReferenceCache& GlobalReferenceCache(){ + return GlobalReferenceModule::getTable(); } #endif diff --git a/include/irender.cpp b/include/irender.cpp index c0fec667..9726b6d8 100644 --- a/include/irender.cpp +++ b/include/irender.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "irender.h" - diff --git a/include/irender.h b/include/irender.h index d9c40b6f..51994542 100644 --- a/include/irender.h +++ b/include/irender.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IRENDER_H) +#if !defined( INCLUDED_IRENDER_H ) #define INCLUDED_IRENDER_H #include "generic/constant.h" @@ -67,26 +67,24 @@ class Shader; class RendererLight { public: - virtual Shader* getShader() const = 0; - virtual const AABB& aabb() const = 0; - virtual bool testAABB(const AABB& other) const = 0; - virtual const Matrix4& rotation() const = 0; - virtual const Vector3& offset() const = 0; - virtual const Vector3& colour() const = 0; - virtual bool isProjected() const = 0; - virtual const Matrix4& projection() const = 0; +virtual Shader* getShader() const = 0; +virtual const AABB& aabb() const = 0; +virtual bool testAABB( const AABB& other ) const = 0; +virtual const Matrix4& rotation() const = 0; +virtual const Vector3& offset() const = 0; +virtual const Vector3& colour() const = 0; +virtual bool isProjected() const = 0; +virtual const Matrix4& projection() const = 0; }; class LightCullable { public: - virtual bool testLight(const RendererLight& light) const = 0; - virtual void insertLight(const RendererLight& light) - { - } - virtual void clearLights() - { - } +virtual bool testLight( const RendererLight& light ) const = 0; +virtual void insertLight( const RendererLight& light ){ +} +virtual void clearLights(){ +} }; class Renderable; @@ -97,9 +95,9 @@ typedef Callback1 RendererLightCallback; class LightList { public: - virtual void evaluateLights() const = 0; - virtual void lightsChanged() const = 0; - virtual void forEachLight(const RendererLightCallback& callback) const = 0; +virtual void evaluateLights() const = 0; +virtual void lightsChanged() const = 0; +virtual void forEachLight( const RendererLightCallback& callback ) const = 0; }; const int c_attr_TexCoord0 = 1; @@ -109,7 +107,7 @@ const int c_attr_Binormal = 4; class OpenGLRenderable { public: - virtual void render(RenderStateFlags state) const = 0; +virtual void render( RenderStateFlags state ) const = 0; }; class Matrix4; @@ -121,42 +119,42 @@ class ModuleObserver; class Shader { public: - virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0) = 0; - virtual void incrementUsed() = 0; - virtual void decrementUsed() = 0; - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; - virtual qtexture_t& getTexture() const = 0; - virtual unsigned int getFlags() const = 0; +virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0 ) = 0; +virtual void incrementUsed() = 0; +virtual void decrementUsed() = 0; +virtual void attach( ModuleObserver& observer ) = 0; +virtual void detach( ModuleObserver& observer ) = 0; +virtual qtexture_t& getTexture() const = 0; +virtual unsigned int getFlags() const = 0; }; class ShaderCache { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "renderstate"); - - virtual Shader* capture(const char* name) = 0; - virtual void release(const char* name) = 0; - /*! Render all Shader objects. */ - virtual void render(RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3(0, 0, 0)) = 0; - - virtual void realise() = 0; - virtual void unrealise() = 0; - - virtual bool lightingSupported() const = 0; - virtual bool useShaderLanguage() const = 0; - - virtual const LightList& attach(LightCullable& cullable) = 0; - virtual void detach(LightCullable& cullable) = 0; - virtual void changed(LightCullable& cullable) = 0; - virtual void attach(RendererLight& light) = 0; - virtual void detach(RendererLight& light) = 0; - virtual void changed(RendererLight& light) = 0; - - virtual void attachRenderable(const Renderable& renderable) = 0; - virtual void detachRenderable(const Renderable& renderable) = 0; - virtual void forEachRenderable(const RenderableCallback& callback) const = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "renderstate" ); + +virtual Shader* capture( const char* name ) = 0; +virtual void release( const char* name ) = 0; +/*! Render all Shader objects. */ +virtual void render( RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3( 0, 0, 0 ) ) = 0; + +virtual void realise() = 0; +virtual void unrealise() = 0; + +virtual bool lightingSupported() const = 0; +virtual bool useShaderLanguage() const = 0; + +virtual const LightList& attach( LightCullable& cullable ) = 0; +virtual void detach( LightCullable& cullable ) = 0; +virtual void changed( LightCullable& cullable ) = 0; +virtual void attach( RendererLight& light ) = 0; +virtual void detach( RendererLight& light ) = 0; +virtual void changed( RendererLight& light ) = 0; + +virtual void attachRenderable( const Renderable& renderable ) = 0; +virtual void detachRenderable( const Renderable& renderable ) = 0; +virtual void forEachRenderable( const RenderableCallback& callback ) const = 0; }; #include "modulesystem.h" @@ -169,9 +167,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalShaderCacheModuleRef; -inline ShaderCache& GlobalShaderCache() -{ - return GlobalShaderCacheModule::getTable(); +inline ShaderCache& GlobalShaderCache(){ + return GlobalShaderCacheModule::getTable(); } #endif diff --git a/include/iscenegraph.cpp b/include/iscenegraph.cpp index 6b7b450e..48cbcf23 100644 --- a/include/iscenegraph.cpp +++ b/include/iscenegraph.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iscenegraph.h" - diff --git a/include/iscenegraph.h b/include/iscenegraph.h index 18e50f77..6b28b0fc 100644 --- a/include/iscenegraph.h +++ b/include/iscenegraph.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_ISCENEGRAPH_H) +#if !defined ( INCLUDED_ISCENEGRAPH_H ) #define INCLUDED_ISCENEGRAPH_H #include @@ -33,19 +33,17 @@ class Reference; namespace scene { - class Instance; - const Instance* const nullInstancePointer = 0; - inline const Instance& nullInstance() - { - return *nullInstancePointer; - } - - class Node; - const Node* const nullNodePointer = 0; - inline const Node& nullNode() - { - return *nullNodePointer; - } +class Instance; +const Instance* const nullInstancePointer = 0; +inline const Instance& nullInstance(){ + return *nullInstancePointer; +} + +class Node; +const Node* const nullNodePointer = 0; +inline const Node& nullNode(){ + return *nullNodePointer; +} } typedef Reference NodeReference; @@ -60,136 +58,134 @@ const TypeId INSTANCETYPEID_NONE = INSTANCETYPEID_MAX; namespace scene { - /// \brief A unique key to an instance of a node in the scene-graph. - typedef Stack Path; - - /// \brief A scene-graph - a Directed Acyclic Graph (DAG). - /// - /// - Each node may refer to zero or more 'child' nodes (directed). - /// - A node may never have itself as one of its ancestors (acyclic). - /// - Each node may have more than one 'parent', thus having more than one 'instance' in the graph. - /// - Each instance is uniquely identified by the list of its ancestors plus itself, known as a 'path'. - class Graph - { - public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "scenegraph"); - - class Walker - { - public: - /// \brief Called before traversing the first child-instance of 'instance'. If the return value is false, the children of the current instance are not traversed. - virtual bool pre(const Path& path, Instance& instance) const = 0; - /// \brief Called after traversing the last child-instance of 'instance'. - virtual void post(const Path& path, Instance& instance) const - { - } - }; - - /// \brief Returns the root-node of the graph. - virtual Node& root() = 0; - /// \brief Sets the root-node of the graph to be 'node'. - virtual void insert_root(Node& root) = 0; - /// \brief Clears the root-node of the graph. - virtual void erase_root() = 0; - /// \brief Traverses all nodes in the graph depth-first, starting from the root node. - virtual void traverse(const Walker& walker) = 0; - /// \brief Traverses all nodes in the graph depth-first, starting from 'start'. - virtual void traverse_subgraph(const Walker& walker, const Path& start) = 0; - /// \brief Returns the instance at the location identified by 'path', or 0 if it does not exist. - virtual scene::Instance* find(const Path& path) = 0; - - /// \brief Invokes all scene-changed callbacks. Called when any part of the scene changes the way it will appear when the scene is rendered. - /// \todo Move to a separate class. - virtual void sceneChanged() = 0; - /// \brief Add a \p callback to be invoked when the scene changes. - /// \todo Move to a separate class. - virtual void addSceneChangedCallback(const SignalHandler& handler) = 0; - - /// \brief Invokes all bounds-changed callbacks. Called when the bounds of any instance in the scene change. - /// \todo Move to a separate class. - virtual void boundsChanged() = 0; - /// \brief Add a \p callback to be invoked when the bounds of any instance in the scene change. - virtual SignalHandlerId addBoundsChangedCallback(const SignalHandler& boundsChanged) = 0; - /// \brief Remove a \p callback to be invoked when the bounds of any instance in the scene change. - virtual void removeBoundsChangedCallback(SignalHandlerId id) = 0; - - virtual TypeId getNodeTypeId(const char* name) = 0; - virtual TypeId getInstanceTypeId(const char* name) = 0; - }; - - class Traversable - { - public: - STRING_CONSTANT(Name, "scene::Traversable"); - - class Observer - { - public: - /// \brief Called when a node is added to the container. - virtual void insert(Node& node) = 0; - /// \brief Called when a node is removed from the container. - virtual void erase(Node& node) = 0; - }; - - class Walker - { - public: - /// \brief Called before traversing the first child-node of 'node'. If the return value is false, the children of the current node are not traversed. - virtual bool pre(Node& node) const = 0; - /// \brief Called after traversing the last child-node of 'node'. - virtual void post(Node& node) const - { - } - }; - /// \brief Adds a node to the container. - virtual void insert(Node& node) = 0; - /// \brief Removes a node from the container. - virtual void erase(Node& node) = 0; - /// \brief Traverses the subgraphs rooted at each node in the container, depth-first. - virtual void traverse(const Walker& walker) = 0; - /// \brief Returns true if the container contains no nodes. - virtual bool empty() const = 0; - }; - - class Instantiable - { - public: - STRING_CONSTANT(Name, "scene::Instantiable"); - - class Observer - { - public: - /// \brief Called when an instance is added to the container. - virtual void insert(scene::Instance* instance) = 0; - /// \brief Called when an instance is removed from the container. - virtual void erase(scene::Instance* instance) = 0; - }; - - class Visitor - { - public: - virtual void visit(Instance& instance) const = 0; - }; - - /// \brief Returns a new instance uniquely identified by 'path'. - virtual scene::Instance* create(const scene::Path& path, scene::Instance* parent) = 0; - /// \brief Calls Visitor::visit(instance) for each instance in the container. - virtual void forEachInstance(const Visitor& visitor) = 0; - /// \brief Adds an instance to the container. - virtual void insert(Observer* observer, const Path& path, scene::Instance* instance) = 0; - /// \brief Returns an instance removed from the container. - virtual scene::Instance* erase(Observer* observer, const Path& path) = 0; - }; - - class Cloneable - { - public: - STRING_CONSTANT(Name, "scene::Cloneable"); - - /// \brief Returns a copy of itself. - virtual scene::Node& clone() const = 0; - }; +/// \brief A unique key to an instance of a node in the scene-graph. +typedef Stack Path; + +/// \brief A scene-graph - a Directed Acyclic Graph (DAG). +/// +/// - Each node may refer to zero or more 'child' nodes (directed). +/// - A node may never have itself as one of its ancestors (acyclic). +/// - Each node may have more than one 'parent', thus having more than one 'instance' in the graph. +/// - Each instance is uniquely identified by the list of its ancestors plus itself, known as a 'path'. +class Graph +{ +public: +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "scenegraph" ); + +class Walker +{ +public: +/// \brief Called before traversing the first child-instance of 'instance'. If the return value is false, the children of the current instance are not traversed. +virtual bool pre( const Path& path, Instance& instance ) const = 0; +/// \brief Called after traversing the last child-instance of 'instance'. +virtual void post( const Path& path, Instance& instance ) const { +} +}; + +/// \brief Returns the root-node of the graph. +virtual Node& root() = 0; +/// \brief Sets the root-node of the graph to be 'node'. +virtual void insert_root( Node& root ) = 0; +/// \brief Clears the root-node of the graph. +virtual void erase_root() = 0; +/// \brief Traverses all nodes in the graph depth-first, starting from the root node. +virtual void traverse( const Walker& walker ) = 0; +/// \brief Traverses all nodes in the graph depth-first, starting from 'start'. +virtual void traverse_subgraph( const Walker& walker, const Path& start ) = 0; +/// \brief Returns the instance at the location identified by 'path', or 0 if it does not exist. +virtual scene::Instance* find( const Path& path ) = 0; + +/// \brief Invokes all scene-changed callbacks. Called when any part of the scene changes the way it will appear when the scene is rendered. +/// \todo Move to a separate class. +virtual void sceneChanged() = 0; +/// \brief Add a \p callback to be invoked when the scene changes. +/// \todo Move to a separate class. +virtual void addSceneChangedCallback( const SignalHandler& handler ) = 0; + +/// \brief Invokes all bounds-changed callbacks. Called when the bounds of any instance in the scene change. +/// \todo Move to a separate class. +virtual void boundsChanged() = 0; +/// \brief Add a \p callback to be invoked when the bounds of any instance in the scene change. +virtual SignalHandlerId addBoundsChangedCallback( const SignalHandler& boundsChanged ) = 0; +/// \brief Remove a \p callback to be invoked when the bounds of any instance in the scene change. +virtual void removeBoundsChangedCallback( SignalHandlerId id ) = 0; + +virtual TypeId getNodeTypeId( const char* name ) = 0; +virtual TypeId getInstanceTypeId( const char* name ) = 0; +}; + +class Traversable +{ +public: +STRING_CONSTANT( Name, "scene::Traversable" ); + +class Observer +{ +public: +/// \brief Called when a node is added to the container. +virtual void insert( Node& node ) = 0; +/// \brief Called when a node is removed from the container. +virtual void erase( Node& node ) = 0; +}; + +class Walker +{ +public: +/// \brief Called before traversing the first child-node of 'node'. If the return value is false, the children of the current node are not traversed. +virtual bool pre( Node& node ) const = 0; +/// \brief Called after traversing the last child-node of 'node'. +virtual void post( Node& node ) const { +} +}; +/// \brief Adds a node to the container. +virtual void insert( Node& node ) = 0; +/// \brief Removes a node from the container. +virtual void erase( Node& node ) = 0; +/// \brief Traverses the subgraphs rooted at each node in the container, depth-first. +virtual void traverse( const Walker& walker ) = 0; +/// \brief Returns true if the container contains no nodes. +virtual bool empty() const = 0; +}; + +class Instantiable +{ +public: +STRING_CONSTANT( Name, "scene::Instantiable" ); + +class Observer +{ +public: +/// \brief Called when an instance is added to the container. +virtual void insert( scene::Instance* instance ) = 0; +/// \brief Called when an instance is removed from the container. +virtual void erase( scene::Instance* instance ) = 0; +}; + +class Visitor +{ +public: +virtual void visit( Instance& instance ) const = 0; +}; + +/// \brief Returns a new instance uniquely identified by 'path'. +virtual scene::Instance* create( const scene::Path& path, scene::Instance* parent ) = 0; +/// \brief Calls Visitor::visit(instance) for each instance in the container. +virtual void forEachInstance( const Visitor& visitor ) = 0; +/// \brief Adds an instance to the container. +virtual void insert( Observer* observer, const Path& path, scene::Instance* instance ) = 0; +/// \brief Returns an instance removed from the container. +virtual scene::Instance* erase( Observer* observer, const Path& path ) = 0; +}; + +class Cloneable +{ +public: +STRING_CONSTANT( Name, "scene::Cloneable" ); + +/// \brief Returns a copy of itself. +virtual scene::Node& clone() const = 0; +}; } #include "modulesystem.h" @@ -202,18 +198,15 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalSceneGraphModuleRef; -inline scene::Graph& GlobalSceneGraph() -{ - return GlobalSceneGraphModule::getTable(); +inline scene::Graph& GlobalSceneGraph(){ + return GlobalSceneGraphModule::getTable(); } -inline void AddSceneChangeCallback(const SignalHandler& handler) -{ - GlobalSceneGraph().addSceneChangedCallback(handler); +inline void AddSceneChangeCallback( const SignalHandler& handler ){ + GlobalSceneGraph().addSceneChangedCallback( handler ); } -inline void SceneChangeNotify() -{ - GlobalSceneGraph().sceneChanged(); +inline void SceneChangeNotify(){ + GlobalSceneGraph().sceneChanged(); } diff --git a/include/iscriplib.cpp b/include/iscriplib.cpp index 4de7c3f9..3c4ba180 100644 --- a/include/iscriplib.cpp +++ b/include/iscriplib.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iscriplib.h" - diff --git a/include/iscriplib.h b/include/iscriplib.h index 98d85c27..8f645033 100644 --- a/include/iscriplib.h +++ b/include/iscriplib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ISCRIPLIB_H) +#if !defined( INCLUDED_ISCRIPLIB_H ) #define INCLUDED_ISCRIPLIB_H /// \file iscriplib.h @@ -28,17 +28,17 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include #include "generic/constant.h" -#define MAXTOKEN 1024 +#define MAXTOKEN 1024 class Tokeniser { public: - virtual void release() = 0; - virtual void nextLine() = 0; - virtual const char* getToken() = 0; - virtual void ungetToken() = 0; - virtual std::size_t getLine() const = 0; - virtual std::size_t getColumn() const = 0; +virtual void release() = 0; +virtual void nextLine() = 0; +virtual const char* getToken() = 0; +virtual void ungetToken() = 0; +virtual std::size_t getLine() const = 0; +virtual std::size_t getColumn() const = 0; }; class TextInputStream; @@ -46,25 +46,25 @@ class TextInputStream; class TokenWriter { public: - virtual void release() = 0; - virtual void nextLine() = 0; - virtual void writeToken(const char* token) = 0; - virtual void writeString(const char* string) = 0; - virtual void writeInteger(int i) = 0; - virtual void writeUnsigned(std::size_t i) = 0; - virtual void writeFloat(double f) = 0; +virtual void release() = 0; +virtual void nextLine() = 0; +virtual void writeToken( const char* token ) = 0; +virtual void writeString( const char* string ) = 0; +virtual void writeInteger( int i ) = 0; +virtual void writeUnsigned( std::size_t i ) = 0; +virtual void writeFloat( double f ) = 0; }; class TextOutputStream; struct _QERScripLibTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "scriptlib"); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "scriptlib" ); - Tokeniser& (* m_pfnNewScriptTokeniser)(TextInputStream& istream); - Tokeniser& (* m_pfnNewSimpleTokeniser)(TextInputStream& istream); - TokenWriter& (* m_pfnNewSimpleTokenWriter)(TextOutputStream& ostream); + Tokeniser& ( *m_pfnNewScriptTokeniser )( TextInputStream & istream ); + Tokeniser& ( *m_pfnNewSimpleTokeniser )( TextInputStream & istream ); + TokenWriter& ( *m_pfnNewSimpleTokenWriter )( TextOutputStream & ostream ); }; #include "modulesystem.h" @@ -77,9 +77,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef<_QERScripLibTable> GlobalScripLibModuleRef; -inline _QERScripLibTable& GlobalScriptLibrary() -{ - return GlobalScripLibModule::getTable(); +inline _QERScripLibTable& GlobalScriptLibrary(){ + return GlobalScripLibModule::getTable(); } #endif diff --git a/include/iselection.cpp b/include/iselection.cpp index 2438d313..c0686cf2 100644 --- a/include/iselection.cpp +++ b/include/iselection.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iselection.h" - diff --git a/include/iselection.h b/include/iselection.h index ec32561e..f5c76310 100644 --- a/include/iselection.h +++ b/include/iselection.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ISELECTION_H) +#if !defined( INCLUDED_ISELECTION_H ) #define INCLUDED_ISELECTION_H #include @@ -33,21 +33,21 @@ class View; class Selectable { public: - STRING_CONSTANT(Name, "Selectable"); +STRING_CONSTANT( Name, "Selectable" ); - virtual void setSelected(bool select) = 0; - virtual bool isSelected() const = 0; +virtual void setSelected( bool select ) = 0; +virtual bool isSelected() const = 0; }; namespace scene { - class Instance; +class Instance; }; class InstanceSelectionObserver { public: - virtual void onSelectedChanged(scene::Instance& instance) = 0; +virtual void onSelectedChanged( scene::Instance& instance ) = 0; }; template class BasicVector3; @@ -63,67 +63,67 @@ typedef SignalHandler1 SelectionChangeHandler; class SelectionSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "selection"); - - enum EMode - { - eEntity, - ePrimitive, - eComponent, - }; - - enum EComponentMode - { - eDefault, - eVertex, - eEdge, - eFace, - }; - - enum EManipulatorMode - { - eTranslate, - eRotate, - eScale, - eDrag, - eClip, - }; - - virtual void SetMode(EMode mode) = 0; - virtual EMode Mode() const = 0; - virtual void SetComponentMode(EComponentMode mode) = 0; - virtual EComponentMode ComponentMode() const = 0; - virtual void SetManipulatorMode(EManipulatorMode mode) = 0; - virtual EManipulatorMode ManipulatorMode() const = 0; - - virtual SelectionChangeCallback getObserver(EMode mode) = 0; - virtual std::size_t countSelected() const = 0; - virtual std::size_t countSelectedComponents() const = 0; - virtual void onSelectedChanged(scene::Instance& instance, const Selectable& selectable) = 0; - virtual void onComponentSelection(scene::Instance& instance, const Selectable& selectable) = 0; - virtual scene::Instance& ultimateSelected() const = 0; - virtual scene::Instance& penultimateSelected() const = 0; - virtual void setSelectedAll(bool selected) = 0; - virtual void setSelectedAllComponents(bool selected) = 0; - - class Visitor - { - public: - virtual void visit(scene::Instance& instance) const = 0; - }; - virtual void foreachSelected(const Visitor& visitor) const = 0; - virtual void foreachSelectedComponent(const Visitor& visitor) const = 0; - - virtual void addSelectionChangeCallback(const SelectionChangeHandler& handler) = 0; - - virtual void NudgeManipulator(const Vector3& nudge, const Vector3& view) = 0; - - virtual void translateSelected(const Vector3& translation) = 0; - virtual void rotateSelected(const Quaternion& rotation) = 0; - virtual void scaleSelected(const Vector3& scaling) = 0; - - virtual void pivotChanged() const = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "selection" ); + +enum EMode +{ + eEntity, + ePrimitive, + eComponent, +}; + +enum EComponentMode +{ + eDefault, + eVertex, + eEdge, + eFace, +}; + +enum EManipulatorMode +{ + eTranslate, + eRotate, + eScale, + eDrag, + eClip, +}; + +virtual void SetMode( EMode mode ) = 0; +virtual EMode Mode() const = 0; +virtual void SetComponentMode( EComponentMode mode ) = 0; +virtual EComponentMode ComponentMode() const = 0; +virtual void SetManipulatorMode( EManipulatorMode mode ) = 0; +virtual EManipulatorMode ManipulatorMode() const = 0; + +virtual SelectionChangeCallback getObserver( EMode mode ) = 0; +virtual std::size_t countSelected() const = 0; +virtual std::size_t countSelectedComponents() const = 0; +virtual void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ) = 0; +virtual void onComponentSelection( scene::Instance& instance, const Selectable& selectable ) = 0; +virtual scene::Instance& ultimateSelected() const = 0; +virtual scene::Instance& penultimateSelected() const = 0; +virtual void setSelectedAll( bool selected ) = 0; +virtual void setSelectedAllComponents( bool selected ) = 0; + +class Visitor +{ +public: +virtual void visit( scene::Instance& instance ) const = 0; +}; +virtual void foreachSelected( const Visitor& visitor ) const = 0; +virtual void foreachSelectedComponent( const Visitor& visitor ) const = 0; + +virtual void addSelectionChangeCallback( const SelectionChangeHandler& handler ) = 0; + +virtual void NudgeManipulator( const Vector3& nudge, const Vector3& view ) = 0; + +virtual void translateSelected( const Vector3& translation ) = 0; +virtual void rotateSelected( const Quaternion& rotation ) = 0; +virtual void scaleSelected( const Vector3& scaling ) = 0; + +virtual void pivotChanged() const = 0; }; #include "modulesystem.h" @@ -136,9 +136,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalSelectionModuleRef; -inline SelectionSystem& GlobalSelectionSystem() -{ - return GlobalSelectionModule::getTable(); +inline SelectionSystem& GlobalSelectionSystem(){ + return GlobalSelectionModule::getTable(); } diff --git a/include/ishaders.cpp b/include/ishaders.cpp index bf380198..4a7affdd 100644 --- a/include/ishaders.cpp +++ b/include/ishaders.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "ishaders.h" - diff --git a/include/ishaders.h b/include/ishaders.h index 928dd1de..ac447090 100644 --- a/include/ishaders.h +++ b/include/ishaders.h @@ -1,25 +1,25 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ISHADERS_H) +#if !defined( INCLUDED_ISHADERS_H ) #define INCLUDED_ISHADERS_H #include "generic/constant.h" @@ -27,18 +27,18 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA enum { - QER_TRANS = 1 << 0, - QER_NOCARVE = 1 << 1, - QER_NODRAW = 1 << 2, - QER_NONSOLID = 1 << 3, - QER_WATER = 1 << 4, - QER_LAVA = 1 << 5, - QER_FOG = 1 << 6, - QER_ALPHATEST = 1 << 7, - QER_CULL = 1 << 8, - QER_AREAPORTAL = 1 << 9, - QER_CLIP = 1 << 10, - QER_BOTCLIP = 1 << 11, + QER_TRANS = 1 << 0, + QER_NOCARVE = 1 << 1, + QER_NODRAW = 1 << 2, + QER_NONSOLID = 1 << 3, + QER_WATER = 1 << 4, + QER_LAVA = 1 << 5, + QER_FOG = 1 << 6, + QER_ALPHATEST = 1 << 7, + QER_CULL = 1 << 8, + QER_AREAPORTAL = 1 << 9, + QER_CLIP = 1 << 10, + QER_BOTCLIP = 1 << 11, }; struct qtexture_t; @@ -63,20 +63,19 @@ const BlendFactor BLEND_SRC_ALPHA_SATURATE = 10; class BlendFunc { public: - BlendFunc(BlendFactor src, BlendFactor dst) : m_src(src), m_dst(dst) - { - } - BlendFactor m_src; - BlendFactor m_dst; +BlendFunc( BlendFactor src, BlendFactor dst ) : m_src( src ), m_dst( dst ){ +} +BlendFactor m_src; +BlendFactor m_dst; }; class ShaderLayer { public: - virtual qtexture_t* texture() const = 0; - virtual BlendFunc blendFunc() const = 0; - virtual bool clampToBorder() const = 0; - virtual float alphaTest() const = 0; +virtual qtexture_t* texture() const = 0; +virtual BlendFunc blendFunc() const = 0; +virtual bool clampToBorder() const = 0; +virtual float alphaTest() const = 0; }; typedef Callback1 ShaderLayerCallback; @@ -85,51 +84,51 @@ typedef Callback1 ShaderLayerCallback; class IShader { public: - enum EAlphaFunc - { - eAlways, - eEqual, - eLess, - eGreater, - eLEqual, - eGEqual, - }; - enum ECull - { - eCullNone, - eCullBack, - }; - // Increment the number of references to this object - virtual void IncRef() = 0; - // Decrement the reference count - virtual void DecRef() = 0; - // get/set the qtexture_t* Radiant uses to represent this shader object - virtual qtexture_t* getTexture() const = 0; - virtual qtexture_t* getDiffuse() const = 0; - virtual qtexture_t* getBump() const = 0; - virtual qtexture_t* getSpecular() const = 0; - // get shader name - virtual const char* getName() const = 0; - virtual bool IsInUse() const = 0; - virtual void SetInUse(bool bInUse) = 0; - // get the editor flags (QER_NOCARVE QER_TRANS) - virtual int getFlags() const = 0; - // get the transparency value - virtual float getTrans() const = 0; - // test if it's a true shader, or a default shader created to wrap around a texture - virtual bool IsDefault() const = 0; - // get the alphaFunc - virtual void getAlphaFunc(EAlphaFunc *func, float *ref) = 0; - virtual BlendFunc getBlendFunc() const = 0; - // get the cull type - virtual ECull getCull() = 0; - // get shader file name (ie the file where this one is defined) - virtual const char* getShaderFileName() const = 0; - - virtual const ShaderLayer* firstLayer() const = 0; - virtual void forEachLayer(const ShaderLayerCallback& layer) const = 0; - - virtual qtexture_t* lightFalloffImage() const = 0; +enum EAlphaFunc +{ + eAlways, + eEqual, + eLess, + eGreater, + eLEqual, + eGEqual, +}; +enum ECull +{ + eCullNone, + eCullBack, +}; +// Increment the number of references to this object +virtual void IncRef() = 0; +// Decrement the reference count +virtual void DecRef() = 0; +// get/set the qtexture_t* Radiant uses to represent this shader object +virtual qtexture_t* getTexture() const = 0; +virtual qtexture_t* getDiffuse() const = 0; +virtual qtexture_t* getBump() const = 0; +virtual qtexture_t* getSpecular() const = 0; +// get shader name +virtual const char* getName() const = 0; +virtual bool IsInUse() const = 0; +virtual void SetInUse( bool bInUse ) = 0; +// get the editor flags (QER_NOCARVE QER_TRANS) +virtual int getFlags() const = 0; +// get the transparency value +virtual float getTrans() const = 0; +// test if it's a true shader, or a default shader created to wrap around a texture +virtual bool IsDefault() const = 0; +// get the alphaFunc +virtual void getAlphaFunc( EAlphaFunc *func, float *ref ) = 0; +virtual BlendFunc getBlendFunc() const = 0; +// get the cull type +virtual ECull getCull() = 0; +// get shader file name (ie the file where this one is defined) +virtual const char* getShaderFileName() const = 0; + +virtual const ShaderLayer* firstLayer() const = 0; +virtual void forEachLayer( const ShaderLayerCallback& layer ) const = 0; + +virtual qtexture_t* lightFalloffImage() const = 0; }; typedef struct _GSList GSList; @@ -140,34 +139,34 @@ class ModuleObserver; class ShaderSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "shaders"); - // NOTE: shader and texture names used must be full path. - // Shaders usable as textures have prefix equal to getTexturePrefix() +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "shaders" ); +// NOTE: shader and texture names used must be full path. +// Shaders usable as textures have prefix equal to getTexturePrefix() - virtual void realise() = 0; - virtual void unrealise() = 0; - virtual void refresh() = 0; - // activate the shader for a given name and return it - // will return the default shader if name is not found - virtual IShader* getShaderForName(const char* name) = 0; +virtual void realise() = 0; +virtual void unrealise() = 0; +virtual void refresh() = 0; +// activate the shader for a given name and return it +// will return the default shader if name is not found +virtual IShader* getShaderForName( const char* name ) = 0; - virtual void foreachShaderName(const ShaderNameCallback& callback) = 0; +virtual void foreachShaderName( const ShaderNameCallback& callback ) = 0; - // iterate over the list of active shaders - virtual void beginActiveShadersIterator() = 0; - virtual bool endActiveShadersIterator() = 0; - virtual IShader* dereferenceActiveShadersIterator() = 0; - virtual void incrementActiveShadersIterator() = 0; +// iterate over the list of active shaders +virtual void beginActiveShadersIterator() = 0; +virtual bool endActiveShadersIterator() = 0; +virtual IShader* dereferenceActiveShadersIterator() = 0; +virtual void incrementActiveShadersIterator() = 0; - virtual void setActiveShadersChangedNotify(const Callback& notify) = 0; +virtual void setActiveShadersChangedNotify( const Callback& notify ) = 0; - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; +virtual void attach( ModuleObserver& observer ) = 0; +virtual void detach( ModuleObserver& observer ) = 0; - virtual void setLightingEnabled(bool enabled) = 0; +virtual void setLightingEnabled( bool enabled ) = 0; - virtual const char* getTexturePrefix() const = 0; +virtual const char* getTexturePrefix() const = 0; }; #include "modulesystem.h" @@ -180,9 +179,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalShadersModuleRef; -inline ShaderSystem& GlobalShaderSystem() -{ - return GlobalShadersModule::getTable(); +inline ShaderSystem& GlobalShaderSystem(){ + return GlobalShadersModule::getTable(); } diff --git a/include/itexdef.cpp b/include/itexdef.cpp index 1973c960..462a7a2f 100644 --- a/include/itexdef.cpp +++ b/include/itexdef.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "itexdef.h" - diff --git a/include/itexdef.h b/include/itexdef.h index a299843b..9d01847f 100644 --- a/include/itexdef.h +++ b/include/itexdef.h @@ -1,42 +1,41 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_ITEXDEF_H) +#if !defined ( INCLUDED_ITEXDEF_H ) #define INCLUDED_ITEXDEF_H class texdef_t { public: - float shift[2]; - float rotate; - float scale[2]; - - texdef_t() - { - shift[0] = 0; - shift[1] = 0; - rotate = 0; - scale[0] = 1; - scale[1] = 1; - } +float shift[2]; +float rotate; +float scale[2]; + +texdef_t(){ + shift[0] = 0; + shift[1] = 0; + rotate = 0; + scale[0] = 1; + scale[1] = 1; +} }; #endif diff --git a/include/itextstream.cpp b/include/itextstream.cpp index c93ae35a..3ce3df75 100644 --- a/include/itextstream.cpp +++ b/include/itextstream.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "itextstream.h" - diff --git a/include/itextstream.h b/include/itextstream.h index 891336e7..7d69c7b5 100644 --- a/include/itextstream.h +++ b/include/itextstream.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ITEXTSTREAM_H) +#if !defined( INCLUDED_ITEXTSTREAM_H ) #define INCLUDED_ITEXTSTREAM_H /// \file @@ -32,83 +32,76 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class TextInputStream { public: - /// \brief Attempts to read the next \p length characters from the stream to \p buffer. - /// Returns the number of characters actually stored in \p buffer. - virtual std::size_t read(char* buffer, std::size_t length) = 0; +/// \brief Attempts to read the next \p length characters from the stream to \p buffer. +/// Returns the number of characters actually stored in \p buffer. +virtual std::size_t read( char* buffer, std::size_t length ) = 0; }; /// \brief A write-only character-stream. class TextOutputStream { public: - /// \brief Attempts to write \p length characters to the stream from \p buffer. - /// Returns the number of characters actually read from \p buffer. - virtual std::size_t write(const char* buffer, std::size_t length) = 0; +/// \brief Attempts to write \p length characters to the stream from \p buffer. +/// Returns the number of characters actually read from \p buffer. +virtual std::size_t write( const char* buffer, std::size_t length ) = 0; }; /// \brief Calls the overloaded function ostream_write() to perform text formatting specific to the type being written. /*! Note that ostream_write() is not globally defined - it must be defined once for each type supported.\n -To support writing a custom type MyClass to any kind of text-output-stream with operator<<: -\code -template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const MyClass& myClass) -{ - return ostream << myClass.getName() << ' ' << myClass.getText(); -} -\endcode -Expressing this as a template allows it to be used directly with any concrete text-output-stream type, not just the abstract TextOutputStream\n -\n -This overload writes a single character to any text-output-stream - ostream_write(TextOutputStreamType& ostream, char c). -*/ + To support writing a custom type MyClass to any kind of text-output-stream with operator<<: + \code + template + TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const MyClass& myClass) + { + return ostream << myClass.getName() << ' ' << myClass.getText(); + } + \endcode + Expressing this as a template allows it to be used directly with any concrete text-output-stream type, not just the abstract TextOutputStream\n + \n + This overload writes a single character to any text-output-stream - ostream_write(TextOutputStreamType& ostream, char c). + */ template -inline TextOutputStream& operator<<(TextOutputStream& ostream, const T& t) -{ - return ostream_write(ostream, t); +inline TextOutputStream& operator<<( TextOutputStream& ostream, const T& t ){ + return ostream_write( ostream, t ); } class NullOutputStream : public TextOutputStream { public: - std::size_t write(const char*, std::size_t length) - { - return length; - } +std::size_t write( const char*, std::size_t length ){ + return length; +} }; class OutputStreamHolder { - NullOutputStream m_nullOutputStream; - TextOutputStream* m_outputStream; +NullOutputStream m_nullOutputStream; +TextOutputStream* m_outputStream; public: - OutputStreamHolder() - : m_outputStream(&m_nullOutputStream) - { - } - void setOutputStream(TextOutputStream& outputStream) - { - m_outputStream = &outputStream; - } - TextOutputStream& getOutputStream() - { - return *m_outputStream; - } +OutputStreamHolder() + : m_outputStream( &m_nullOutputStream ){ +} +void setOutputStream( TextOutputStream& outputStream ){ + m_outputStream = &outputStream; +} +TextOutputStream& getOutputStream(){ + return *m_outputStream; +} }; typedef Static GlobalOutputStream; /// \brief Returns the global output stream. Used to display messages to the user. -inline TextOutputStream& globalOutputStream() -{ - return GlobalOutputStream::instance().getOutputStream(); +inline TextOutputStream& globalOutputStream(){ + return GlobalOutputStream::instance().getOutputStream(); } class ErrorStreamHolder : public OutputStreamHolder {}; typedef Static GlobalErrorStream; /// \brief Returns the global error stream. Used to display error messages to the user. -inline TextOutputStream& globalErrorStream() -{ - return GlobalErrorStream::instance().getOutputStream(); +inline TextOutputStream& globalErrorStream(){ + return GlobalErrorStream::instance().getOutputStream(); } #endif diff --git a/include/itextures.cpp b/include/itextures.cpp index 26e2bf6d..ae75c635 100644 --- a/include/itextures.cpp +++ b/include/itextures.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "itextures.h" - diff --git a/include/itextures.h b/include/itextures.h index 368e7b76..cc91399d 100644 --- a/include/itextures.h +++ b/include/itextures.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ITEXTURES_H) +#if !defined( INCLUDED_ITEXTURES_H ) #define INCLUDED_ITEXTURES_H #include "iimage.h" @@ -29,49 +29,45 @@ struct qtexture_t; class LoadImageCallback { - typedef Image* (*LoadFunc)(void* environment, const char* name); +typedef Image* ( *LoadFunc )( void* environment, const char* name ); public: - void* m_environment; - LoadFunc m_func; - - LoadImageCallback(void* environment, LoadFunc func) : m_environment(environment), m_func(func) - { - } - Image* loadImage(const char* name) const - { - return m_func(m_environment, name); - } +void* m_environment; +LoadFunc m_func; + +LoadImageCallback( void* environment, LoadFunc func ) : m_environment( environment ), m_func( func ){ +} +Image* loadImage( const char* name ) const { + return m_func( m_environment, name ); +} }; -inline bool operator==(const LoadImageCallback& self, const LoadImageCallback& other) -{ - return self.m_environment == other.m_environment && self.m_func == other.m_func; +inline bool operator==( const LoadImageCallback& self, const LoadImageCallback& other ){ + return self.m_environment == other.m_environment && self.m_func == other.m_func; } -inline bool operator<(const LoadImageCallback& self, const LoadImageCallback& other) -{ - return self.m_environment < other.m_environment || - (!(other.m_environment < self.m_environment) && self.m_func < other.m_func); +inline bool operator<( const LoadImageCallback& self, const LoadImageCallback& other ){ + return self.m_environment < other.m_environment || + ( !( other.m_environment < self.m_environment ) && self.m_func < other.m_func ); } class TexturesCacheObserver { public: - virtual void unrealise() = 0; - virtual void realise() = 0; +virtual void unrealise() = 0; +virtual void realise() = 0; }; class TexturesCache { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "textures"); - virtual LoadImageCallback defaultLoader() const = 0; - virtual Image* loadImage(const char* name) = 0; - virtual qtexture_t* capture(const char* name) = 0; - virtual qtexture_t* capture(const LoadImageCallback& load, const char* name) = 0; - virtual void release(qtexture_t* texture) = 0; - virtual void attach(TexturesCacheObserver& observer) = 0; - virtual void detach(TexturesCacheObserver& observer) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "textures" ); +virtual LoadImageCallback defaultLoader() const = 0; +virtual Image* loadImage( const char* name ) = 0; +virtual qtexture_t* capture( const char* name ) = 0; +virtual qtexture_t* capture( const LoadImageCallback& load, const char* name ) = 0; +virtual void release( qtexture_t* texture ) = 0; +virtual void attach( TexturesCacheObserver& observer ) = 0; +virtual void detach( TexturesCacheObserver& observer ) = 0; }; #include "modulesystem.h" @@ -84,9 +80,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalTexturesModuleRef; -inline TexturesCache& GlobalTexturesCache() -{ - return GlobalTexturesModule::getTable(); +inline TexturesCache& GlobalTexturesCache(){ + return GlobalTexturesModule::getTable(); } #endif diff --git a/include/itoolbar.cpp b/include/itoolbar.cpp index 2c989b6a..146f7551 100644 --- a/include/itoolbar.cpp +++ b/include/itoolbar.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "itoolbar.h" - diff --git a/include/itoolbar.h b/include/itoolbar.h index 350e5a5f..62d82b6e 100644 --- a/include/itoolbar.h +++ b/include/itoolbar.h @@ -1,25 +1,25 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IPLUGTOOLBAR_H) +#if !defined( INCLUDED_IPLUGTOOLBAR_H ) #define INCLUDED_IPLUGTOOLBAR_H #include @@ -28,31 +28,31 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class IToolbarButton { public: - enum EType - { - eSpace, - eButton, - eToggleButton, - eRadioButton, - }; +enum EType +{ + eSpace, + eButton, + eToggleButton, + eRadioButton, +}; - virtual const char* getImage() const = 0; - virtual const char* getText() const = 0; - virtual const char* getTooltip() const = 0; - virtual EType getType() const = 0; - virtual void activate() const = 0; +virtual const char* getImage() const = 0; +virtual const char* getText() const = 0; +virtual const char* getTooltip() const = 0; +virtual EType getType() const = 0; +virtual void activate() const = 0; }; -typedef std::size_t (* PFN_TOOLBARBUTTONCOUNT)(); -typedef const IToolbarButton* (* PFN_GETTOOLBARBUTTON)(std::size_t index); +typedef std::size_t ( *PFN_TOOLBARBUTTONCOUNT )(); +typedef const IToolbarButton* ( *PFN_GETTOOLBARBUTTON )( std::size_t index ); struct _QERPlugToolbarTable { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "toolbar"); + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "toolbar" ); - PFN_TOOLBARBUTTONCOUNT m_pfnToolbarButtonCount; - PFN_GETTOOLBARBUTTON m_pfnGetToolbarButton; + PFN_TOOLBARBUTTONCOUNT m_pfnToolbarButtonCount; + PFN_GETTOOLBARBUTTON m_pfnGetToolbarButton; }; template diff --git a/include/iundo.cpp b/include/iundo.cpp index 49b96b03..8dfd9e2d 100644 --- a/include/iundo.cpp +++ b/include/iundo.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "iundo.h" - diff --git a/include/iundo.h b/include/iundo.h index 4dcbad85..58f72d4b 100644 --- a/include/iundo.h +++ b/include/iundo.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IUNDO_H) +#if !defined( INCLUDED_IUNDO_H ) #define INCLUDED_IUNDO_H /// \file @@ -32,49 +32,49 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class UndoMemento { public: - virtual void release() = 0; +virtual void release() = 0; }; class Undoable { public: - virtual UndoMemento* exportState() const = 0; - virtual void importState(const UndoMemento* state) = 0; +virtual UndoMemento* exportState() const = 0; +virtual void importState( const UndoMemento* state ) = 0; }; class UndoObserver { public: - virtual void save(Undoable* undoable) = 0; +virtual void save( Undoable* undoable ) = 0; }; class UndoTracker { public: - virtual void clear() = 0; - virtual void begin() = 0; - virtual void undo() = 0; - virtual void redo() = 0; +virtual void clear() = 0; +virtual void begin() = 0; +virtual void undo() = 0; +virtual void redo() = 0; }; class UndoSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "undo"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "undo" ); - virtual UndoObserver* observer(Undoable* undoable) = 0; - virtual void release(Undoable* undoable) = 0; +virtual UndoObserver* observer( Undoable* undoable ) = 0; +virtual void release( Undoable* undoable ) = 0; - virtual std::size_t size() const = 0; - virtual void start() = 0; - virtual void finish(const char* command) = 0; - virtual void undo() = 0; - virtual void redo() = 0; - virtual void clear() = 0; +virtual std::size_t size() const = 0; +virtual void start() = 0; +virtual void finish( const char* command ) = 0; +virtual void undo() = 0; +virtual void redo() = 0; +virtual void clear() = 0; - virtual void trackerAttach(UndoTracker& tracker) = 0; - virtual void trackerDetach(UndoTracker& tracker) = 0; +virtual void trackerAttach( UndoTracker& tracker ) = 0; +virtual void trackerDetach( UndoTracker& tracker ) = 0; }; #include "modulesystem.h" @@ -87,23 +87,20 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalUndoModuleRef; -inline UndoSystem& GlobalUndoSystem() -{ - return GlobalUndoModule::getTable(); +inline UndoSystem& GlobalUndoSystem(){ + return GlobalUndoModule::getTable(); } class UndoableCommand { - const char* m_command; +const char* m_command; public: - UndoableCommand(const char* command) : m_command(command) - { - GlobalUndoSystem().start(); - } - ~UndoableCommand() - { - GlobalUndoSystem().finish(m_command); - } +UndoableCommand( const char* command ) : m_command( command ){ + GlobalUndoSystem().start(); +} +~UndoableCommand(){ + GlobalUndoSystem().finish( m_command ); +} }; diff --git a/include/mapfile.cpp b/include/mapfile.cpp index 1065f591..5a6332ee 100644 --- a/include/mapfile.cpp +++ b/include/mapfile.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "mapfile.h" - diff --git a/include/mapfile.h b/include/mapfile.h index e53d79c1..df1ab36f 100644 --- a/include/mapfile.h +++ b/include/mapfile.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MAPFILE_H) +#if !defined( INCLUDED_MAPFILE_H ) #define INCLUDED_MAPFILE_H #include @@ -32,43 +32,39 @@ const std::size_t MAPFILE_MAX_CHANGES = std::numeric_limits::max(); class MapFile { public: - STRING_CONSTANT(Name, "MapFile"); +STRING_CONSTANT( Name, "MapFile" ); - virtual void save() = 0; - virtual bool saved() const = 0; - virtual void changed() = 0; - virtual void setChangedCallback(const Callback& changed) = 0; - virtual std::size_t changes() const = 0; +virtual void save() = 0; +virtual bool saved() const = 0; +virtual void changed() = 0; +virtual void setChangedCallback( const Callback& changed ) = 0; +virtual std::size_t changes() const = 0; }; #include "scenelib.h" -inline MapFile* Node_getMapFile(scene::Node& node) -{ - return NodeTypeCast::cast(node); +inline MapFile* Node_getMapFile( scene::Node& node ){ + return NodeTypeCast::cast( node ); } template -inline MapFile* path_find_mapfile(Iterator first, Iterator last) -{ - Iterator i = last; - for(;;) - { - --i; - - MapFile* map = Node_getMapFile(*i); - if(map != 0) - { - return map; - } - - if(i == first) - { - break; - } - } - ERROR_MESSAGE("failed to find parent mapfile for path"); - return 0; +inline MapFile* path_find_mapfile( Iterator first, Iterator last ){ + Iterator i = last; + for (;; ) + { + --i; + + MapFile* map = Node_getMapFile( *i ); + if ( map != 0 ) { + return map; + } + + if ( i == first ) { + break; + } + } + ERROR_MESSAGE( "failed to find parent mapfile for path" ); + return 0; } diff --git a/include/modelskin.cpp b/include/modelskin.cpp index 6d34f272..fcdda390 100644 --- a/include/modelskin.cpp +++ b/include/modelskin.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "modelskin.h" - diff --git a/include/modelskin.h b/include/modelskin.h index c01b5f30..bb5922ee 100644 --- a/include/modelskin.h +++ b/include/modelskin.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODELSKIN_H) +#if !defined( INCLUDED_MODELSKIN_H ) #define INCLUDED_MODELSKIN_H #include "generic/constant.h" @@ -28,11 +28,10 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class SkinRemap { public: - const char* m_from; - const char* m_to; - SkinRemap(const char* from, const char* to) : m_from(from), m_to(to) - { - } +const char* m_from; +const char* m_to; +SkinRemap( const char* from, const char* to ) : m_from( from ), m_to( to ){ +} }; typedef Callback1 SkinRemapCallback; @@ -41,36 +40,36 @@ class ModuleObserver; class ModelSkin { public: - STRING_CONSTANT(Name, "ModelSkin"); - /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the skin is loaded or unloaded. - virtual void attach(ModuleObserver& observer) = 0; - /// \brief Detach an \p observer previously-attached by calling \c attach. - virtual void detach(ModuleObserver& observer) = 0; - /// \brief Returns true if this skin is currently loaded. - virtual bool realised() const = 0; - /// \brief Returns the shader identifier that \p name remaps to, or "" if not found or not realised. - virtual const char* getRemap(const char* name) const = 0; - /// \brief Calls \p callback for each remap pair. Has no effect if not realised. - virtual void forEachRemap(const SkinRemapCallback& callback) const = 0; +STRING_CONSTANT( Name, "ModelSkin" ); +/// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the skin is loaded or unloaded. +virtual void attach( ModuleObserver& observer ) = 0; +/// \brief Detach an \p observer previously-attached by calling \c attach. +virtual void detach( ModuleObserver& observer ) = 0; +/// \brief Returns true if this skin is currently loaded. +virtual bool realised() const = 0; +/// \brief Returns the shader identifier that \p name remaps to, or "" if not found or not realised. +virtual const char* getRemap( const char* name ) const = 0; +/// \brief Calls \p callback for each remap pair. Has no effect if not realised. +virtual void forEachRemap( const SkinRemapCallback& callback ) const = 0; }; class SkinnedModel { public: - STRING_CONSTANT(Name, "SkinnedModel"); - /// \brief Instructs the skinned model to update its skin. - virtual void skinChanged() = 0; +STRING_CONSTANT( Name, "SkinnedModel" ); +/// \brief Instructs the skinned model to update its skin. +virtual void skinChanged() = 0; }; class ModelSkinCache { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "modelskin"); - /// \brief Increments the reference count of and returns a reference to the skin uniquely identified by 'name'. - virtual ModelSkin& capture(const char* name) = 0; - /// \brief Decrements the reference-count of the skin uniquely identified by 'name'. - virtual void release(const char* name) = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "modelskin" ); +/// \brief Increments the reference count of and returns a reference to the skin uniquely identified by 'name'. +virtual ModelSkin& capture( const char* name ) = 0; +/// \brief Decrements the reference-count of the skin uniquely identified by 'name'. +virtual void release( const char* name ) = 0; }; @@ -84,9 +83,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalModelSkinCacheModuleRef; -inline ModelSkinCache& GlobalModelSkinCache() -{ - return GlobalModelSkinCacheModule::getTable(); +inline ModelSkinCache& GlobalModelSkinCache(){ + return GlobalModelSkinCacheModule::getTable(); } #endif diff --git a/include/moduleobserver.cpp b/include/moduleobserver.cpp index fa26f8d9..f9d40b12 100644 --- a/include/moduleobserver.cpp +++ b/include/moduleobserver.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "moduleobserver.h" - diff --git a/include/moduleobserver.h b/include/moduleobserver.h index e218b4aa..496d6f2e 100644 --- a/include/moduleobserver.h +++ b/include/moduleobserver.h @@ -1,32 +1,32 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULEOBSERVER_H) +#if !defined( INCLUDED_MODULEOBSERVER_H ) #define INCLUDED_MODULEOBSERVER_H class ModuleObserver { public: - virtual void unrealise() = 0; - virtual void realise() = 0; +virtual void unrealise() = 0; +virtual void realise() = 0; }; #endif diff --git a/include/modulesystem.cpp b/include/modulesystem.cpp index 6b7a27c9..907e8f7c 100644 --- a/include/modulesystem.cpp +++ b/include/modulesystem.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "modulesystem.h" - diff --git a/include/modulesystem.h b/include/modulesystem.h index 0378cc1d..8b1913fb 100644 --- a/include/modulesystem.h +++ b/include/modulesystem.h @@ -1,34 +1,34 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULESYSTEM_H) +#if !defined( INCLUDED_MODULESYSTEM_H ) #define INCLUDED_MODULESYSTEM_H #include "generic/static.h" #include "debugging/debugging.h" -#if defined(WIN32) +#if defined( WIN32 ) #ifdef MINGW32 -#define RADIANT_DLLEXPORT __declspec(dllexport) -#define RADIANT_DLLIMPORT __declspec(dllimport) +#define RADIANT_DLLEXPORT __declspec( dllexport ) +#define RADIANT_DLLIMPORT __declspec( dllimport ) #else #define RADIANT_DLLEXPORT __stdcall #define RADIANT_DLLIMPORT __stdcall @@ -42,14 +42,13 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class Module { public: - virtual void capture() = 0; - virtual void release() = 0; - virtual void* getTable() = 0; +virtual void capture() = 0; +virtual void release() = 0; +virtual void* getTable() = 0; }; -inline void* Module_getTable(Module& module) -{ - return module.getTable(); +inline void* Module_getTable( Module& module ){ + return module.getTable(); } class TextOutputStream; @@ -58,56 +57,51 @@ class DebugMessageHandler; class ModuleServer { public: - class Visitor - { - public: - virtual void visit(const char* name, Module& module) const = 0; - }; - - virtual void setError(bool error) = 0; - virtual bool getError() const = 0; - - virtual TextOutputStream& getOutputStream() = 0; - virtual TextOutputStream& getErrorStream() = 0; - virtual DebugMessageHandler& getDebugMessageHandler() = 0; - - virtual void registerModule(const char* type, int version, const char* name, Module& module) = 0; - virtual Module* findModule(const char* type, int version, const char* name) const = 0; - virtual void foreachModule(const char* type, int version, const Visitor& visitor) = 0; +class Visitor +{ +public: +virtual void visit( const char* name, Module& module ) const = 0; +}; + +virtual void setError( bool error ) = 0; +virtual bool getError() const = 0; + +virtual TextOutputStream& getOutputStream() = 0; +virtual TextOutputStream& getErrorStream() = 0; +virtual DebugMessageHandler& getDebugMessageHandler() = 0; + +virtual void registerModule( const char* type, int version, const char* name, Module& module ) = 0; +virtual Module* findModule( const char* type, int version, const char* name ) const = 0; +virtual void foreachModule( const char* type, int version, const Visitor& visitor ) = 0; }; class ModuleServerHolder { - ModuleServer* m_server; +ModuleServer* m_server; public: - ModuleServerHolder() - : m_server(0) - { - } - void set(ModuleServer& server) - { - m_server = &server; - } - ModuleServer& get() - { - return *m_server; - } +ModuleServerHolder() + : m_server( 0 ){ +} +void set( ModuleServer& server ){ + m_server = &server; +} +ModuleServer& get(){ + return *m_server; +} }; typedef Static GlobalModuleServer; -inline ModuleServer& globalModuleServer() -{ - return GlobalModuleServer::instance().get(); +inline ModuleServer& globalModuleServer(){ + return GlobalModuleServer::instance().get(); } -inline void initialiseModule(ModuleServer& server) -{ - GlobalErrorStream::instance().setOutputStream(server.getErrorStream()); - GlobalOutputStream::instance().setOutputStream(server.getOutputStream()); - GlobalDebugMessageHandler::instance().setHandler(server.getDebugMessageHandler()); - GlobalModuleServer::instance().set(server); +inline void initialiseModule( ModuleServer& server ){ + GlobalErrorStream::instance().setOutputStream( server.getErrorStream() ); + GlobalOutputStream::instance().setOutputStream( server.getOutputStream() ); + GlobalDebugMessageHandler::instance().setHandler( server.getDebugMessageHandler() ); + GlobalModuleServer::instance().set( server ); } @@ -116,14 +110,14 @@ template class Modules { public: - class Visitor - { - public: - virtual void visit(const char* name, const Type& table) const = 0; - }; - - virtual Type* findModule(const char* name) = 0; - virtual void foreachModule(const Visitor& visitor) = 0; +class Visitor +{ +public: +virtual void visit( const char* name, const Type& table ) const = 0; +}; + +virtual Type* findModule( const char* name ) = 0; +virtual void foreachModule( const Visitor& visitor ) = 0; }; #include "debugging/debugging.h" @@ -131,109 +125,91 @@ public: template class ModuleRef { - Module* m_module; - Type* m_table; +Module* m_module; +Type* m_table; public: - ModuleRef(const char* name) : m_table(0) - { - if(!globalModuleServer().getError()) - { - m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(m_module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - } - else - { - m_module->capture(); - if(!globalModuleServer().getError()) - { - m_table = static_cast(m_module->getTable()); - } - } - } - } - ~ModuleRef() - { - if(m_module != 0) - { - m_module->release(); - } - } - Type* getTable() - { -#if defined(_DEBUG) - ASSERT_MESSAGE(m_table != 0, "ModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); +ModuleRef( const char* name ) : m_table( 0 ){ + if ( !globalModuleServer().getError() ) { + m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( m_module == 0 ) { + globalModuleServer().setError( true ); + globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + } + else + { + m_module->capture(); + if ( !globalModuleServer().getError() ) { + m_table = static_cast( m_module->getTable() ); + } + } + } +} +~ModuleRef(){ + if ( m_module != 0 ) { + m_module->release(); + } +} +Type* getTable(){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( m_table != 0, "ModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); #endif - return m_table; - } + return m_table; +} }; template class SingletonModuleRef { - Module* m_module; - Type* m_table; +Module* m_module; +Type* m_table; public: - SingletonModuleRef() - : m_module(0), m_table(0) - { - } - - bool initialised() const - { - return m_module != 0; - } - - void initialise(const char* name) - { - m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(m_module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - } - } - - Type* getTable() - { -#if defined(_DEBUG) - ASSERT_MESSAGE(m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); +SingletonModuleRef() + : m_module( 0 ), m_table( 0 ){ +} + +bool initialised() const { + return m_module != 0; +} + +void initialise( const char* name ){ + m_module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( m_module == 0 ) { + globalModuleServer().setError( true ); + globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + } +} + +Type* getTable(){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " - module-reference used without being initialised" ); #endif - return m_table; - } - void capture() - { - if(initialised()) - { - m_module->capture(); - m_table = static_cast(m_module->getTable()); - } - } - void release() - { - if(initialised()) - { - m_module->release(); - } - } + return m_table; +} +void capture(){ + if ( initialised() ) { + m_module->capture(); + m_table = static_cast( m_module->getTable() ); + } +} +void release(){ + if ( initialised() ) { + m_module->release(); + } +} }; template class GlobalModule { - static SingletonModuleRef m_instance; +static SingletonModuleRef m_instance; public: - static SingletonModuleRef& instance() - { - return m_instance; - } - static Type& getTable() - { - return *m_instance.getTable(); - } +static SingletonModuleRef& instance(){ + return m_instance; +} +static Type& getTable(){ + return *m_instance.getTable(); +} }; template @@ -244,22 +220,18 @@ template class GlobalModuleRef { public: - GlobalModuleRef(const char* name = "*") - { - if(!globalModuleServer().getError()) - { - GlobalModule::instance().initialise(name); - } - GlobalModule::instance().capture(); - } - ~GlobalModuleRef() - { - GlobalModule::instance().release(); - } - Type& getTable() - { - return GlobalModule::getTable(); - } +GlobalModuleRef( const char* name = "*" ){ + if ( !globalModuleServer().getError() ) { + GlobalModule::instance().initialise( name ); + } + GlobalModule::instance().capture(); +} +~GlobalModuleRef(){ + GlobalModule::instance().release(); +} +Type& getTable(){ + return GlobalModule::getTable(); +} }; #endif diff --git a/include/nameable.cpp b/include/nameable.cpp index f401626c..8722c471 100644 --- a/include/nameable.cpp +++ b/include/nameable.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "nameable.h" - diff --git a/include/nameable.h b/include/nameable.h index 8e1357a4..bbc6f899 100644 --- a/include/nameable.h +++ b/include/nameable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_NAMEABLE_H) +#if !defined( INCLUDED_NAMEABLE_H ) #define INCLUDED_NAMEABLE_H #include "generic/constant.h" @@ -30,11 +30,11 @@ typedef Callback1 NameCallback; class Nameable { public: - STRING_CONSTANT(Name, "Nameable"); +STRING_CONSTANT( Name, "Nameable" ); - virtual const char* name() const = 0; - virtual void attach(const NameCallback& callback) = 0; - virtual void detach(const NameCallback& callback) = 0; +virtual const char* name() const = 0; +virtual void attach( const NameCallback& callback ) = 0; +virtual void detach( const NameCallback& callback ) = 0; }; diff --git a/include/namespace.cpp b/include/namespace.cpp index 2f322fda..f9b22f5b 100644 --- a/include/namespace.cpp +++ b/include/namespace.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "namespace.h" - diff --git a/include/namespace.h b/include/namespace.h index 30367bfd..9a00793c 100644 --- a/include/namespace.h +++ b/include/namespace.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_NAMESPACE_H) +#if !defined( INCLUDED_NAMESPACE_H ) #define INCLUDED_NAMESPACE_H #include "generic/constant.h" @@ -31,19 +31,19 @@ typedef Callback1 NameCallbackCallback; class Namespace { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "namespace"); - virtual void attach(const NameCallback& setName, const NameCallbackCallback& attachObserver) = 0; - virtual void detach(const NameCallback& setName, const NameCallbackCallback& detachObserver) = 0; - virtual void makeUnique(const char* name, const NameCallback& setName) const = 0; +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "namespace" ); +virtual void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ) = 0; +virtual void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ) = 0; +virtual void makeUnique( const char* name, const NameCallback& setName ) const = 0; }; class Namespaced { public: - STRING_CONSTANT(Name, "Namespaced"); +STRING_CONSTANT( Name, "Namespaced" ); - virtual void setNamespace(Namespace& space) = 0; +virtual void setNamespace( Namespace& space ) = 0; }; #include "modulesystem.h" @@ -56,8 +56,7 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalNamespaceModuleRef; -inline Namespace& GlobalNamespace() -{ - return GlobalNamespaceModule::getTable(); +inline Namespace& GlobalNamespace(){ + return GlobalNamespaceModule::getTable(); } #endif diff --git a/include/preferencesystem.cpp b/include/preferencesystem.cpp index a5fecd4d..6152cb14 100644 --- a/include/preferencesystem.cpp +++ b/include/preferencesystem.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #if 0 @@ -28,179 +28,160 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "xml/xmlwriter.h" -void LoadPrefs(PreferenceDictionary& preferences, const char* filename) -{ - TextFileInputStream file(filename); - if(!file.failed()) - { - XMLStreamParser parser(file); - XMLPreferenceDictionaryImporter importer(preferences); - parser.exportXML(importer); - } - else - { - // error - } +void LoadPrefs( PreferenceDictionary& preferences, const char* filename ){ + TextFileInputStream file( filename ); + if ( !file.failed() ) { + XMLStreamParser parser( file ); + XMLPreferenceDictionaryImporter importer( preferences ); + parser.exportXML( importer ); + } + else + { + // error + } } -void SavePrefs(PreferenceDictionary& preferences, const char* filename) -{ - TextFileOutputStream file(filename); - if(!file.failed()) - { - XMLStreamWriter writer(file); - XMLPreferenceDictionaryExporter exporter(preferences, "1"); - exporter.exportXML(writer); - } - else - { - // error - } +void SavePrefs( PreferenceDictionary& preferences, const char* filename ){ + TextFileOutputStream file( filename ); + if ( !file.failed() ) { + XMLStreamWriter writer( file ); + XMLPreferenceDictionaryExporter exporter( preferences, "1" ); + exporter.exportXML( writer ); + } + else + { + // error + } } class StringPreference { public: - class Observer - { - public: - virtual void onChanged() = 0; - }; +class Observer +{ +public: +virtual void onChanged() = 0; +}; private: - CopiedString m_string; - Observer& m_observer; +CopiedString m_string; +Observer& m_observer; public: - StringPreference(Observer& observer) - : m_observer(observer) - { - } - void importString(const char* value) - { - m_string = value; - m_observer.onChanged(); - } - typedef MemberCaller1 ImportStringCaller; - void exportString(StringImportCallback& importer) - { - importer(m_string.c_str()); - } - typedef MemberCaller1 ExportStringCaller; +StringPreference( Observer& observer ) + : m_observer( observer ){ +} +void importString( const char* value ){ + m_string = value; + m_observer.onChanged(); +} +typedef MemberCaller1 ImportStringCaller; +void exportString( StringImportCallback& importer ){ + importer( m_string.c_str() ); +} +typedef MemberCaller1 ExportStringCaller; }; -inline void int_export(int i, StringImportCallback& importer) -{ - char buffer[16]; - sprintf(buffer, "%d", i); - importer(buffer); +inline void int_export( int i, StringImportCallback& importer ){ + char buffer[16]; + sprintf( buffer, "%d", i ); + importer( buffer ); } -inline int int_import(const char* value) -{ - return atoi(value); +inline int int_import( const char* value ){ + return atoi( value ); } class IntPreference { public: - class Observer - { - public: - virtual void onChanged() = 0; - }; +class Observer +{ +public: +virtual void onChanged() = 0; +}; private: - int m_int; - Observer& m_observer; +int m_int; +Observer& m_observer; public: - IntPreference(Observer& observer) - : m_observer(observer) - { - } - void importString(const char* value) - { - m_int = int_import(value); - m_observer.onChanged(); - } - typedef MemberCaller1 ImportStringCaller; - void exportString(StringImportCallback& importer) - { - int_export(m_int, importer); - } - typedef MemberCaller1 ExportStringCaller; +IntPreference( Observer& observer ) + : m_observer( observer ){ +} +void importString( const char* value ){ + m_int = int_import( value ); + m_observer.onChanged(); +} +typedef MemberCaller1 ImportStringCaller; +void exportString( StringImportCallback& importer ){ + int_export( m_int, importer ); +} +typedef MemberCaller1 ExportStringCaller; }; class IntPreferenceImporter { - int& m_i; +int& m_i; public: - IntPreferenceImporter(int& i) - : m_i(i) - { - } - void importString(const char* value) - { - m_i = int_import(value); - } +IntPreferenceImporter( int& i ) + : m_i( i ){ +} +void importString( const char* value ){ + m_i = int_import( value ); +} }; class TestPrefs { public: - TestPrefs() - { - PreferenceDictionary preferences; - - class StringObserver : public StringPreference::Observer - { - public: - void onChanged() - { - int bleh = 0; - } - } string_observer; - StringPreference string1(string_observer); - string1.importString("twenty-three"); - - class IntObserver : public IntPreference::Observer - { - public: - void onChanged() - { - int bleh = 0; - } - - } int_observer; - IntPreference int1(int_observer); - int1.importString("23"); - - preferences.registerPreference("string1", StringPreference::ImportStringCaller(string1), StringPreference::ExportStringCaller(string1)); - preferences.registerPreference("int1", IntPreference::ImportStringCaller(int1), IntPreference::ExportStringCaller(int1)); - - LoadPrefs(preferences, "test.pref"); - SavePrefs(preferences, "test.pref"); - - } +TestPrefs(){ + PreferenceDictionary preferences; + + class StringObserver : public StringPreference::Observer + { +public: + void onChanged(){ + int bleh = 0; + } + } string_observer; + StringPreference string1( string_observer ); + string1.importString( "twenty-three" ); + + class IntObserver : public IntPreference::Observer + { +public: + void onChanged(){ + int bleh = 0; + } + + } int_observer; + IntPreference int1( int_observer ); + int1.importString( "23" ); + + preferences.registerPreference( "string1", StringPreference::ImportStringCaller( string1 ), StringPreference::ExportStringCaller( string1 ) ); + preferences.registerPreference( "int1", IntPreference::ImportStringCaller( int1 ), IntPreference::ExportStringCaller( int1 ) ); + + LoadPrefs( preferences, "test.pref" ); + SavePrefs( preferences, "test.pref" ); + +} }; #if 0 TestPrefs g_TestPrefs; #endif -void readpref(PreferenceDictionary& preferences, int& int_variable) -{ - PreferenceDictionary::iterator i = preferences.find("int_variable"); - IntPreferenceImporter importer(int_variable); - (*i).second.exporter().exportString(importer); +void readpref( PreferenceDictionary& preferences, int& int_variable ){ + PreferenceDictionary::iterator i = preferences.find( "int_variable" ); + IntPreferenceImporter importer( int_variable ); + ( *i ).second.exporter().exportString( importer ); } -void writepref(PreferenceDictionary& preferences, int& int_variable) -{ - PreferenceDictionary::iterator i = preferences.find("int_variable"); - int_export(int_variable, (*i).second.importer()); +void writepref( PreferenceDictionary& preferences, int& int_variable ){ + PreferenceDictionary::iterator i = preferences.find( "int_variable" ); + int_export( int_variable, ( *i ).second.importer() ); } #endif diff --git a/include/preferencesystem.h b/include/preferencesystem.h index f5ebae1d..45678024 100644 --- a/include/preferencesystem.h +++ b/include/preferencesystem.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_PREFERENCESYSTEM_H) +#if !defined( INCLUDED_PREFERENCESYSTEM_H ) #define INCLUDED_PREFERENCESYSTEM_H #include "generic/constant.h" @@ -31,10 +31,10 @@ typedef Callback1 StringExportCallback; class PreferenceSystem { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "preferences"); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "preferences" ); - virtual void registerPreference(const char* name, const StringImportCallback& importer, const StringExportCallback& exporter) = 0; +virtual void registerPreference( const char* name, const StringImportCallback& importer, const StringExportCallback& exporter ) = 0; }; #include "modulesystem.h" @@ -47,9 +47,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef GlobalPreferenceSystemModuleRef; -inline PreferenceSystem& GlobalPreferenceSystem() -{ - return GlobalPreferenceSystemModule::getTable(); +inline PreferenceSystem& GlobalPreferenceSystem(){ + return GlobalPreferenceSystemModule::getTable(); } diff --git a/include/qerplugin.cpp b/include/qerplugin.cpp index dd209319..54760013 100644 --- a/include/qerplugin.cpp +++ b/include/qerplugin.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "qerplugin.h" - diff --git a/include/qerplugin.h b/include/qerplugin.h index cac311ab..3c1db046 100644 --- a/include/qerplugin.h +++ b/include/qerplugin.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // QERadiant PlugIns // @@ -39,60 +39,60 @@ typedef struct _GtkWidget GtkWidget; enum EMessageBoxType { - eMB_OK, - eMB_OKCANCEL, - eMB_YESNO, - eMB_YESNOCANCEL, - eMB_NOYES, + eMB_OK, + eMB_OKCANCEL, + eMB_YESNO, + eMB_YESNOCANCEL, + eMB_NOYES, }; enum EMessageBoxIcon { - eMB_ICONDEFAULT, - eMB_ICONERROR, - eMB_ICONWARNING, - eMB_ICONQUESTION, - eMB_ICONASTERISK, + eMB_ICONDEFAULT, + eMB_ICONERROR, + eMB_ICONWARNING, + eMB_ICONQUESTION, + eMB_ICONASTERISK, }; enum EMessageBoxReturn { - eIDOK, - eIDCANCEL, - eIDYES, - eIDNO, + eIDOK, + eIDCANCEL, + eIDYES, + eIDNO, }; // simple Message Box, see above for the 'type' flags -typedef EMessageBoxReturn (* PFN_QERAPP_MESSAGEBOX) (GtkWidget *parent, const char* text, const char* caption/* = "NetRadiant"*/, EMessageBoxType type/* = eMB_OK*/, EMessageBoxIcon icon/* = eMB_ICONDEFAULT*/); +typedef EMessageBoxReturn ( *PFN_QERAPP_MESSAGEBOX )( GtkWidget *parent, const char* text, const char* caption /* = "NetRadiant"*/, EMessageBoxType type /* = eMB_OK*/, EMessageBoxIcon icon /* = eMB_ICONDEFAULT*/ ); // file and directory selection functions return null if the user hits cancel // - 'title' is the dialog title (can be null) // - 'path' is used to set the initial directory (can be null) // - 'pattern': the first pattern is for the win32 mode, then comes the Gtk pattern list, see Radiant source for samples -typedef const char* (* PFN_QERAPP_FILEDIALOG) (GtkWidget *parent, bool open, const char* title, const char* path/* = 0*/, const char* pattern/* = 0*/, bool want_load/* = false*/, bool want_import/* = false*/, bool want_save/* = false*/); +typedef const char* ( *PFN_QERAPP_FILEDIALOG )( GtkWidget *parent, bool open, const char* title, const char* path /* = 0*/, const char* pattern /* = 0*/, bool want_load /* = false*/, bool want_import /* = false*/, bool want_save /* = false*/ ); // returns a gchar* string that must be g_free'd by the user -typedef char* (* PFN_QERAPP_DIRDIALOG) (GtkWidget *parent, const char* title/* = "Choose Directory"*/, const char* path/* = 0*/); +typedef char* ( *PFN_QERAPP_DIRDIALOG )( GtkWidget *parent, const char* title /* = "Choose Directory"*/, const char* path /* = 0*/ ); // return true if the user closed the dialog with 'Ok' // 'color' is used to set the initial value and store the selected value template class BasicVector3; typedef BasicVector3 Vector3; -typedef bool (* PFN_QERAPP_COLORDIALOG) (GtkWidget *parent, Vector3& color, - const char* title/* = "Choose Color"*/); +typedef bool ( *PFN_QERAPP_COLORDIALOG )( GtkWidget *parent, Vector3& color, + const char* title /* = "Choose Color"*/ ); // load a .bmp file and create a GtkImage widget from it // NOTE: 'filename' is relative to /plugins/bitmaps/ typedef struct _GtkImage GtkImage; -typedef GtkImage* (* PFN_QERAPP_NEWIMAGE) (const char* filename); +typedef GtkImage* ( *PFN_QERAPP_NEWIMAGE )( const char* filename ); // ======================================== namespace scene { - class Node; +class Node; } class ModuleObserver; @@ -106,57 +106,57 @@ typedef SignalFwd::handler_id_type MouseEventHandlerId; enum VIEWTYPE { - YZ = 0, - XZ = 1, - XY = 2 + YZ = 0, + XZ = 1, + XY = 2 }; // the radiant core API struct _QERFuncTable_1 { - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "radiant"); - - const char* (*getEnginePath)(); - const char* (*getLocalRcPath)(); - const char* (*getGameToolsPath)(); - const char* (*getAppPath)(); - const char* (*getSettingsPath)(); - const char* (*getMapsPath)(); - - const char* (*getGameName)(); - const char* (*getGameMode)(); - - const char* (*getMapName)(); - scene::Node& (*getMapWorldEntity)(); - float (*getGridSize)(); - - const char* (*getGameDescriptionKeyValue)(const char* key); - const char* (*getRequiredGameDescriptionKeyValue)(const char* key); - - void (*attachGameToolsPathObserver)(ModuleObserver& observer); - void (*detachGameToolsPathObserver)(ModuleObserver& observer); - void (*attachEnginePathObserver)(ModuleObserver& observer); - void (*detachEnginePathObserver)(ModuleObserver& observer); - void (*attachGameNameObserver)(ModuleObserver& observer); - void (*detachGameNameObserver)(ModuleObserver& observer); - void (*attachGameModeObserver)(ModuleObserver& observer); - void (*detachGameModeObserver)(ModuleObserver& observer); - - SignalHandlerId (*XYWindowDestroyed_connect)(const SignalHandler& handler); - void (*XYWindowDestroyed_disconnect)(SignalHandlerId id); - MouseEventHandlerId (*XYWindowMouseDown_connect)(const MouseEventHandler& handler); - void (*XYWindowMouseDown_disconnect)(MouseEventHandlerId id); - VIEWTYPE (*XYWindow_getViewType)(); - Vector3 (*XYWindow_windowToWorld)(const WindowVector& position); - const char* (*TextureBrowser_getSelectedShader)(); - - // GTK+ functions - PFN_QERAPP_MESSAGEBOX m_pfnMessageBox; - PFN_QERAPP_FILEDIALOG m_pfnFileDialog; - PFN_QERAPP_DIRDIALOG m_pfnDirDialog; - PFN_QERAPP_COLORDIALOG m_pfnColorDialog; - PFN_QERAPP_NEWIMAGE m_pfnNewImage; + INTEGER_CONSTANT( Version, 1 ); + STRING_CONSTANT( Name, "radiant" ); + + const char* ( *getEnginePath )( ); + const char* ( *getLocalRcPath )( ); + const char* ( *getGameToolsPath )( ); + const char* ( *getAppPath )( ); + const char* ( *getSettingsPath )( ); + const char* ( *getMapsPath )( ); + + const char* ( *getGameName )( ); + const char* ( *getGameMode )( ); + + const char* ( *getMapName )( ); + scene::Node& ( *getMapWorldEntity )( ); + float ( *getGridSize )(); + + const char* ( *getGameDescriptionKeyValue )(const char* key); + const char* ( *getRequiredGameDescriptionKeyValue )(const char* key); + + void ( *attachGameToolsPathObserver )( ModuleObserver& observer ); + void ( *detachGameToolsPathObserver )( ModuleObserver& observer ); + void ( *attachEnginePathObserver )( ModuleObserver& observer ); + void ( *detachEnginePathObserver )( ModuleObserver& observer ); + void ( *attachGameNameObserver )( ModuleObserver& observer ); + void ( *detachGameNameObserver )( ModuleObserver& observer ); + void ( *attachGameModeObserver )( ModuleObserver& observer ); + void ( *detachGameModeObserver )( ModuleObserver& observer ); + + SignalHandlerId ( *XYWindowDestroyed_connect )( const SignalHandler& handler ); + void ( *XYWindowDestroyed_disconnect )( SignalHandlerId id ); + MouseEventHandlerId ( *XYWindowMouseDown_connect )( const MouseEventHandler& handler ); + void ( *XYWindowMouseDown_disconnect )( MouseEventHandlerId id ); + VIEWTYPE ( *XYWindow_getViewType )(); + Vector3 ( *XYWindow_windowToWorld )( const WindowVector& position ); + const char* ( *TextureBrowser_getSelectedShader )( ); + + // GTK+ functions + PFN_QERAPP_MESSAGEBOX m_pfnMessageBox; + PFN_QERAPP_FILEDIALOG m_pfnFileDialog; + PFN_QERAPP_DIRDIALOG m_pfnDirDialog; + PFN_QERAPP_COLORDIALOG m_pfnColorDialog; + PFN_QERAPP_NEWIMAGE m_pfnNewImage; }; @@ -170,9 +170,8 @@ template class GlobalModuleRef; typedef GlobalModuleRef<_QERFuncTable_1> GlobalRadiantModuleRef; -inline _QERFuncTable_1& GlobalRadiant() -{ - return GlobalRadiantModule::getTable(); +inline _QERFuncTable_1& GlobalRadiant(){ + return GlobalRadiantModule::getTable(); } #endif diff --git a/include/renderable.cpp b/include/renderable.cpp index 9ca3673f..dfc186fd 100644 --- a/include/renderable.cpp +++ b/include/renderable.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "renderable.h" - diff --git a/include/renderable.h b/include/renderable.h index de573910..8b972170 100644 --- a/include/renderable.h +++ b/include/renderable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_RENDERABLE_H) +#if !defined( INCLUDED_RENDERABLE_H ) #define INCLUDED_RENDERABLE_H #include "generic/constant.h" @@ -32,28 +32,27 @@ class Matrix4; class Renderer { public: - enum EHighlightMode - { - eFace = 1 << 0, - /*! Full highlighting. */ - ePrimitive = 1 << 1, - }; +enum EHighlightMode +{ + eFace = 1 << 0, + /*! Full highlighting. */ + ePrimitive = 1 << 1, +}; - enum EStyle - { - eWireframeOnly, - eFullMaterials, - }; +enum EStyle +{ + eWireframeOnly, + eFullMaterials, +}; - virtual void PushState() = 0; - virtual void PopState() = 0; - virtual void SetState(Shader* state, EStyle mode) = 0; - virtual const EStyle getStyle() const = 0; - virtual void Highlight(EHighlightMode mode, bool bEnable = true) = 0; - virtual void setLights(const LightList& lights) - { - } - virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& world) = 0; +virtual void PushState() = 0; +virtual void PopState() = 0; +virtual void SetState( Shader* state, EStyle mode ) = 0; +virtual const EStyle getStyle() const = 0; +virtual void Highlight( EHighlightMode mode, bool bEnable = true ) = 0; +virtual void setLights( const LightList& lights ){ +} +virtual void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ) = 0; }; class VolumeTest; @@ -61,16 +60,14 @@ class VolumeTest; class Renderable { public: - STRING_CONSTANT(Name, "Renderable"); +STRING_CONSTANT( Name, "Renderable" ); - virtual void renderSolid(Renderer& renderer, const VolumeTest& volume) const = 0; - virtual void renderWireframe(Renderer& renderer, const VolumeTest& volume) const = 0; - virtual void renderComponents(Renderer&, const VolumeTest&) const - { - } - virtual void viewChanged() const - { - } +virtual void renderSolid( Renderer& renderer, const VolumeTest& volume ) const = 0; +virtual void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const = 0; +virtual void renderComponents( Renderer&, const VolumeTest& ) const { +} +virtual void viewChanged() const { +} }; #endif diff --git a/include/selectable.cpp b/include/selectable.cpp index 206bebe4..38a2d1ab 100644 --- a/include/selectable.cpp +++ b/include/selectable.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "selectable.h" - diff --git a/include/selectable.h b/include/selectable.h index fffcfe29..2b8eab07 100644 --- a/include/selectable.h +++ b/include/selectable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_SELECTABLE_H) +#if !defined( INCLUDED_SELECTABLE_H ) #define INCLUDED_SELECTABLE_H #include @@ -30,55 +30,44 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class SelectionIntersection { - float m_depth; - float m_distance; +float m_depth; +float m_distance; public: - SelectionIntersection() : m_depth(1), m_distance(2) - { - } - SelectionIntersection(float depth, float distance) : m_depth(depth), m_distance(distance) - { - } - bool operator<(const SelectionIntersection& other) const - { - if(m_distance != other.m_distance) - { - return m_distance < other.m_distance; - } - if(m_depth != other.m_depth) - { - return m_depth < other.m_depth; - } - return false; - } - bool equalEpsilon(const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon) const - { - return float_equal_epsilon(m_distance, other.m_distance, distanceEpsilon) - && float_equal_epsilon(m_depth, other.m_depth, depthEpsilon); - } - float depth() const - { - return m_depth; - } - bool valid() const - { - return depth() < 1; - } +SelectionIntersection() : m_depth( 1 ), m_distance( 2 ){ +} +SelectionIntersection( float depth, float distance ) : m_depth( depth ), m_distance( distance ){ +} +bool operator<( const SelectionIntersection& other ) const { + if ( m_distance != other.m_distance ) { + return m_distance < other.m_distance; + } + if ( m_depth != other.m_depth ) { + return m_depth < other.m_depth; + } + return false; +} +bool equalEpsilon( const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon ) const { + return float_equal_epsilon( m_distance, other.m_distance, distanceEpsilon ) + && float_equal_epsilon( m_depth, other.m_depth, depthEpsilon ); +} +float depth() const { + return m_depth; +} +bool valid() const { + return depth() < 1; +} }; // returns true if self is closer than other -inline bool SelectionIntersection_closer(const SelectionIntersection& self, const SelectionIntersection& other) -{ - return self < other; +inline bool SelectionIntersection_closer( const SelectionIntersection& self, const SelectionIntersection& other ){ + return self < other; } // assigns other to best if other is closer than best -inline void assign_if_closer(SelectionIntersection& best, const SelectionIntersection& other) -{ - if(SelectionIntersection_closer(other, best)) - { - best = other; - } +inline void assign_if_closer( SelectionIntersection& best, const SelectionIntersection& other ){ + if ( SelectionIntersection_closer( other, best ) ) { + best = other; + } } @@ -86,138 +75,119 @@ inline void assign_if_closer(SelectionIntersection& best, const SelectionInterse class VertexPointer { - typedef const unsigned char* byte_pointer; +typedef const unsigned char* byte_pointer; +public: +typedef float elem_type; +typedef const elem_type* pointer; +typedef const elem_type& reference; + +class iterator +{ public: - typedef float elem_type; - typedef const elem_type* pointer; - typedef const elem_type& reference; - - class iterator - { - public: - iterator() {} - iterator(byte_pointer vertices, std::size_t stride) - : m_iter(vertices), m_stride(stride) {} - - bool operator==(const iterator& other) const - { - return m_iter == other.m_iter; - } - bool operator!=(const iterator& other) const - { - return !operator==(other); - } - - iterator operator+(std::size_t i) - { - return iterator(m_iter + i * m_stride, m_stride); - } - iterator operator+=(std::size_t i) - { - m_iter += i * m_stride; - return *this; - } - iterator& operator++() - { - m_iter += m_stride; - return *this; - } - iterator operator++(int) - { - iterator tmp = *this; - m_iter += m_stride; - return tmp; - } - reference operator*() const - { - return *reinterpret_cast(m_iter); - } - private: - byte_pointer m_iter; - std::size_t m_stride; - }; - - VertexPointer(pointer vertices, std::size_t stride) - : m_vertices(reinterpret_cast(vertices)), m_stride(stride) {} - - iterator begin() const - { - return iterator(m_vertices, m_stride); - } - - reference operator[](std::size_t i) const - { - return *reinterpret_cast(m_vertices + m_stride*i); - } +iterator() {} +iterator( byte_pointer vertices, std::size_t stride ) + : m_iter( vertices ), m_stride( stride ) {} +bool operator==( const iterator& other ) const { + return m_iter == other.m_iter; +} +bool operator!=( const iterator& other ) const { + return !operator==( other ); +} + +iterator operator+( std::size_t i ){ + return iterator( m_iter + i * m_stride, m_stride ); +} +iterator operator+=( std::size_t i ){ + m_iter += i * m_stride; + return *this; +} +iterator& operator++(){ + m_iter += m_stride; + return *this; +} +iterator operator++( int ){ + iterator tmp = *this; + m_iter += m_stride; + return tmp; +} +reference operator*() const { + return *reinterpret_cast( m_iter ); +} private: - byte_pointer m_vertices; - std::size_t m_stride; +byte_pointer m_iter; +std::size_t m_stride; +}; + +VertexPointer( pointer vertices, std::size_t stride ) + : m_vertices( reinterpret_cast( vertices ) ), m_stride( stride ) {} + +iterator begin() const { + return iterator( m_vertices, m_stride ); +} + +reference operator[]( std::size_t i ) const { + return *reinterpret_cast( m_vertices + m_stride * i ); +} + +private: +byte_pointer m_vertices; +std::size_t m_stride; }; class IndexPointer { public: - typedef unsigned int index_type; - typedef const index_type* pointer; - - class iterator - { - public: - iterator(pointer iter) : m_iter(iter) {} - - bool operator==(const iterator& other) const - { - return m_iter == other.m_iter; - } - bool operator!=(const iterator& other) const - { - return !operator==(other); - } - - iterator operator+(std::size_t i) - { - return m_iter + i; - } - iterator operator+=(std::size_t i) - { - return m_iter += i; - } - iterator operator++() - { - return ++m_iter; - } - iterator operator++(int) - { - return m_iter++; - } - const index_type& operator*() const - { - return *m_iter; - } - private: - void increment() - { - ++m_iter; - } - pointer m_iter; - }; - - IndexPointer(pointer indices, std::size_t count) - : m_indices(indices), m_finish(indices + count) {} - - iterator begin() const - { - return m_indices; - } - iterator end() const - { - return m_finish; - } +typedef unsigned int index_type; +typedef const index_type* pointer; + +class iterator +{ +public: +iterator( pointer iter ) : m_iter( iter ) {} + +bool operator==( const iterator& other ) const { + return m_iter == other.m_iter; +} +bool operator!=( const iterator& other ) const { + return !operator==( other ); +} + +iterator operator+( std::size_t i ){ + return m_iter + i; +} +iterator operator+=( std::size_t i ){ + return m_iter += i; +} +iterator operator++(){ + return ++m_iter; +} +iterator operator++( int ){ + return m_iter++; +} +const index_type& operator*() const { + return *m_iter; +} +private: +void increment(){ + ++m_iter; +} +pointer m_iter; +}; + +IndexPointer( pointer indices, std::size_t count ) + : m_indices( indices ), m_finish( indices + count ) {} + +iterator begin() const { + return m_indices; +} +iterator end() const { + return m_finish; +} private: - pointer m_indices; - pointer m_finish; +pointer m_indices; +pointer m_finish; }; template class BasicVector3; @@ -228,18 +198,18 @@ class VolumeTest; class SelectionTest { public: - virtual void BeginMesh(const Matrix4& localToWorld, bool twoSided = false) = 0; - virtual const VolumeTest& getVolume() const = 0; - virtual const Vector3& getNear() const = 0; - virtual const Vector3& getFar() const = 0; - virtual void TestPoint(const Vector3& point, SelectionIntersection& best) = 0; - virtual void TestPolygon(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLineLoop(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLineStrip(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLines(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestTriangles(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; - virtual void TestQuads(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; - virtual void TestQuadStrip(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; +virtual void BeginMesh( const Matrix4& localToWorld, bool twoSided = false ) = 0; +virtual const VolumeTest& getVolume() const = 0; +virtual const Vector3& getNear() const = 0; +virtual const Vector3& getFar() const = 0; +virtual void TestPoint( const Vector3& point, SelectionIntersection& best ) = 0; +virtual void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; +virtual void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; +virtual void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; +virtual void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ) = 0; +virtual void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; +virtual void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; +virtual void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ) = 0; }; class Selectable; @@ -247,23 +217,21 @@ class Selectable; class Selector { public: - virtual void pushSelectable(Selectable& selectable) = 0; - virtual void popSelectable() = 0; - virtual void addIntersection(const SelectionIntersection& intersection) = 0; +virtual void pushSelectable( Selectable& selectable ) = 0; +virtual void popSelectable() = 0; +virtual void addIntersection( const SelectionIntersection& intersection ) = 0; }; -inline void Selector_add(Selector& selector, Selectable& selectable) -{ - selector.pushSelectable(selectable); - selector.addIntersection(SelectionIntersection(0, 0)); - selector.popSelectable(); +inline void Selector_add( Selector& selector, Selectable& selectable ){ + selector.pushSelectable( selectable ); + selector.addIntersection( SelectionIntersection( 0, 0 ) ); + selector.popSelectable(); } -inline void Selector_add(Selector& selector, Selectable& selectable, const SelectionIntersection& intersection) -{ - selector.pushSelectable(selectable); - selector.addIntersection(intersection); - selector.popSelectable(); +inline void Selector_add( Selector& selector, Selectable& selectable, const SelectionIntersection& intersection ){ + selector.pushSelectable( selectable ); + selector.addIntersection( intersection ); + selector.popSelectable(); } @@ -271,14 +239,13 @@ class VolumeTest; class SelectionTestable { public: - STRING_CONSTANT(Name, "SelectionTestable"); +STRING_CONSTANT( Name, "SelectionTestable" ); - virtual void testSelect(Selector& selector, SelectionTest& test) = 0; +virtual void testSelect( Selector& selector, SelectionTest& test ) = 0; }; -inline SelectionTestable* Instance_getSelectionTestable(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); +inline SelectionTestable* Instance_getSelectionTestable( scene::Instance& instance ){ + return InstanceTypeCast::cast( instance ); } @@ -288,16 +255,16 @@ typedef Callback1 PlaneCallback; class SelectedPlanes { public: - virtual bool contains(const Plane3& plane) const = 0; +virtual bool contains( const Plane3& plane ) const = 0; }; class PlaneSelectable { public: - STRING_CONSTANT(Name, "PlaneSelectable"); +STRING_CONSTANT( Name, "PlaneSelectable" ); - virtual void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) = 0; - virtual void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) = 0; +virtual void selectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ) = 0; +virtual void selectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes ) = 0; }; diff --git a/include/stream_version.h b/include/stream_version.h index 17ce6339..21a26fff 100644 --- a/include/stream_version.h +++ b/include/stream_version.h @@ -1,3 +1,2 @@ // version defines for q3map stream #define Q3MAP_STREAM_VERSION "1" - diff --git a/include/warnings.h b/include/warnings.h index 66415614..e067fd11 100644 --- a/include/warnings.h +++ b/include/warnings.h @@ -1,31 +1,30 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_WARNINGS_H) +#if !defined ( INCLUDED_WARNINGS_H ) #define INCLUDED_WARNINGS_H -#if _MSC_VER > 1000 && defined(WIN32) +#if _MSC_VER > 1000 && defined( WIN32 ) #pragma warning(disable:4355) // 'this' : used in base member initializer list #pragma warning(disable:4503) // '[symbol]' : decorated name length exceeded, name was truncated #endif #endif - diff --git a/include/windowobserver.cpp b/include/windowobserver.cpp index 2e59b8c0..16b4a006 100644 --- a/include/windowobserver.cpp +++ b/include/windowobserver.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "windowobserver.h" - diff --git a/include/windowobserver.h b/include/windowobserver.h index 99fc03da..b72d0820 100644 --- a/include/windowobserver.h +++ b/include/windowobserver.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_WINDOWOBSERVER_H) +#if !defined( INCLUDED_WINDOWOBSERVER_H ) #define INCLUDED_WINDOWOBSERVER_H template class BitFieldValue; @@ -35,40 +35,40 @@ typedef EnumeratedValue ButtonIdentifier; struct ModifierEnumeration { - enum Value - { - SHIFT = 0, - CONTROL = 1, - ALT = 2 - }; + enum Value + { + SHIFT = 0, + CONTROL = 1, + ALT = 2 + }; }; typedef BitFieldValue ModifierFlags; const ModifierFlags c_modifierNone; -const ModifierFlags c_modifierShift(ModifierEnumeration::SHIFT); -const ModifierFlags c_modifierControl(ModifierEnumeration::CONTROL); -const ModifierFlags c_modifierAlt(ModifierEnumeration::ALT); +const ModifierFlags c_modifierShift( ModifierEnumeration::SHIFT ); +const ModifierFlags c_modifierControl( ModifierEnumeration::CONTROL ); +const ModifierFlags c_modifierAlt( ModifierEnumeration::ALT ); #include "generic/enumeration.h" struct ButtonEnumeration { - enum Value - { - INVALID = 0, - LEFT = 1, - MIDDLE = 3, - RIGHT = 2 - }; + enum Value + { + INVALID = 0, + LEFT = 1, + MIDDLE = 3, + RIGHT = 2 + }; }; typedef EnumeratedValue ButtonIdentifier; -const ButtonIdentifier c_buttonInvalid(ButtonEnumeration::INVALID); -const ButtonIdentifier c_buttonLeft(ButtonEnumeration::LEFT); -const ButtonIdentifier c_buttonMiddle(ButtonEnumeration::MIDDLE); -const ButtonIdentifier c_buttonRight(ButtonEnumeration::RIGHT); +const ButtonIdentifier c_buttonInvalid( ButtonEnumeration::INVALID ); +const ButtonIdentifier c_buttonLeft( ButtonEnumeration::LEFT ); +const ButtonIdentifier c_buttonMiddle( ButtonEnumeration::MIDDLE ); +const ButtonIdentifier c_buttonRight( ButtonEnumeration::RIGHT ); template @@ -79,13 +79,13 @@ typedef Vector2 WindowVector; class WindowObserver { public: - virtual void release() = 0; - virtual void onSizeChanged(int width, int height) = 0; - virtual void onMouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; - virtual void onMouseUp(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; - virtual void onMouseMotion(const WindowVector& position, ModifierFlags modifiers) = 0; - virtual void onModifierDown(ModifierFlags modifier) = 0; - virtual void onModifierUp(ModifierFlags modifier) = 0; +virtual void release() = 0; +virtual void onSizeChanged( int width, int height ) = 0; +virtual void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; +virtual void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ) = 0; +virtual void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ) = 0; +virtual void onModifierDown( ModifierFlags modifier ) = 0; +virtual void onModifierUp( ModifierFlags modifier ) = 0; }; #endif diff --git a/libs/archivelib.cpp b/libs/archivelib.cpp index 795f7c88..a66f1309 100644 --- a/libs/archivelib.cpp +++ b/libs/archivelib.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "archivelib.h" diff --git a/libs/archivelib.h b/libs/archivelib.h index 710d2e8a..78fc7eb5 100644 --- a/libs/archivelib.h +++ b/libs/archivelib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_ARCHIVELIB_H) +#if !defined ( INCLUDED_ARCHIVELIB_H ) #define INCLUDED_ARCHIVELIB_H #include "debugging/debugging.h" @@ -35,40 +35,35 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class SingleByteInputStream { - typedef typename InputStreamType::byte_type byte_type; +typedef typename InputStreamType::byte_type byte_type; - InputStreamType& m_inputStream; - byte_type m_buffer[SIZE]; - byte_type* m_cur; - byte_type* m_end; +InputStreamType& m_inputStream; +byte_type m_buffer[SIZE]; +byte_type* m_cur; +byte_type* m_end; public: - SingleByteInputStream(InputStreamType& inputStream) : m_inputStream(inputStream), m_cur(m_buffer + SIZE), m_end(m_cur) - { - } - bool readByte(byte_type& b) - { - if(m_cur == m_end) - { - if(m_end != m_buffer + SIZE) - { - return false; - } +SingleByteInputStream( InputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer + SIZE ), m_end( m_cur ){ +} +bool readByte( byte_type& b ){ + if ( m_cur == m_end ) { + if ( m_end != m_buffer + SIZE ) { + return false; + } - m_end = m_buffer + m_inputStream.read(m_buffer, SIZE); - m_cur = m_buffer; + m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); + m_cur = m_buffer; - if(m_end == m_buffer) - { - return false; - } - } + if ( m_end == m_buffer ) { + return false; + } + } - b = *m_cur++; + b = *m_cur++; - return true; - } + return true; +} }; /// \brief A binary-to-text wrapper around an InputStream. @@ -76,180 +71,153 @@ public: template class BinaryToTextInputStream : public TextInputStream { - SingleByteInputStream m_inputStream; +SingleByteInputStream m_inputStream; public: - BinaryToTextInputStream(BinaryInputStreamType& inputStream) : m_inputStream(inputStream) - { - } - std::size_t read(char* buffer, std::size_t length) - { - char* p = buffer; - for(;;) - { - if(length != 0 && m_inputStream.readByte(*reinterpret_cast(p))) - { - if(*p != '\r') - { - ++p; - --length; - } - } - else - { - return p - buffer; - } - } - } +BinaryToTextInputStream( BinaryInputStreamType& inputStream ) : m_inputStream( inputStream ){ +} +std::size_t read( char* buffer, std::size_t length ){ + char* p = buffer; + for (;; ) + { + if ( length != 0 && m_inputStream.readByte( *reinterpret_cast( p ) ) ) { + if ( *p != '\r' ) { + ++p; + --length; + } + } + else + { + return p - buffer; + } + } +} }; /// \brief An ArchiveFile which is stored uncompressed as part of a larger archive file. class StoredArchiveFile : public ArchiveFile { - CopiedString m_name; - FileInputStream m_filestream; - SubFileInputStream m_substream; - FileInputStream::size_type m_size; +CopiedString m_name; +FileInputStream m_filestream; +SubFileInputStream m_substream; +FileInputStream::size_type m_size; public: - typedef FileInputStream::size_type size_type; - typedef FileInputStream::position_type position_type; - - StoredArchiveFile(const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size) - : m_name(name), m_filestream(archiveName), m_substream(m_filestream, position, stream_size), m_size(file_size) - { - } - - static StoredArchiveFile* create(const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size) - { - return New().scalar(name, archiveName, position, stream_size, file_size); - } - - void release() - { - Delete().scalar(this); - } - size_type size() const - { - return m_size; - } - const char* getName() const - { - return m_name.c_str(); - } - InputStream& getInputStream() - { - return m_substream; - } +typedef FileInputStream::size_type size_type; +typedef FileInputStream::position_type position_type; + +StoredArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) + : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_size( file_size ){ +} + +static StoredArchiveFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ){ + return New().scalar( name, archiveName, position, stream_size, file_size ); +} + +void release(){ + Delete().scalar( this ); +} +size_type size() const { + return m_size; +} +const char* getName() const { + return m_name.c_str(); +} +InputStream& getInputStream(){ + return m_substream; +} }; /// \brief An ArchiveTextFile which is stored uncompressed as part of a larger archive file. class StoredArchiveTextFile : public ArchiveTextFile { - CopiedString m_name; - FileInputStream m_filestream; - SubFileInputStream m_substream; - BinaryToTextInputStream m_textStream; +CopiedString m_name; +FileInputStream m_filestream; +SubFileInputStream m_substream; +BinaryToTextInputStream m_textStream; public: - typedef FileInputStream::size_type size_type; - typedef FileInputStream::position_type position_type; - - StoredArchiveTextFile(const char* name, const char* archiveName, position_type position, size_type stream_size) - : m_name(name), m_filestream(archiveName), m_substream(m_filestream, position, stream_size), m_textStream(m_substream) - { - } - - static StoredArchiveTextFile* create(const char* name, const char* archiveName, position_type position, size_type stream_size) - { - return New().scalar(name, archiveName, position, stream_size); - } - - void release() - { - Delete().scalar(this); - } - const char* getName() const - { - return m_name.c_str(); - } - TextInputStream& getInputStream() - { - return m_textStream; - } +typedef FileInputStream::size_type size_type; +typedef FileInputStream::position_type position_type; + +StoredArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) + : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_textStream( m_substream ){ +} + +static StoredArchiveTextFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size ){ + return New().scalar( name, archiveName, position, stream_size ); +} + +void release(){ + Delete().scalar( this ); +} +const char* getName() const { + return m_name.c_str(); +} +TextInputStream& getInputStream(){ + return m_textStream; +} }; /// \brief An ArchiveFile which is stored as a single file on disk. class DirectoryArchiveFile : public ArchiveFile { - CopiedString m_name; - FileInputStream m_istream; - FileInputStream::size_type m_size; +CopiedString m_name; +FileInputStream m_istream; +FileInputStream::size_type m_size; public: - typedef FileInputStream::size_type size_type; - - DirectoryArchiveFile(const char* name, const char* filename) - : m_name(name), m_istream(filename) - { - if(!failed()) - { - m_istream.seek(0, FileInputStream::end); - m_size = m_istream.tell(); - m_istream.seek(0); - } - else - { - m_size = 0; - } - } - bool failed() const - { - return m_istream.failed(); - } - - void release() - { - delete this; - } - size_type size() const - { - return m_size; - } - const char* getName() const - { - return m_name.c_str(); - } - InputStream& getInputStream() - { - return m_istream; - } +typedef FileInputStream::size_type size_type; + +DirectoryArchiveFile( const char* name, const char* filename ) + : m_name( name ), m_istream( filename ){ + if ( !failed() ) { + m_istream.seek( 0, FileInputStream::end ); + m_size = m_istream.tell(); + m_istream.seek( 0 ); + } + else + { + m_size = 0; + } +} +bool failed() const { + return m_istream.failed(); +} + +void release(){ + delete this; +} +size_type size() const { + return m_size; +} +const char* getName() const { + return m_name.c_str(); +} +InputStream& getInputStream(){ + return m_istream; +} }; /// \brief An ArchiveTextFile which is stored as a single file on disk. class DirectoryArchiveTextFile : public ArchiveTextFile { - CopiedString m_name; - TextFileInputStream m_inputStream; +CopiedString m_name; +TextFileInputStream m_inputStream; public: - DirectoryArchiveTextFile(const char* name, const char* filename) - : m_name(name), m_inputStream(filename) - { - } - bool failed() const - { - return m_inputStream.failed(); - } - - void release() - { - delete this; - } - const char* getName() const - { - return m_name.c_str(); - } - TextInputStream& getInputStream() - { - return m_inputStream; - } +DirectoryArchiveTextFile( const char* name, const char* filename ) + : m_name( name ), m_inputStream( filename ){ +} +bool failed() const { + return m_inputStream.failed(); +} + +void release(){ + delete this; +} +const char* getName() const { + return m_name.c_str(); +} +TextInputStream& getInputStream(){ + return m_inputStream; +} }; diff --git a/libs/bytebool.cpp b/libs/bytebool.cpp index 036061fe..d636f556 100644 --- a/libs/bytebool.cpp +++ b/libs/bytebool.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "bytebool.h" diff --git a/libs/bytebool.h b/libs/bytebool.h index 4009c2dd..7e3d3306 100644 --- a/libs/bytebool.h +++ b/libs/bytebool.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #ifndef __BYTEBOOL__ #define __BYTEBOOL__ diff --git a/libs/bytestreamutils.cpp b/libs/bytestreamutils.cpp index f9b8ddca..87917d2c 100644 --- a/libs/bytestreamutils.cpp +++ b/libs/bytestreamutils.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "bytestreamutils.h" diff --git a/libs/bytestreamutils.h b/libs/bytestreamutils.h index aad7d7e4..156333a1 100644 --- a/libs/bytestreamutils.h +++ b/libs/bytestreamutils.h @@ -1,34 +1,34 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_BYTESTREAMUTILS_H) +#if !defined( INCLUDED_BYTESTREAMUTILS_H ) #define INCLUDED_BYTESTREAMUTILS_H -#if defined(__GNUC__) +#if defined( __GNUC__ ) -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 +#define _ISOC9X_SOURCE 1 +#define _ISOC99_SOURCE 1 -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 +#define __USE_ISOC9X 1 +#define __USE_ISOC99 1 #include @@ -37,16 +37,16 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include // if C99 is unavailable, fall back to the types most likely to be the right sizes -#if !defined(int16_t) +#if !defined( int16_t ) typedef signed short int16_t; #endif -#if !defined(uint16_t) +#if !defined( uint16_t ) typedef unsigned short uint16_t; #endif -#if !defined(int32_t) +#if !defined( int32_t ) typedef signed int int32_t; #endif -#if !defined(uint32_t) +#if !defined( uint32_t ) typedef unsigned int uint32_t; #endif @@ -54,76 +54,67 @@ typedef unsigned int uint32_t; template -inline void istream_read_little_endian(InputStreamType& istream, Type& value) -{ - istream.read(reinterpret_cast(&value), sizeof(Type)); -#if defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&value), reinterpret_cast(&value) + sizeof(Type)); +inline void istream_read_little_endian( InputStreamType& istream, Type& value ){ + istream.read( reinterpret_cast( &value ), sizeof( Type ) ); +#if defined( __BIG_ENDIAN__ ) + std::reverse( reinterpret_cast( &value ), reinterpret_cast( &value ) + sizeof( Type ) ); #endif } template -inline void istream_read_big_endian(InputStreamType& istream, Type& value) -{ - istream.read(reinterpret_cast(&value), sizeof(Type)); -#if !defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&value), reinterpret_cast(&value) + sizeof(Type)); +inline void istream_read_big_endian( InputStreamType& istream, Type& value ){ + istream.read( reinterpret_cast( &value ), sizeof( Type ) ); +#if !defined( __BIG_ENDIAN__ ) + std::reverse( reinterpret_cast( &value ), reinterpret_cast( &value ) + sizeof( Type ) ); #endif } template -inline void istream_read_byte(InputStreamType& istream, typename InputStreamType::byte_type& b) -{ - istream.read(&b, 1); +inline void istream_read_byte( InputStreamType& istream, typename InputStreamType::byte_type& b ){ + istream.read( &b, 1 ); } template -inline int16_t istream_read_int16_le(InputStreamType& istream) -{ - int16_t value; - istream_read_little_endian(istream, value); - return value; +inline int16_t istream_read_int16_le( InputStreamType& istream ){ + int16_t value; + istream_read_little_endian( istream, value ); + return value; } template -inline uint16_t istream_read_uint16_le(InputStreamType& istream) -{ - uint16_t value; - istream_read_little_endian(istream, value); - return value; +inline uint16_t istream_read_uint16_le( InputStreamType& istream ){ + uint16_t value; + istream_read_little_endian( istream, value ); + return value; } template -inline int32_t istream_read_int32_le(InputStreamType& istream) -{ - int32_t value; - istream_read_little_endian(istream, value); - return value; +inline int32_t istream_read_int32_le( InputStreamType& istream ){ + int32_t value; + istream_read_little_endian( istream, value ); + return value; } template -inline uint32_t istream_read_uint32_le(InputStreamType& istream) -{ - uint32_t value; - istream_read_little_endian(istream, value); - return value; +inline uint32_t istream_read_uint32_le( InputStreamType& istream ){ + uint32_t value; + istream_read_little_endian( istream, value ); + return value; } template -inline float istream_read_float32_le(InputStreamType& istream) -{ - float value; - istream_read_little_endian(istream, value); - return value; +inline float istream_read_float32_le( InputStreamType& istream ){ + float value; + istream_read_little_endian( istream, value ); + return value; } template -inline typename InputStreamType::byte_type istream_read_byte(InputStreamType& istream) -{ - typename InputStreamType::byte_type b; - istream.read(&b, sizeof(typename InputStreamType::byte_type)); - return b; +inline typename InputStreamType::byte_type istream_read_byte( InputStreamType& istream ){ + typename InputStreamType::byte_type b; + istream.read( &b, sizeof( typename InputStreamType::byte_type ) ); + return b; } #endif diff --git a/libs/character.cpp b/libs/character.cpp index ab8969b6..cd36bc7b 100644 --- a/libs/character.cpp +++ b/libs/character.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "character.h" - diff --git a/libs/character.h b/libs/character.h index 1e6d3b16..bc35d3ff 100644 --- a/libs/character.h +++ b/libs/character.h @@ -1,47 +1,44 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CHARACTER_H) +#if !defined( INCLUDED_CHARACTER_H ) #define INCLUDED_CHARACTER_H /// \file /// \brief Character encoding. /// \brief Returns true if \p c is an ASCII character that can be represented with 7 bits. -inline bool char_is_ascii(char c) -{ - return (c & 0x80) == 0; +inline bool char_is_ascii( char c ){ + return ( c & 0x80 ) == 0; } /// \brief Returns true if \p string consists entirely of ASCII characters. -inline bool string_is_ascii(const char* string) -{ - while(*string != '\0') - { - if(!char_is_ascii(*string++)) - { - return false; - } - } - return true; +inline bool string_is_ascii( const char* string ){ + while ( *string != '\0' ) + { + if ( !char_is_ascii( *string++ ) ) { + return false; + } + } + return true; } #endif diff --git a/libs/cmdlib.h b/libs/cmdlib.h index 8961bd2a..843dee76 100644 --- a/libs/cmdlib.h +++ b/libs/cmdlib.h @@ -1,27 +1,27 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // start of shared cmdlib stuff -// +// #ifndef __CMDLIB__ #define __CMDLIB__ @@ -43,7 +43,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // if the spawn was fine // TODO TTimo add functionality to track the process until it dies -bool Q_Exec(const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor); +bool Q_Exec( const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor ); // some easy portability crap @@ -73,29 +73,26 @@ bool Q_Exec(const char *cmd, char *cmdline, const char *execdir, bool bCreateCon #define access_others_rwx 0007 -#define access_rwxrwxr_x (access_owner_rwx | access_group_rwx | access_others_r_x) -#define access_rwxrwxrwx (access_owner_rwx | access_group_rwx | access_others_rwx) +#define access_rwxrwxr_x ( access_owner_rwx | access_group_rwx | access_others_r_x ) +#define access_rwxrwxrwx ( access_owner_rwx | access_group_rwx | access_others_rwx ) // Q_mkdir // returns true if succeeded in creating directory #ifdef WIN32 #include -inline bool Q_mkdir(const char* name) -{ - return _mkdir(name) != -1; +inline bool Q_mkdir( const char* name ){ + return _mkdir( name ) != -1; } #else #include -inline bool Q_mkdir(const char* name) -{ - return mkdir(name, access_rwxrwxr_x) != -1; +inline bool Q_mkdir( const char* name ){ + return mkdir( name, access_rwxrwxr_x ) != -1; } #endif -inline double Sys_DoubleTime(void) -{ - return clock()/ 1000.0; +inline double Sys_DoubleTime( void ){ + return clock() / 1000.0; } diff --git a/libs/cmdlib/cmdlib.cpp b/libs/cmdlib/cmdlib.cpp index f6ace0fe..2a9ab55a 100644 --- a/libs/cmdlib/cmdlib.cpp +++ b/libs/cmdlib/cmdlib.cpp @@ -1,27 +1,27 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // // start of shared cmdlib stuff -// +// #include "cmdlib.h" @@ -33,108 +33,105 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "container/array.h" -#if defined (POSIX) +#if defined ( POSIX ) #include #include #include -bool Q_Exec(const char *cmd, char *cmdline, const char *, bool, bool waitfor) -{ - char fullcmd[2048]; - char *pCmd; - pid_t pid; +bool Q_Exec( const char *cmd, char *cmdline, const char *, bool, bool waitfor ){ + char fullcmd[2048]; + char *pCmd; + pid_t pid; #ifdef _DEBUG - printf("Q_Exec damnit\n"); + printf( "Q_Exec damnit\n" ); #endif - switch ((pid = fork())) - { - default: - if(waitfor) - waitpid(pid, NULL, 0); - break; - case -1: - return true; - break; - case 0: - // always concat the command on linux - if (cmd) - { - strcpy(fullcmd, cmd); - } - else - fullcmd[0] = '\0'; - if (cmdline) - { - strcat(fullcmd, " "); - strcat(fullcmd, cmdline); - } - pCmd = fullcmd; - while (*pCmd == ' ') - pCmd++; + switch ( ( pid = fork() ) ) + { + default: + if ( waitfor ) { + waitpid( pid, NULL, 0 ); + } + break; + case -1: + return true; + break; + case 0: + // always concat the command on linux + if ( cmd ) { + strcpy( fullcmd, cmd ); + } + else{ + fullcmd[0] = '\0'; + } + if ( cmdline ) { + strcat( fullcmd, " " ); + strcat( fullcmd, cmdline ); + } + pCmd = fullcmd; + while ( *pCmd == ' ' ) + pCmd++; #ifdef _DEBUG - printf("Running system...\n"); - printf("Command: %s\n", pCmd); + printf( "Running system...\n" ); + printf( "Command: %s\n", pCmd ); #endif - system( pCmd ); + system( pCmd ); #ifdef _DEBUG - printf ("system() returned\n"); + printf( "system() returned\n" ); #endif - _exit (0); - break; - } - return true; + _exit( 0 ); + break; + } + return true; } -#elif defined(WIN32) +#elif defined( WIN32 ) #include // NOTE TTimo windows is VERY nitpicky about the syntax in CreateProcess -bool Q_Exec(const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor) -{ - PROCESS_INFORMATION ProcessInformation; - STARTUPINFO startupinfo = {0}; - DWORD dwCreationFlags; - GetStartupInfo (&startupinfo); - if (bCreateConsole) - dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; - else - dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; - const char *pCmd; - char *pCmdline; - pCmd = cmd; - if (pCmd) - { - while (*pCmd == ' ') - pCmd++; - } - pCmdline = cmdline; - if (pCmdline) - { - while (*pCmdline == ' ') - pCmdline++; - } - - if (CreateProcess( - pCmd, - pCmdline, - NULL, - NULL, - FALSE, - dwCreationFlags, - NULL, - execdir, - &startupinfo, - &ProcessInformation - )) - { - if(waitfor) - WaitForSingleObject(ProcessInformation.hProcess, INFINITE); - return true; - } - return false; +bool Q_Exec( const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor ){ + PROCESS_INFORMATION ProcessInformation; + STARTUPINFO startupinfo = {0}; + DWORD dwCreationFlags; + GetStartupInfo( &startupinfo ); + if ( bCreateConsole ) { + dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; + } + else{ + dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; + } + const char *pCmd; + char *pCmdline; + pCmd = cmd; + if ( pCmd ) { + while ( *pCmd == ' ' ) + pCmd++; + } + pCmdline = cmdline; + if ( pCmdline ) { + while ( *pCmdline == ' ' ) + pCmdline++; + } + + if ( CreateProcess( + pCmd, + pCmdline, + NULL, + NULL, + FALSE, + dwCreationFlags, + NULL, + execdir, + &startupinfo, + &ProcessInformation + ) ) { + if ( waitfor ) { + WaitForSingleObject( ProcessInformation.hProcess, INFINITE ); + } + return true; + } + return false; } #endif - diff --git a/libs/container/array.cpp b/libs/container/array.cpp index 378a2e76..8ce77f50 100644 --- a/libs/container/array.cpp +++ b/libs/container/array.cpp @@ -1,39 +1,37 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "array.h" namespace { - class Bleh - { - Array m_array; - public: - Bleh() : m_array(16) - { - } - }; +class Bleh +{ +Array m_array; +public: +Bleh() : m_array( 16 ){ +} +}; - void testAutoArray() - { - Array array(32); - } +void testAutoArray(){ + Array array( 32 ); +} } \ No newline at end of file diff --git a/libs/container/array.h b/libs/container/array.h index de444fd8..c359df15 100644 --- a/libs/container/array.h +++ b/libs/container/array.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_ARRAY_H) +#if !defined( INCLUDED_CONTAINER_ARRAY_H ) #define INCLUDED_CONTAINER_ARRAY_H #include @@ -30,7 +30,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// \brief An array whose size is variable at run-time. /// /// - Resizing the array destroys all the existing elements and invalidates all iterators. -/// - Default-Constructible, Copyable, Assignable. +/// - Default-Constructible, Copyable, Assignable. /// - Compatible with the containers and algorithms in the Standard Template Library (STL) - http://www.sgi.com/tech/stl/ /// /// \param Element The type to be stored in the array. Must provide a default-constructor and a copy-constructor. @@ -38,160 +38,133 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template > class Array : public Allocator { - std::size_t m_size; - Element* m_data; +std::size_t m_size; +Element* m_data; - Element* construct(std::size_t size) - { +Element* construct( std::size_t size ){ #if 1 - return New(*this).vector(size); + return New( *this ).vector( size ); #else - return new Element[size]; + return new Element[size]; #endif - } - template - Element* construct(std::size_t size, const T1& value) - { - return New(*this).vector(size, value); - } - void destroy(Element* data, std::size_t size) - { +} +template +Element* construct( std::size_t size, const T1& value ){ + return New( *this ).vector( size, value ); +} +void destroy( Element* data, std::size_t size ){ #if 1 - Delete(*this).vector(data, size); + Delete( *this ).vector( data, size ); #else - delete[] data; + delete[] data; #endif - } +} public: - typedef Element value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - - Array() - : m_size(0), m_data(0) - { - } - Array(std::size_t size) - : m_size(size), m_data(construct(size)) - { - } - template - Array(std::size_t size, const T1& value) - : m_size(size), m_data(construct(size, value)) - { - } - Array(const Array& other) - : Allocator(other), m_size(other.size()), m_data(construct(m_size)) - { - std::copy(other.begin(), other.end(), begin()); - } - template - Array(Iterator start, Iterator finish) - : m_size(std::distance(start, finish)), m_data(construct(m_size)) - { - std::copy(start, finish, begin()); - } - ~Array() - { - destroy(m_data, m_size); - } - - Array& operator=(const Array& other) - { - if(other.size() == size()) - { - std::copy(other.begin(), other.end(), begin()); - } - else - { - Array temp(other); - temp.swap(*this); - } - return *this; - } - - void swap(Array& other) - { - std::swap(m_size, other.m_size); - std::swap(m_data, other.m_data); - } - - iterator begin() - { - return m_data; - } - const_iterator begin() const - { - return m_data; - } - iterator end() - { - return m_data + m_size; - } - const_iterator end() const - { - return m_data + m_size; - } - - value_type& operator[](std::size_t index) - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); +typedef Element value_type; +typedef value_type* iterator; +typedef const value_type* const_iterator; + +Array() + : m_size( 0 ), m_data( 0 ){ +} +Array( std::size_t size ) + : m_size( size ), m_data( construct( size ) ){ +} +template +Array( std::size_t size, const T1& value ) + : m_size( size ), m_data( construct( size, value ) ){ +} +Array( const Array& other ) + : Allocator( other ), m_size( other.size() ), m_data( construct( m_size ) ){ + std::copy( other.begin(), other.end(), begin() ); +} +template +Array( Iterator start, Iterator finish ) + : m_size( std::distance( start, finish ) ), m_data( construct( m_size ) ){ + std::copy( start, finish, begin() ); +} +~Array(){ + destroy( m_data, m_size ); +} + +Array& operator=( const Array& other ){ + if ( other.size() == size() ) { + std::copy( other.begin(), other.end(), begin() ); + } + else + { + Array temp( other ); + temp.swap( *this ); + } + return *this; +} + +void swap( Array& other ){ + std::swap( m_size, other.m_size ); + std::swap( m_data, other.m_data ); +} + +iterator begin(){ + return m_data; +} +const_iterator begin() const { + return m_data; +} +iterator end(){ + return m_data + m_size; +} +const_iterator end() const { + return m_data + m_size; +} + +value_type& operator[]( std::size_t index ){ +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - const value_type& operator[](std::size_t index) const - { -#if defined(_DEBUG) - ASSERT_MESSAGE(index < size(), "array index out of bounds"); + return m_data[index]; +} +const value_type& operator[]( std::size_t index ) const { +#if defined( _DEBUG ) + ASSERT_MESSAGE( index < size(), "array index out of bounds" ); #endif - return m_data[index]; - } - value_type* data() - { - return m_data; - } - const value_type* data() const - { - return m_data; - } - std::size_t size() const - { - return m_size; - } - bool empty() const - { - return m_size == 0; - } - - void resize(std::size_t count) - { - if(count != size()) - { - Array temp(count); - temp.swap(*this); - } - } - void resize(std::size_t count, const value_type& value) - { - if(count != size()) - { - Array temp(count, value); - temp.swap(*this); - } - } + return m_data[index]; +} +value_type* data(){ + return m_data; +} +const value_type* data() const { + return m_data; +} +std::size_t size() const { + return m_size; +} +bool empty() const { + return m_size == 0; +} + +void resize( std::size_t count ){ + if ( count != size() ) { + Array temp( count ); + temp.swap( *this ); + } +} +void resize( std::size_t count, const value_type& value ){ + if ( count != size() ) { + Array temp( count, value ); + temp.swap( *this ); + } +} }; namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - template - inline void swap(Array& self, Array& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap. +template +inline void swap( Array& self, Array& other ){ + self.swap( other ); +} } #endif diff --git a/libs/container/cache.cpp b/libs/container/cache.cpp index a704287e..5cbdb00b 100644 --- a/libs/container/cache.cpp +++ b/libs/container/cache.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "cache.h" diff --git a/libs/container/cache.h b/libs/container/cache.h index 8c594b88..880a7a7a 100644 --- a/libs/container/cache.h +++ b/libs/container/cache.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_CACHE_H) +#if !defined( INCLUDED_CONTAINER_CACHE_H ) #define INCLUDED_CONTAINER_CACHE_H #include @@ -30,69 +30,57 @@ template class DefaultCreationPolicy { public: - Type* construct(const Parameter& parameter) - { - return New().scalar(parameter); - } - void destroy(Type* p) - { - Delete().scalar(p); - } +Type* construct( const Parameter& parameter ){ + return New().scalar( parameter ); +} +void destroy( Type* p ){ + Delete().scalar( p ); +} }; template class SharedValue { - typedef Type value_type; - typedef value_type* pointer; - typedef value_type& reference; +typedef Type value_type; +typedef value_type* pointer; +typedef value_type& reference; - std::size_t m_count; - pointer m_value; +std::size_t m_count; +pointer m_value; public: - SharedValue() - : m_count(0), m_value(0) - { - } - ~SharedValue() - { - ASSERT_MESSAGE(m_count == 0 , "destroying a referenced object\n"); - } - void set(pointer value) - { - m_value = value; - } - pointer get() - { - return m_value; - } - std::size_t increment() - { - return ++m_count; - } - std::size_t decrement() - { - ASSERT_MESSAGE(!empty(), "destroying a non-existent object\n"); - return --m_count; - } - std::size_t count() - { - return m_count; - } - bool empty() - { - return m_count == 0; - } - reference operator*() const - { - ASSERT_NOTNULL(m_value); - return *m_value; - } - pointer operator->() const - { - return &(operator*()); - } +SharedValue() + : m_count( 0 ), m_value( 0 ){ +} +~SharedValue(){ + ASSERT_MESSAGE( m_count == 0, "destroying a referenced object\n" ); +} +void set( pointer value ){ + m_value = value; +} +pointer get(){ + return m_value; +} +std::size_t increment(){ + return ++m_count; +} +std::size_t decrement(){ + ASSERT_MESSAGE( !empty(), "destroying a non-existent object\n" ); + return --m_count; +} +std::size_t count(){ + return m_count; +} +bool empty(){ + return m_count == 0; +} +reference operator*() const { + ASSERT_NOTNULL( m_value ); + return *m_value; +} +pointer operator->() const { + return &( operator*() ); +} }; @@ -107,99 +95,83 @@ public: template, typename CreationPolicy = DefaultCreationPolicy > class HashedCache : public CreationPolicy { - typedef SharedValue Element; - typedef HashTable map_type; +typedef SharedValue Element; +typedef HashTable map_type; - map_type m_map; +map_type m_map; public: - explicit HashedCache(const CreationPolicy& creation = CreationPolicy()) - : CreationPolicy(creation), m_map(256) - { - } - ~HashedCache() - { - ASSERT_MESSAGE(empty(), "HashedCache::~HashedCache: not empty"); - } - - typedef typename map_type::iterator iterator; - typedef typename map_type::value_type value_type; - - iterator begin() - { - return m_map.begin(); - } - iterator end() - { - return m_map.end(); - } - - bool empty() const - { - return m_map.empty(); - } - - iterator find(const Key& key) - { - return m_map.find(key); - } - - void capture(iterator i) - { - (*i).value.increment(); - } - void release(iterator i) - { - if((*i).value.decrement() == 0) - { - CreationPolicy::destroy((*i).value.get()); - m_map.erase(i); - } - } +explicit HashedCache( const CreationPolicy& creation = CreationPolicy() ) + : CreationPolicy( creation ), m_map( 256 ){ +} +~HashedCache(){ + ASSERT_MESSAGE( empty(), "HashedCache::~HashedCache: not empty" ); +} + +typedef typename map_type::iterator iterator; +typedef typename map_type::value_type value_type; + +iterator begin(){ + return m_map.begin(); +} +iterator end(){ + return m_map.end(); +} + +bool empty() const { + return m_map.empty(); +} + +iterator find( const Key& key ){ + return m_map.find( key ); +} + +void capture( iterator i ){ + ( *i ).value.increment(); +} +void release( iterator i ){ + if ( ( *i ).value.decrement() == 0 ) { + CreationPolicy::destroy( ( *i ).value.get() ); + m_map.erase( i ); + } +} #if 1 - Element& capture(const Key& key) - { +Element& capture( const Key& key ){ #if 0 - Element& elem = m_map[key]; - if(elem.increment() == 1) - { - elem.set(CreationPolicy::construct(key)); - } - return elem; + Element& elem = m_map[key]; + if ( elem.increment() == 1 ) { + elem.set( CreationPolicy::construct( key ) ); + } + return elem; #else - iterator i = m_map.insert(key, Element()); - if((*i).value.increment() == 1) - { - (*i).value.set(CreationPolicy::construct((*i).key)); - } - return (*i).value; + iterator i = m_map.insert( key, Element() ); + if ( ( *i ).value.increment() == 1 ) { + ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); + } + return ( *i ).value; #endif - } +} #else - value_type& capture(const Key& key) - { - iterator i = m_map.find(key); - if(i == m_map.end()) - { - i = m_map.insert(key, Element()); - (*i).value.set(CreationPolicy::construct((*i).key)); - } - (*i).value.increment(); - return (*i); - } +value_type& capture( const Key& key ){ + iterator i = m_map.find( key ); + if ( i == m_map.end() ) { + i = m_map.insert( key, Element() ); + ( *i ).value.set( CreationPolicy::construct( ( *i ).key ) ); + } + ( *i ).value.increment(); + return ( *i ); +} #endif - void release(const Key& key) - { - iterator i = m_map.find(key); - ASSERT_MESSAGE(i != m_map.end(), "releasing a non-existent object\n"); - release(i); - } - - void clear() - { - m_map.clear(); - } +void release( const Key& key ){ + iterator i = m_map.find( key ); + ASSERT_MESSAGE( i != m_map.end(), "releasing a non-existent object\n" ); + release( i ); +} + +void clear(){ + m_map.clear(); +} }; diff --git a/libs/container/container.cpp b/libs/container/container.cpp index 627e0c88..8790307e 100644 --- a/libs/container/container.cpp +++ b/libs/container/container.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "container.h" - diff --git a/libs/container/container.h b/libs/container/container.h index b6d75841..47f823e6 100644 --- a/libs/container/container.h +++ b/libs/container/container.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_CONTAINER_H) +#if !defined( INCLUDED_CONTAINER_CONTAINER_H ) #define INCLUDED_CONTAINER_CONTAINER_H #include @@ -31,35 +31,29 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class Single { - Type* m_value; +Type* m_value; public: - Single() : m_value(0) - { - } - bool empty() - { - return m_value == 0; - } - Type* insert(const Type& other) - { - m_value = new Type(other); - return m_value; - } - void clear() - { - delete m_value; - m_value = 0; - } - Type& get() - { - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; - } - const Type& get() const - { - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; - } +Single() : m_value( 0 ){ +} +bool empty(){ + return m_value == 0; +} +Type* insert( const Type& other ){ + m_value = new Type( other ); + return m_value; +} +void clear(){ + delete m_value; + m_value = 0; +} +Type& get(){ + //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); + return *m_value; +} +const Type& get() const { + //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); + return *m_value; +} }; @@ -68,91 +62,75 @@ public: template class UnsortedSet { - typedef typename std::list Values; - Values m_values; +typedef typename std::list Values; +Values m_values; public: - typedef typename Values::iterator iterator; - typedef typename Values::const_iterator const_iterator; - typedef typename Values::reverse_iterator reverse_iterator; - typedef typename Values::const_reverse_iterator const_reverse_iterator; +typedef typename Values::iterator iterator; +typedef typename Values::const_iterator const_iterator; +typedef typename Values::reverse_iterator reverse_iterator; +typedef typename Values::const_reverse_iterator const_reverse_iterator; - iterator begin() - { - return m_values.begin(); - } - const_iterator begin() const - { - return m_values.begin(); - } - iterator end() - { - return m_values.end(); - } - const_iterator end() const - { - return m_values.end(); - } - reverse_iterator rbegin() - { - return m_values.rbegin(); - } - const_reverse_iterator rbegin() const - { - return m_values.rbegin(); - } - reverse_iterator rend() - { - return m_values.rend(); - } - const_reverse_iterator rend() const - { - return m_values.rend(); - } +iterator begin(){ + return m_values.begin(); +} +const_iterator begin() const { + return m_values.begin(); +} +iterator end(){ + return m_values.end(); +} +const_iterator end() const { + return m_values.end(); +} +reverse_iterator rbegin(){ + return m_values.rbegin(); +} +const_reverse_iterator rbegin() const { + return m_values.rbegin(); +} +reverse_iterator rend(){ + return m_values.rend(); +} +const_reverse_iterator rend() const { + return m_values.rend(); +} - bool empty() const - { - return m_values.empty(); - } - std::size_t size() const - { - return m_values.size(); - } - void clear() - { - m_values.clear(); - } +bool empty() const { + return m_values.empty(); +} +std::size_t size() const { + return m_values.size(); +} +void clear(){ + m_values.clear(); +} - void swap(UnsortedSet& other) - { - std::swap(m_values, other.m_values); - } - iterator insert(const Value& value) - { - ASSERT_MESSAGE(find(value) == end(), "UnsortedSet::insert: already added"); - m_values.push_back(value); - return --end(); - } - void erase(const Value& value) - { - iterator i = find(value); - ASSERT_MESSAGE(i != end(), "UnsortedSet::erase: not found"); - m_values.erase(i); - } - iterator find(const Value& value) - { - return std::find(begin(), end(), value); - } +void swap( UnsortedSet& other ){ + std::swap( m_values, other.m_values ); +} +iterator insert( const Value& value ){ + ASSERT_MESSAGE( find( value ) == end(), "UnsortedSet::insert: already added" ); + m_values.push_back( value ); + return --end(); +} +void erase( const Value& value ){ + iterator i = find( value ); + ASSERT_MESSAGE( i != end(), "UnsortedSet::erase: not found" ); + m_values.erase( i ); +} +iterator find( const Value& value ){ + return std::find( begin(), end(), value ); +} }; namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - template - inline void swap(UnsortedSet& self, UnsortedSet& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap. +template +inline void swap( UnsortedSet& self, UnsortedSet& other ){ + self.swap( other ); +} } /// An adaptor to make std::list into a Unique Associative Sequence - which cannot contain the same value more than once. @@ -161,232 +139,190 @@ namespace std template class UnsortedMap { - typedef typename std::list< std::pair > Values; - Values m_values; +typedef typename std::list< std::pair > Values; +Values m_values; public: - typedef typename Values::value_type value_type; - typedef typename Values::iterator iterator; - typedef typename Values::const_iterator const_iterator; +typedef typename Values::value_type value_type; +typedef typename Values::iterator iterator; +typedef typename Values::const_iterator const_iterator; - iterator begin() - { - return m_values.begin(); - } - const_iterator begin() const - { - return m_values.begin(); - } - iterator end() - { - return m_values.end(); - } - const_iterator end() const - { - return m_values.end(); - } +iterator begin(){ + return m_values.begin(); +} +const_iterator begin() const { + return m_values.begin(); +} +iterator end(){ + return m_values.end(); +} +const_iterator end() const { + return m_values.end(); +} + +bool empty() const { + return m_values.empty(); +} +std::size_t size() const { + return m_values.size(); +} +void clear(){ + m_values.clear(); +} - bool empty() const - { - return m_values.empty(); - } - std::size_t size() const - { - return m_values.size(); - } - void clear() - { - m_values.clear(); - } +iterator insert( const value_type& value ){ + ASSERT_MESSAGE( find( value.first ) == end(), "UnsortedMap::insert: already added" ); + m_values.push_back( value ); + return --m_values.end(); +} +void erase( const Key& key ){ + iterator i = find( key ); + ASSERT_MESSAGE( i != end(), "UnsortedMap::erase: not found" ); + erase( i ); +} +void erase( iterator i ){ + m_values.erase( i ); +} +iterator find( const Key& key ){ + for ( iterator i = m_values.begin(); i != m_values.end(); ++i ) + { + if ( ( *i ).first == key ) { + return i; + } + } + return m_values.end(); +} +const_iterator find( const Key& key ) const { + for ( const_iterator i = m_values.begin(); i != m_values.end(); ++i ) + { + if ( ( *i ).first == key ) { + return i; + } + } + return m_values.end(); +} - iterator insert(const value_type& value) - { - ASSERT_MESSAGE(find(value.first) == end(), "UnsortedMap::insert: already added"); - m_values.push_back(value); - return --m_values.end(); - } - void erase(const Key& key) - { - iterator i = find(key); - ASSERT_MESSAGE(i != end(), "UnsortedMap::erase: not found"); - erase(i); - } - void erase(iterator i) - { - m_values.erase(i); - } - iterator find(const Key& key) - { - for(iterator i = m_values.begin(); i != m_values.end(); ++i) - { - if((*i).first == key) - { - return i; - } - } - return m_values.end(); - } - const_iterator find(const Key& key) const - { - for(const_iterator i = m_values.begin(); i != m_values.end(); ++i) - { - if((*i).first == key) - { - return i; - } - } - return m_values.end(); - } +Value& operator[]( const Key& key ){ + iterator i = find( key ); + if ( i != end() ) { + return ( *i ).second; + } - Value& operator[](const Key& key) - { - iterator i = find(key); - if(i != end()) - { - return (*i).second; - } - - m_values.push_back(Values::value_type(key, Value())); - return m_values.back().second; - } + m_values.push_back( Values::value_type( key, Value() ) ); + return m_values.back().second; +} }; /// An adaptor to assert when duplicate values are added, or non-existent values removed from a std::set. template class UniqueSet { - typedef std::set Values; - Values m_values; +typedef std::set Values; +Values m_values; public: - typedef typename Values::iterator iterator; - typedef typename Values::const_iterator const_iterator; - typedef typename Values::reverse_iterator reverse_iterator; - typedef typename Values::const_reverse_iterator const_reverse_iterator; +typedef typename Values::iterator iterator; +typedef typename Values::const_iterator const_iterator; +typedef typename Values::reverse_iterator reverse_iterator; +typedef typename Values::const_reverse_iterator const_reverse_iterator; - iterator begin() - { - return m_values.begin(); - } - const_iterator begin() const - { - return m_values.begin(); - } - iterator end() - { - return m_values.end(); - } - const_iterator end() const - { - return m_values.end(); - } - reverse_iterator rbegin() - { - return m_values.rbegin(); - } - const_reverse_iterator rbegin() const - { - return m_values.rbegin(); - } - reverse_iterator rend() - { - return m_values.rend(); - } - const_reverse_iterator rend() const - { - return m_values.rend(); - } +iterator begin(){ + return m_values.begin(); +} +const_iterator begin() const { + return m_values.begin(); +} +iterator end(){ + return m_values.end(); +} +const_iterator end() const { + return m_values.end(); +} +reverse_iterator rbegin(){ + return m_values.rbegin(); +} +const_reverse_iterator rbegin() const { + return m_values.rbegin(); +} +reverse_iterator rend(){ + return m_values.rend(); +} +const_reverse_iterator rend() const { + return m_values.rend(); +} - bool empty() const - { - return m_values.empty(); - } - std::size_t size() const - { - return m_values.size(); - } - void clear() - { - m_values.clear(); - } +bool empty() const { + return m_values.empty(); +} +std::size_t size() const { + return m_values.size(); +} +void clear(){ + m_values.clear(); +} - void swap(UniqueSet& other) - { - std::swap(m_values, other.m_values); - } - iterator insert(const Value& value) - { - std::pair result = m_values.insert(value); - ASSERT_MESSAGE(result.second, "UniqueSet::insert: already added"); - return result.first; - } - void erase(const Value& value) - { - iterator i = find(value); - ASSERT_MESSAGE(i != end(), "UniqueSet::erase: not found"); - m_values.erase(i); - } - iterator find(const Value& value) - { - return std::find(begin(), end(), value); - } +void swap( UniqueSet& other ){ + std::swap( m_values, other.m_values ); +} +iterator insert( const Value& value ){ + std::pair result = m_values.insert( value ); + ASSERT_MESSAGE( result.second, "UniqueSet::insert: already added" ); + return result.first; +} +void erase( const Value& value ){ + iterator i = find( value ); + ASSERT_MESSAGE( i != end(), "UniqueSet::erase: not found" ); + m_values.erase( i ); +} +iterator find( const Value& value ){ + return std::find( begin(), end(), value ); +} }; namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - template - inline void swap(UniqueSet& self, UniqueSet& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap. +template +inline void swap( UniqueSet& self, UniqueSet& other ){ + self.swap( other ); +} } template class ReferencePair { - Type* m_first; - Type* m_second; +Type* m_first; +Type* m_second; public: - ReferencePair() : m_first(0), m_second(0) - { - } - void attach(Type& t) - { - ASSERT_MESSAGE(m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists"); - if(m_first == 0) - { - m_first = &t; - } - else if(m_second == 0) - { - m_second = &t; - } - } - void detach(Type& t) - { - ASSERT_MESSAGE(m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found"); - if(m_first == &t) - { - m_first = 0; - } - else if(m_second == &t) - { - m_second = 0; - } - } - template - void forEach(const Functor& functor) - { - if(m_second != 0) - { - functor(*m_second); - } - if(m_first != 0) - { - functor(*m_first); - } - } +ReferencePair() : m_first( 0 ), m_second( 0 ){ +} +void attach( Type& t ){ + ASSERT_MESSAGE( m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists" ); + if ( m_first == 0 ) { + m_first = &t; + } + else if ( m_second == 0 ) { + m_second = &t; + } +} +void detach( Type& t ){ + ASSERT_MESSAGE( m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found" ); + if ( m_first == &t ) { + m_first = 0; + } + else if ( m_second == &t ) { + m_second = 0; + } +} +template +void forEach( const Functor& functor ){ + if ( m_second != 0 ) { + functor( *m_second ); + } + if ( m_first != 0 ) { + functor( *m_first ); + } +} }; diff --git a/libs/container/hashfunc.cpp b/libs/container/hashfunc.cpp index 20569cd1..4c3d2e07 100644 --- a/libs/container/hashfunc.cpp +++ b/libs/container/hashfunc.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "hashfunc.h" diff --git a/libs/container/hashfunc.h b/libs/container/hashfunc.h index a4ec5fee..6d216697 100644 --- a/libs/container/hashfunc.h +++ b/libs/container/hashfunc.h @@ -1,359 +1,338 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_HASHFUNC_H) +#if !defined( INCLUDED_CONTAINER_HASHFUNC_H ) #define INCLUDED_CONTAINER_HASHFUNC_H #include #include "string/string.h" #include "container/array.h" -typedef unsigned long int ub4; /* unsigned 4-byte quantities */ -typedef unsigned char ub1; +typedef unsigned long int ub4; /* unsigned 4-byte quantities */ +typedef unsigned char ub1; -inline ub1 ub1_as_ub1_nocase(ub1 byte) -{ - return std::tolower(byte); +inline ub1 ub1_as_ub1_nocase( ub1 byte ){ + return std::tolower( byte ); } -inline ub4 ub1x4_as_ub4_nocase(const ub1 bytes[4]) -{ - ub4 result; - reinterpret_cast(&result)[0] = ub1_as_ub1_nocase(bytes[0]); - reinterpret_cast(&result)[1] = ub1_as_ub1_nocase(bytes[1]); - reinterpret_cast(&result)[2] = ub1_as_ub1_nocase(bytes[2]); - reinterpret_cast(&result)[3] = ub1_as_ub1_nocase(bytes[3]); - return result; +inline ub4 ub1x4_as_ub4_nocase( const ub1 bytes[4] ){ + ub4 result; + reinterpret_cast( &result )[0] = ub1_as_ub1_nocase( bytes[0] ); + reinterpret_cast( &result )[1] = ub1_as_ub1_nocase( bytes[1] ); + reinterpret_cast( &result )[2] = ub1_as_ub1_nocase( bytes[2] ); + reinterpret_cast( &result )[3] = ub1_as_ub1_nocase( bytes[3] ); + return result; } class ub1_default_traits { public: - static ub1 as_ub1(ub1 byte) - { - return byte; - } +static ub1 as_ub1( ub1 byte ){ + return byte; +} }; class ub1_nocase_traits { public: - static ub1 as_ub1(ub1 byte) - { - return ub1_as_ub1_nocase(byte); - } +static ub1 as_ub1( ub1 byte ){ + return ub1_as_ub1_nocase( byte ); +} }; class ub1x4_default_traits { public: - static ub4 as_ub4(const ub1 bytes[4]) - { - return *reinterpret_cast(bytes); - } +static ub4 as_ub4( const ub1 bytes[4] ){ + return *reinterpret_cast( bytes ); +} }; class ub1x4_nocase_traits { public: - static ub4 as_ub4(const ub1 bytes[4]) - { - return ub1x4_as_ub4_nocase(bytes); - } +static ub4 as_ub4( const ub1 bytes[4] ){ + return ub1x4_as_ub4_nocase( bytes ); +} }; class ub4_default_traits { public: - static ub4 as_ub4(ub4 i) - { - return i; - } +static ub4 as_ub4( ub4 i ){ + return i; +} }; class ub4_nocase_traits { public: - static ub4 as_ub4(ub4 i) - { - return ub1x4_as_ub4_nocase(reinterpret_cast(&i)); - } +static ub4 as_ub4( ub4 i ){ + return ub1x4_as_ub4_nocase( reinterpret_cast( &i ) ); +} }; // lookup2.c // By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this // code any way you wish, private, educational, or commercial. It's free. -#define hashsize(n) ((ub4)1<<(n)) -#define hashmask(n) (hashsize(n)-1) +#define hashsize( n ) ( (ub4)1 << ( n ) ) +#define hashmask( n ) ( hashsize( n ) - 1 ) /* --------------------------------------------------------------------- -mix -- mix 3 32-bit values reversibly. -For every delta with one or two bit set, and the deltas of all three - high bits or all three low bits, whether the original value of a,b,c - is almost all zero or is uniformly distributed, -* If mix() is run forward or backward, at least 32 bits in a,b,c - have at least 1/4 probability of changing. -* If mix() is run forward, every bit of c will change between 1/3 and - 2/3 of the time. (Well, 22/100 and 78/100 for some 2-bit deltas.) -mix() was built out of 36 single-cycle latency instructions in a - structure that could supported 2x parallelism, like so: - a -= b; + -------------------------------------------------------------------- + mix -- mix 3 32-bit values reversibly. + For every delta with one or two bit set, and the deltas of all three + high bits or all three low bits, whether the original value of a,b,c + is almost all zero or is uniformly distributed, + * If mix() is run forward or backward, at least 32 bits in a,b,c + have at least 1/4 probability of changing. + * If mix() is run forward, every bit of c will change between 1/3 and + 2/3 of the time. (Well, 22/100 and 78/100 for some 2-bit deltas.) + mix() was built out of 36 single-cycle latency instructions in a + structure that could supported 2x parallelism, like so: + a -= b; a -= c; x = (c>>13); b -= c; a ^= x; b -= a; x = (a<<8); c -= a; b ^= x; c -= b; x = (b>>13); ... - Unfortunately, superscalar Pentiums and Sparcs can't take advantage - of that parallelism. They've also turned some of those single-cycle - latency instructions into multi-cycle latency instructions. Still, - this is the fastest good hash I could find. There were about 2^^68 - to choose from. I only looked at a billion or so. --------------------------------------------------------------------- -*/ -#define mix(a,b,c) \ -{ \ - a -= b; a -= c; a ^= (c>>13); \ - b -= c; b -= a; b ^= (a<<8); \ - c -= a; c -= b; c ^= (b>>13); \ - a -= b; a -= c; a ^= (c>>12); \ - b -= c; b -= a; b ^= (a<<16); \ - c -= a; c -= b; c ^= (b>>5); \ - a -= b; a -= c; a ^= (c>>3); \ - b -= c; b -= a; b ^= (a<<10); \ - c -= a; c -= b; c ^= (b>>15); \ -} + Unfortunately, superscalar Pentiums and Sparcs can't take advantage + of that parallelism. They've also turned some of those single-cycle + latency instructions into multi-cycle latency instructions. Still, + this is the fastest good hash I could find. There were about 2^^68 + to choose from. I only looked at a billion or so. + -------------------------------------------------------------------- + */ +#define mix( a,b,c ) \ + { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ + } /* same, but slower, works on systems that might have 8 byte ub4's */ -#define mix2(a,b,c) \ -{ \ - a -= b; a -= c; a ^= (c>>13); \ - b -= c; b -= a; b ^= (a<< 8); \ - c -= a; c -= b; c ^= ((b&0xffffffff)>>13); \ - a -= b; a -= c; a ^= ((c&0xffffffff)>>12); \ - b -= c; b -= a; b = (b ^ (a<<16)) & 0xffffffff; \ - c -= a; c -= b; c = (c ^ (b>> 5)) & 0xffffffff; \ - a -= b; a -= c; a = (a ^ (c>> 3)) & 0xffffffff; \ - b -= c; b -= a; b = (b ^ (a<<10)) & 0xffffffff; \ - c -= a; c -= b; c = (c ^ (b>>15)) & 0xffffffff; \ -} +#define mix2( a,b,c ) \ + { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( ( b & 0xffffffff ) >> 13 ); \ + a -= b; a -= c; a ^= ( ( c & 0xffffffff ) >> 12 ); \ + b -= c; b -= a; b = ( b ^ ( a << 16 ) ) & 0xffffffff; \ + c -= a; c -= b; c = ( c ^ ( b >> 5 ) ) & 0xffffffff; \ + a -= b; a -= c; a = ( a ^ ( c >> 3 ) ) & 0xffffffff; \ + b -= c; b -= a; b = ( b ^ ( a << 10 ) ) & 0xffffffff; \ + c -= a; c -= b; c = ( c ^ ( b >> 15 ) ) & 0xffffffff; \ + } /* --------------------------------------------------------------------- -hash() -- hash a variable-length key into a 32-bit value - k : the key (the unaligned variable-length array of bytes) - len : the length of the key, counting by bytes - level : can be any 4-byte value -Returns a 32-bit value. Every bit of the key affects every bit of -the return value. Every 1-bit and 2-bit delta achieves avalanche. -About 36+6len instructions. - -The best hash table sizes are powers of 2. There is no need to do -mod a prime (mod is sooo slow!). If you need less than 32 bits, -use a bitmask. For example, if you need only 10 bits, do - h = (h & hashmask(10)); -In which case, the hash table should have hashsize(10) elements. - -If you are hashing n strings (ub1 **)k, do it like this: - for (i=0, h=0; i inline ub4 hash( -const ub1 *k, /* the key */ -ub4 length, /* the length of the key */ -ub4 initval, /* the previous hash, or an arbitrary value */ -const UB1Traits& ub1traits, -const UB4x1Traits& ub4x1traits -) -{ - register ub4 a,b,c,len; - - /* Set up the internal state */ - len = length; - a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ - c = initval; /* the previous hash value */ - - /*---------------------------------------- handle most of the key */ - while (len >= 12) - { - a += (k[0] +((ub4)UB1Traits::as_ub1(k[1])<<8) +((ub4)UB1Traits::as_ub1(k[2])<<16) +((ub4)UB1Traits::as_ub1(k[3])<<24)); - b += (k[4] +((ub4)UB1Traits::as_ub1(k[5])<<8) +((ub4)UB1Traits::as_ub1(k[6])<<16) +((ub4)UB1Traits::as_ub1(k[7])<<24)); - c += (k[8] +((ub4)UB1Traits::as_ub1(k[9])<<8) +((ub4)UB1Traits::as_ub1(k[10])<<16)+((ub4)UB1Traits::as_ub1(k[11])<<24)); - mix(a,b,c); - k += 12; len -= 12; - } - - /*------------------------------------- handle the last 11 bytes */ - c += length; - switch(len) /* all the case statements fall through */ - { - case 11: c += ((ub4)UB1Traits::as_ub1(k[10]) << 24); - case 10: c += ((ub4)UB1Traits::as_ub1(k[9]) << 16); - case 9 : c += ((ub4)UB1Traits::as_ub1(k[8]) << 8); - /* the first byte of c is reserved for the length */ - case 8 : b += ((ub4)UB1Traits::as_ub1(k[7]) << 24); - case 7 : b += ((ub4)UB1Traits::as_ub1(k[6]) << 16); - case 6 : b += ((ub4)UB1Traits::as_ub1(k[5]) << 8); - case 5 : b += UB1Traits::as_ub1(k[4]); - case 4 : a += ((ub4)UB1Traits::as_ub1(k[3]) << 24); - case 3 : a += ((ub4)UB1Traits::as_ub1(k[2]) << 16); - case 2 : a += ((ub4)UB1Traits::as_ub1(k[1]) << 8); - case 1 : a += UB1Traits::as_ub1(k[0]); - /* case 0: nothing left to add */ - } - mix(a,b,c); - /*-------------------------------------------- report the result */ - return c; + const ub1 *k, /* the key */ + ub4 length, /* the length of the key */ + ub4 initval, /* the previous hash, or an arbitrary value */ + const UB1Traits& ub1traits, + const UB4x1Traits& ub4x1traits + ){ + register ub4 a,b,c,len; + + /* Set up the internal state */ + len = length; + a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ + c = initval; /* the previous hash value */ + + /*---------------------------------------- handle most of the key */ + while ( len >= 12 ) + { + a += ( k[0] + ( ( ub4 ) UB1Traits::as_ub1( k[1] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[2] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[3] ) << 24 ) ); + b += ( k[4] + ( ( ub4 ) UB1Traits::as_ub1( k[5] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[6] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[7] ) << 24 ) ); + c += ( k[8] + ( ( ub4 ) UB1Traits::as_ub1( k[9] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[10] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[11] ) << 24 ) ); + mix( a,b,c ); + k += 12; len -= 12; + } + + /*------------------------------------- handle the last 11 bytes */ + c += length; + switch ( len ) /* all the case statements fall through */ + { + case 11: c += ( ( ub4 ) UB1Traits::as_ub1( k[10] ) << 24 ); + case 10: c += ( ( ub4 ) UB1Traits::as_ub1( k[9] ) << 16 ); + case 9: c += ( ( ub4 ) UB1Traits::as_ub1( k[8] ) << 8 ); + /* the first byte of c is reserved for the length */ + case 8: b += ( ( ub4 ) UB1Traits::as_ub1( k[7] ) << 24 ); + case 7: b += ( ( ub4 ) UB1Traits::as_ub1( k[6] ) << 16 ); + case 6: b += ( ( ub4 ) UB1Traits::as_ub1( k[5] ) << 8 ); + case 5: b += UB1Traits::as_ub1( k[4] ); + case 4: a += ( ( ub4 ) UB1Traits::as_ub1( k[3] ) << 24 ); + case 3: a += ( ( ub4 ) UB1Traits::as_ub1( k[2] ) << 16 ); + case 2: a += ( ( ub4 ) UB1Traits::as_ub1( k[1] ) << 8 ); + case 1: a += UB1Traits::as_ub1( k[0] ); + /* case 0: nothing left to add */ + } + mix( a,b,c ); + /*-------------------------------------------- report the result */ + return c; } /* --------------------------------------------------------------------- - This works on all machines. hash2() is identical to hash() on - little-endian machines, except that the length has to be measured - in ub4s instead of bytes. It is much faster than hash(). It - requires - -- that the key be an array of ub4's, and - -- that all your machines have the same endianness, and - -- that the length be the number of ub4's in the key --------------------------------------------------------------------- -*/ + -------------------------------------------------------------------- + This works on all machines. hash2() is identical to hash() on + little-endian machines, except that the length has to be measured + in ub4s instead of bytes. It is much faster than hash(). It + requires + -- that the key be an array of ub4's, and + -- that all your machines have the same endianness, and + -- that the length be the number of ub4's in the key + -------------------------------------------------------------------- + */ template inline ub4 hash2( -const ub4 *k, /* the key */ -ub4 length, /* the length of the key, in ub4s */ -ub4 initval, /* the previous hash, or an arbitrary value */ -const UB4Traits& ub4traits -) -{ - register ub4 a,b,c,len; - - /* Set up the internal state */ - len = length; - a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ - c = initval; /* the previous hash value */ - - /*---------------------------------------- handle most of the key */ - while (len >= 3) - { - a += UB4Traits::as_ub4(k[0]); - b += UB4Traits::as_ub4(k[1]); - c += UB4Traits::as_ub4(k[2]); - mix(a,b,c); - k += 3; len -= 3; - } - - /*-------------------------------------- handle the last 2 ub4's */ - c += length; - switch(len) /* all the case statements fall through */ - { - /* c is reserved for the length */ - case 2 : b += UB4Traits::as_ub4(k[1]); - case 1 : a += UB4Traits::as_ub4(k[0]); - /* case 0: nothing left to add */ - } - mix(a,b,c); - /*-------------------------------------------- report the result */ - return c; + const ub4 *k, /* the key */ + ub4 length, /* the length of the key, in ub4s */ + ub4 initval, /* the previous hash, or an arbitrary value */ + const UB4Traits& ub4traits + ){ + register ub4 a,b,c,len; + + /* Set up the internal state */ + len = length; + a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ + c = initval; /* the previous hash value */ + + /*---------------------------------------- handle most of the key */ + while ( len >= 3 ) + { + a += UB4Traits::as_ub4( k[0] ); + b += UB4Traits::as_ub4( k[1] ); + c += UB4Traits::as_ub4( k[2] ); + mix( a,b,c ); + k += 3; len -= 3; + } + + /*-------------------------------------- handle the last 2 ub4's */ + c += length; + switch ( len ) /* all the case statements fall through */ + { + /* c is reserved for the length */ + case 2: b += UB4Traits::as_ub4( k[1] ); + case 1: a += UB4Traits::as_ub4( k[0] ); + /* case 0: nothing left to add */ + } + mix( a,b,c ); + /*-------------------------------------------- report the result */ + return c; } typedef ub4 hash_t; -inline hash_t hash_ub1(const ub1* key, std::size_t len, hash_t previous = 0) -{ - return hash(key, ub4(len), previous, ub1_default_traits(), ub1x4_default_traits()); +inline hash_t hash_ub1( const ub1* key, std::size_t len, hash_t previous = 0 ){ + return hash( key, ub4( len ), previous, ub1_default_traits(), ub1x4_default_traits() ); } -inline hash_t hash_ub1_nocase(const ub1* key, std::size_t len, hash_t previous = 0) -{ - return hash(key, ub4(len), previous, ub1_nocase_traits(), ub1x4_nocase_traits()); +inline hash_t hash_ub1_nocase( const ub1* key, std::size_t len, hash_t previous = 0 ){ + return hash( key, ub4( len ), previous, ub1_nocase_traits(), ub1x4_nocase_traits() ); } template -inline hash_t hash_ub4(const ub4* key, std::size_t len, const UB4Traits& traits, hash_t previous = 0) -{ - return hash2(key,ub4(len), previous, traits); +inline hash_t hash_ub4( const ub4* key, std::size_t len, const UB4Traits& traits, hash_t previous = 0 ){ + return hash2( key,ub4( len ), previous, traits ); } -inline ub4 hash_combine(ub4 left, ub4 right) -{ - return hash_ub1(reinterpret_cast(&left), 4, right); +inline ub4 hash_combine( ub4 left, ub4 right ){ + return hash_ub1( reinterpret_cast( &left ), 4, right ); } template -inline hash_t pod_hash(const POD& pod) -{ - return hash_ub1(reinterpret_cast(&pod), sizeof(POD)); +inline hash_t pod_hash( const POD& pod ){ + return hash_ub1( reinterpret_cast( &pod ), sizeof( POD ) ); } -inline hash_t string_hash(const char* string, hash_t previous = 0) -{ - return hash_ub1(reinterpret_cast(string), string_length(string), previous); +inline hash_t string_hash( const char* string, hash_t previous = 0 ){ + return hash_ub1( reinterpret_cast( string ), string_length( string ), previous ); } -inline hash_t string_hash_nocase(const char* string, hash_t previous = 0) -{ - return hash_ub1_nocase(reinterpret_cast(string), string_length(string), previous); +inline hash_t string_hash_nocase( const char* string, hash_t previous = 0 ){ + return hash_ub1_nocase( reinterpret_cast( string ), string_length( string ), previous ); } struct RawStringHash { - typedef hash_t hash_type; - hash_type operator()(const char* string) const - { - return string_hash(string); - } + typedef hash_t hash_type; + hash_type operator()( const char* string ) const { + return string_hash( string ); + } }; struct HashString { - typedef hash_t hash_type; - hash_type operator()(const CopiedString& string) const - { - return string_hash(string.c_str()); - } + typedef hash_t hash_type; + hash_type operator()( const CopiedString& string ) const { + return string_hash( string.c_str() ); + } }; struct HashStringNoCase { - typedef hash_t hash_type; - hash_type operator()(const CopiedString& string) const - { - return string_hash_nocase(string.c_str()); - } + typedef hash_t hash_type; + hash_type operator()( const CopiedString& string ) const { + return string_hash_nocase( string.c_str() ); + } }; /// \brief Length of a string in ub4. /// "wibble" (6) gives 2, /// "and" (3) gives 1, /// "bleh" (4) gives 2 -inline std::size_t string_length_ub4(const char* string) -{ - return ((string_length(string)>>2)+1)<<2; +inline std::size_t string_length_ub4( const char* string ){ + return ( ( string_length( string ) >> 2 ) + 1 ) << 2; } /// \brief Hashable key type that stores a string as an array of ub4 - making hashing faster. @@ -361,72 +340,61 @@ inline std::size_t string_length_ub4(const char* string) template class HashKey { - Array m_key; - hash_t m_hash; - - void copy(const HashKey& other) - { - std::copy(other.m_key.begin(), other.m_key.end(), m_key.begin()); - m_hash = other.m_hash; - } - void copy(const char* string) - { - strncpy(reinterpret_cast(m_key.data()), string, m_key.size()); - for(Array::iterator i = m_key.begin(); i != m_key.end(); ++i) - { - *i = UB4Traits::as_ub4(*i); - } - m_hash = hash_ub4(m_key.data(), m_key.size(), ub4_default_traits()); - } - bool equal(const HashKey& other) const - { - return m_hash == other.m_hash && m_key.size() == other.m_key.size() - && std::equal(m_key.begin(), m_key.end(), other.m_key.begin()); - } +Array m_key; +hash_t m_hash; + +void copy( const HashKey& other ){ + std::copy( other.m_key.begin(), other.m_key.end(), m_key.begin() ); + m_hash = other.m_hash; +} +void copy( const char* string ){ + strncpy( reinterpret_cast( m_key.data() ), string, m_key.size() ); + for ( Array::iterator i = m_key.begin(); i != m_key.end(); ++i ) + { + *i = UB4Traits::as_ub4( *i ); + } + m_hash = hash_ub4( m_key.data(), m_key.size(), ub4_default_traits() ); +} +bool equal( const HashKey& other ) const { + return m_hash == other.m_hash && m_key.size() == other.m_key.size() + && std::equal( m_key.begin(), m_key.end(), other.m_key.begin() ); +} public: - HashKey(const HashKey& other) : m_key(other.m_key.size()) - { - copy(other); - } - HashKey(const char* string) : m_key(string_length_ub4(string)) - { - copy(string); - } - HashKey& operator=(const char* string) - { - m_key.resize(string_length_ub4(string)); - copy(string); - return *this; - } - bool operator==(const HashKey& other) const - { - return equal(other); - } - bool operator!=(const HashKey& other) const - { - return !equal(other); - } - hash_t hash() const - { - return m_hash; - } +HashKey( const HashKey& other ) : m_key( other.m_key.size() ){ + copy( other ); +} +HashKey( const char* string ) : m_key( string_length_ub4( string ) ){ + copy( string ); +} +HashKey& operator=( const char* string ){ + m_key.resize( string_length_ub4( string ) ); + copy( string ); + return *this; +} +bool operator==( const HashKey& other ) const { + return equal( other ); +} +bool operator!=( const HashKey& other ) const { + return !equal( other ); +} +hash_t hash() const { + return m_hash; +} #if 0 - const char* c_str() const - { - return reinterpret_cast(m_key.data()); - } +const char* c_str() const { + return reinterpret_cast( m_key.data() ); +} #endif }; /// \brief Hash function to use with HashKey. struct HashKeyHasher { - typedef hash_t hash_type; - hash_type operator()(const HashKey& key) const - { - return key.hash(); - } + typedef hash_t hash_type; + hash_type operator()( const HashKey& key ) const { + return key.hash(); + } }; diff --git a/libs/container/hashtable.cpp b/libs/container/hashtable.cpp index e4d02c93..edcaff63 100644 --- a/libs/container/hashtable.cpp +++ b/libs/container/hashtable.cpp @@ -1,65 +1,62 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "hashtable.h" -#if defined(_DEBUG) || defined(DOXYGEN) +#if defined( _DEBUG ) || defined( DOXYGEN ) #include "hashfunc.h" namespace ExampleHashTable { - void testStuff() - { - // HashTable example - typedef HashTable MyHashTable; - MyHashTable hashtable; - hashtable["bleh"] = 5; - hashtable.insert("blah", 17); - hashtable["foo"] = 99; - hashtable.insert("bar", 23); - - int bleh = (*hashtable.find("bleh")).value; // 5 - int blah = hashtable["blah"]; // 17 - hashtable.erase("foo"); - MyHashTable::iterator barIter = hashtable.find("bar"); - hashtable.erase(barIter); - - for(MyHashTable::iterator i = hashtable.begin(); i != hashtable.end(); ++i) - { - if((*i).key != "bleh") - { - ++hashtable["count"]; // insertion does not invalidate iterators - } - } - // end example - } +void testStuff(){ + // HashTable example + typedef HashTable MyHashTable; + MyHashTable hashtable; + hashtable["bleh"] = 5; + hashtable.insert( "blah", 17 ); + hashtable["foo"] = 99; + hashtable.insert( "bar", 23 ); + + int bleh = ( *hashtable.find( "bleh" ) ).value; // 5 + int blah = hashtable["blah"]; // 17 + hashtable.erase( "foo" ); + MyHashTable::iterator barIter = hashtable.find( "bar" ); + hashtable.erase( barIter ); + + for ( MyHashTable::iterator i = hashtable.begin(); i != hashtable.end(); ++i ) + { + if ( ( *i ).key != "bleh" ) { + ++hashtable["count"]; // insertion does not invalidate iterators + } + } + // end example +} - struct Always - { - Always() - { - testStuff(); - } - } always; +struct Always +{ + Always(){ + testStuff(); + } +} always; } #endif diff --git a/libs/container/hashtable.h b/libs/container/hashtable.h index 88d672cf..2c5677ce 100644 --- a/libs/container/hashtable.h +++ b/libs/container/hashtable.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_HASHTABLE_H) +#if !defined( INCLUDED_CONTAINER_HASHTABLE_H ) #define INCLUDED_CONTAINER_HASHTABLE_H #include @@ -30,151 +30,131 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA namespace HashTableDetail { - inline std::size_t next_power_of_two(std::size_t size) - { - std::size_t result = 1; - while(result < size) - { - result <<= 1; - } - return result; - } - - struct BucketNodeBase - { - BucketNodeBase* next; - BucketNodeBase* prev; - }; - - inline void list_initialise(BucketNodeBase& self) - { - self.next = self.prev = &self; - } - - inline void list_swap(BucketNodeBase& self, BucketNodeBase& other) - { - BucketNodeBase tmp(self); - if(other.next == &other) - { - list_initialise(self); - } - else - { - self = other; - self.next->prev = self.prev->next = &self; - } - if(tmp.next == &self) - { - list_initialise(other); - } - else - { - other = tmp; - other.next->prev = other.prev->next = &other; - } - } - - inline void node_link(BucketNodeBase* node, BucketNodeBase* next) - { - node->next = next; - node->prev = next->prev; - next->prev = node; - node->prev->next = node; - } - inline void node_unlink(BucketNodeBase* node) - { - node->prev->next = node->next; - node->next->prev = node->prev; - } - - template - struct KeyValue - { - const Key key; - Value value; - - KeyValue(const Key& key_, const Value& value_) - : key(key_), value(value_) - { - } - }; - - template - struct BucketNode : public BucketNodeBase - { - Hash m_hash; - KeyValue m_value; - - BucketNode(Hash hash, const Key& key, const Value& value) - : m_hash(hash), m_value(key, value) - { - } - BucketNode* getNext() const - { - return static_cast(next); - } - BucketNode* getPrev() const - { - return static_cast(prev); - } - }; - - template - class BucketIterator - { - typedef BucketNode Node; - Node* m_node; - - void increment() - { - m_node = m_node->getNext(); - } - - public: - typedef std::forward_iterator_tag iterator_category; - typedef std::ptrdiff_t difference_type; - typedef difference_type distance_type; - typedef KeyValue value_type; - typedef value_type* pointer; - typedef value_type& reference; - - BucketIterator(Node* node) : m_node(node) - { - } - - Node* node() - { - return m_node; - } - - bool operator==(const BucketIterator& other) const - { - return m_node == other.m_node; - } - bool operator!=(const BucketIterator& other) const - { - return !operator==(other); - } - BucketIterator& operator++() - { - increment(); - return *this; - } - BucketIterator operator++(int) - { - BucketIterator tmp = *this; - increment(); - return tmp; - } - value_type& operator*() const - { - return m_node->m_value; - } - value_type* operator->() const - { - return &(operator*()); - } - }; +inline std::size_t next_power_of_two( std::size_t size ){ + std::size_t result = 1; + while ( result < size ) + { + result <<= 1; + } + return result; +} + +struct BucketNodeBase +{ + BucketNodeBase* next; + BucketNodeBase* prev; +}; + +inline void list_initialise( BucketNodeBase& self ){ + self.next = self.prev = &self; +} + +inline void list_swap( BucketNodeBase& self, BucketNodeBase& other ){ + BucketNodeBase tmp( self ); + if ( other.next == &other ) { + list_initialise( self ); + } + else + { + self = other; + self.next->prev = self.prev->next = &self; + } + if ( tmp.next == &self ) { + list_initialise( other ); + } + else + { + other = tmp; + other.next->prev = other.prev->next = &other; + } +} + +inline void node_link( BucketNodeBase* node, BucketNodeBase* next ){ + node->next = next; + node->prev = next->prev; + next->prev = node; + node->prev->next = node; +} +inline void node_unlink( BucketNodeBase* node ){ + node->prev->next = node->next; + node->next->prev = node->prev; +} + +template +struct KeyValue +{ + const Key key; + Value value; + + KeyValue( const Key& key_, const Value& value_ ) + : key( key_ ), value( value_ ){ + } +}; + +template +struct BucketNode : public BucketNodeBase +{ + Hash m_hash; + KeyValue m_value; + + BucketNode( Hash hash, const Key& key, const Value& value ) + : m_hash( hash ), m_value( key, value ){ + } + BucketNode* getNext() const { + return static_cast( next ); + } + BucketNode* getPrev() const { + return static_cast( prev ); + } +}; + +template +class BucketIterator +{ +typedef BucketNode Node; +Node* m_node; + +void increment(){ + m_node = m_node->getNext(); +} + +public: +typedef std::forward_iterator_tag iterator_category; +typedef std::ptrdiff_t difference_type; +typedef difference_type distance_type; +typedef KeyValue value_type; +typedef value_type* pointer; +typedef value_type& reference; + +BucketIterator( Node* node ) : m_node( node ){ +} + +Node* node(){ + return m_node; +} + +bool operator==( const BucketIterator& other ) const { + return m_node == other.m_node; +} +bool operator!=( const BucketIterator& other ) const { + return !operator==( other ); +} +BucketIterator& operator++(){ + increment(); + return *this; +} +BucketIterator operator++( int ){ + BucketIterator tmp = *this; + increment(); + return tmp; +} +value_type& operator*() const { + return m_node->m_value; +} +value_type* operator->() const { + return &( operator*() ); +} +}; } @@ -195,280 +175,236 @@ namespace HashTableDetail template > class HashTable : private KeyEqual, private Hasher { - typedef typename Hasher::hash_type hash_type; - typedef HashTableDetail::KeyValue KeyValue; - typedef HashTableDetail::BucketNode BucketNode; - - inline BucketNode* node_create(hash_type hash, const Key& key, const Value& value) - { - return new BucketNode(hash, key, value); - } - inline void node_destroy(BucketNode* node) - { - delete node; - } - - typedef BucketNode* Bucket; - - static Bucket* buckets_new(std::size_t count) - { - Bucket* buckets = new Bucket[count]; - std::uninitialized_fill(buckets, buckets + count, Bucket(0)); - return buckets; - } - static void buckets_delete(Bucket* buckets) - { - delete[] buckets; - } - - std::size_t m_bucketCount; - Bucket* m_buckets; - std::size_t m_size; - HashTableDetail::BucketNodeBase m_list; - - BucketNode* getFirst() - { - return static_cast(m_list.next); - } - BucketNode* getLast() - { - return static_cast(&m_list); - } +typedef typename Hasher::hash_type hash_type; +typedef HashTableDetail::KeyValue KeyValue; +typedef HashTableDetail::BucketNode BucketNode; + +inline BucketNode* node_create( hash_type hash, const Key& key, const Value& value ){ + return new BucketNode( hash, key, value ); +} +inline void node_destroy( BucketNode* node ){ + delete node; +} + +typedef BucketNode* Bucket; + +static Bucket* buckets_new( std::size_t count ){ + Bucket* buckets = new Bucket[count]; + std::uninitialized_fill( buckets, buckets + count, Bucket( 0 ) ); + return buckets; +} +static void buckets_delete( Bucket* buckets ){ + delete[] buckets; +} + +std::size_t m_bucketCount; +Bucket* m_buckets; +std::size_t m_size; +HashTableDetail::BucketNodeBase m_list; + +BucketNode* getFirst(){ + return static_cast( m_list.next ); +} +BucketNode* getLast(){ + return static_cast( &m_list ); +} public: - typedef KeyValue value_type; - typedef HashTableDetail::BucketIterator iterator; +typedef KeyValue value_type; +typedef HashTableDetail::BucketIterator iterator; private: - void initialise() - { - list_initialise(m_list); - } - hash_type hashKey(const Key& key) - { - return Hasher::operator()(key); - } - - std::size_t getBucketId(hash_type hash) const - { - return hash & (m_bucketCount - 1); - } - Bucket& getBucket(hash_type hash) - { - return m_buckets[getBucketId(hash)]; - } - BucketNode* bucket_find(Bucket bucket, hash_type hash, const Key& key) - { - std::size_t bucketId = getBucketId(hash); - for(iterator i(bucket); i != end(); ++i) - { - hash_type nodeHash = i.node()->m_hash; - - if(getBucketId(nodeHash) != bucketId) - { - return 0; - } - - if(nodeHash == hash && KeyEqual::operator()((*i).key, key)) - { - return i.node(); - } - } - return 0; - } - BucketNode* bucket_insert(Bucket& bucket, BucketNode* node) - { - // link node into list - node_link(node, bucket_next(bucket)); - bucket = node; - return node; - } - BucketNode* bucket_next(Bucket& bucket) - { - Bucket* end = m_buckets + m_bucketCount; - for(Bucket* i = &bucket; i != end; ++i) - { - if(*i != 0) - { - return *i; - } - } - return getLast(); - } - - void buckets_resize(std::size_t count) - { - BucketNode* first = getFirst(); - BucketNode* last = getLast(); - - buckets_delete(m_buckets); - - m_bucketCount = count; - - m_buckets = buckets_new(m_bucketCount); - initialise(); - - for(BucketNode* i = first; i != last;) - { - BucketNode* node = i; - i = i->getNext(); - bucket_insert(getBucket((*node).m_hash), node); - } - } - void size_increment() - { - if(m_size == m_bucketCount) - { - buckets_resize(m_bucketCount == 0 ? 8 : m_bucketCount << 1); - } - ++m_size; - } - void size_decrement() - { - --m_size; - } - - HashTable(const HashTable& other); - HashTable& operator=(const HashTable& other); +void initialise(){ + list_initialise( m_list ); +} +hash_type hashKey( const Key& key ){ + return Hasher::operator()( key ); +} + +std::size_t getBucketId( hash_type hash ) const { + return hash & ( m_bucketCount - 1 ); +} +Bucket& getBucket( hash_type hash ){ + return m_buckets[getBucketId( hash )]; +} +BucketNode* bucket_find( Bucket bucket, hash_type hash, const Key& key ){ + std::size_t bucketId = getBucketId( hash ); + for ( iterator i( bucket ); i != end(); ++i ) + { + hash_type nodeHash = i.node()->m_hash; + + if ( getBucketId( nodeHash ) != bucketId ) { + return 0; + } + + if ( nodeHash == hash && KeyEqual::operator()( ( *i ).key, key ) ) { + return i.node(); + } + } + return 0; +} +BucketNode* bucket_insert( Bucket& bucket, BucketNode* node ){ + // link node into list + node_link( node, bucket_next( bucket ) ); + bucket = node; + return node; +} +BucketNode* bucket_next( Bucket& bucket ){ + Bucket* end = m_buckets + m_bucketCount; + for ( Bucket* i = &bucket; i != end; ++i ) + { + if ( *i != 0 ) { + return *i; + } + } + return getLast(); +} + +void buckets_resize( std::size_t count ){ + BucketNode* first = getFirst(); + BucketNode* last = getLast(); + + buckets_delete( m_buckets ); + + m_bucketCount = count; + + m_buckets = buckets_new( m_bucketCount ); + initialise(); + + for ( BucketNode* i = first; i != last; ) + { + BucketNode* node = i; + i = i->getNext(); + bucket_insert( getBucket( ( *node ).m_hash ), node ); + } +} +void size_increment(){ + if ( m_size == m_bucketCount ) { + buckets_resize( m_bucketCount == 0 ? 8 : m_bucketCount << 1 ); + } + ++m_size; +} +void size_decrement(){ + --m_size; +} + +HashTable( const HashTable& other ); +HashTable& operator=( const HashTable& other ); public: - HashTable() : m_bucketCount(0), m_buckets(0), m_size(0) - { - initialise(); - } - HashTable(std::size_t bucketCount) : m_bucketCount(HashTableDetail::next_power_of_two(bucketCount)), m_buckets(buckets_new(m_bucketCount)), m_size(0) - { - initialise(); - } - ~HashTable() - { - for(BucketNode* i = getFirst(); i != getLast();) - { - BucketNode* node = i; - i = i->getNext(); - node_destroy(node); - } - buckets_delete(m_buckets); - } - - iterator begin() - { - return iterator(getFirst()); - } - iterator end() - { - return iterator(getLast()); - } - - bool empty() const - { - return m_size == 0; - } - std::size_t size() const - { - return m_size; - } - - /// \brief Returns an iterator pointing to the value associated with \p key if it is contained by the hash-table, else \c end(). - iterator find(const Key& key) - { - hash_type hash = hashKey(key); - if(m_bucketCount != 0) - { - Bucket bucket = getBucket(hash); - if(bucket != 0) - { - BucketNode* node = bucket_find(bucket, hash, key); - if(node != 0) - { - return iterator(node); - } - } - } - - return end(); - } - /// \brief Adds \p value to the hash-table associated with \p key if it does not exist. - iterator insert(const Key& key, const Value& value) - { - hash_type hash = hashKey(key); - if(m_bucketCount != 0) - { - Bucket& bucket = getBucket(hash); - if(bucket != 0) - { - BucketNode* node = bucket_find(bucket, hash, key); - if(node != 0) - { - return iterator(node); - } - } - } - - size_increment(); - return iterator(bucket_insert(getBucket(hash), node_create(hash, key, value))); - } - - /// \brief Removes the value pointed to by \p i from the hash-table. - /// - /// \p i must be a deferenceable iterator into the hash-table. - void erase(iterator i) - { - Bucket& bucket = getBucket(i.node()->m_hash); - BucketNode* node = i.node(); - - // if this was the last node in the bucket - if(bucket == node) - { - bucket = (node->getNext() == getLast() || &getBucket(node->getNext()->m_hash) != &bucket) ? 0 : node->getNext(); - } - - node_unlink(node); - ASSERT_MESSAGE(node != 0, "tried to erase a non-existent key/value"); - node_destroy(node); - - size_decrement(); - } - - /// \brief Returns the value identified by \p key if it is contained by the hash-table, else inserts and returns a new default-constructed value associated with \p key. - Value& operator[](const Key& key) - { - hash_type hash = hashKey(key); - if(m_bucketCount != 0) - { - Bucket& bucket = getBucket(hash); - if(bucket != 0) - { - BucketNode* node = bucket_find(bucket, hash, key); - if(node != 0) - { - return node->m_value.value; - } - } - } - size_increment(); - return bucket_insert(getBucket(hash), node_create(hash, key, Value()))->m_value.value; - } - /// \brief Removes the value associated with \p key from the hash-table. - void erase(const Key& key) - { - erase(find(key)); - } - /// \brief Swaps the contents of the hash-table with \p other. - void swap(HashTable& other) - { - std::swap(m_buckets, other.m_buckets); - std::swap(m_bucketCount, other.m_bucketCount); - std::swap(m_size, other.m_size); - HashTableDetail::list_swap(m_list, other.m_list); - } - /// \brief Removes all values from the hash-table. - void clear() - { - HashTable tmp; - tmp.swap(*this); - } +HashTable() : m_bucketCount( 0 ), m_buckets( 0 ), m_size( 0 ){ + initialise(); +} +HashTable( std::size_t bucketCount ) : m_bucketCount( HashTableDetail::next_power_of_two( bucketCount ) ), m_buckets( buckets_new( m_bucketCount ) ), m_size( 0 ){ + initialise(); +} +~HashTable(){ + for ( BucketNode* i = getFirst(); i != getLast(); ) + { + BucketNode* node = i; + i = i->getNext(); + node_destroy( node ); + } + buckets_delete( m_buckets ); +} + +iterator begin(){ + return iterator( getFirst() ); +} +iterator end(){ + return iterator( getLast() ); +} + +bool empty() const { + return m_size == 0; +} +std::size_t size() const { + return m_size; +} + +/// \brief Returns an iterator pointing to the value associated with \p key if it is contained by the hash-table, else \c end(). +iterator find( const Key& key ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return iterator( node ); + } + } + } + + return end(); +} +/// \brief Adds \p value to the hash-table associated with \p key if it does not exist. +iterator insert( const Key& key, const Value& value ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket& bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return iterator( node ); + } + } + } + + size_increment(); + return iterator( bucket_insert( getBucket( hash ), node_create( hash, key, value ) ) ); +} + +/// \brief Removes the value pointed to by \p i from the hash-table. +/// +/// \p i must be a deferenceable iterator into the hash-table. +void erase( iterator i ){ + Bucket& bucket = getBucket( i.node()->m_hash ); + BucketNode* node = i.node(); + + // if this was the last node in the bucket + if ( bucket == node ) { + bucket = ( node->getNext() == getLast() || &getBucket( node->getNext()->m_hash ) != &bucket ) ? 0 : node->getNext(); + } + + node_unlink( node ); + ASSERT_MESSAGE( node != 0, "tried to erase a non-existent key/value" ); + node_destroy( node ); + + size_decrement(); +} + +/// \brief Returns the value identified by \p key if it is contained by the hash-table, else inserts and returns a new default-constructed value associated with \p key. +Value& operator[]( const Key& key ){ + hash_type hash = hashKey( key ); + if ( m_bucketCount != 0 ) { + Bucket& bucket = getBucket( hash ); + if ( bucket != 0 ) { + BucketNode* node = bucket_find( bucket, hash, key ); + if ( node != 0 ) { + return node->m_value.value; + } + } + } + size_increment(); + return bucket_insert( getBucket( hash ), node_create( hash, key, Value() ) )->m_value.value; +} +/// \brief Removes the value associated with \p key from the hash-table. +void erase( const Key& key ){ + erase( find( key ) ); +} +/// \brief Swaps the contents of the hash-table with \p other. +void swap( HashTable& other ){ + std::swap( m_buckets, other.m_buckets ); + std::swap( m_bucketCount, other.m_bucketCount ); + std::swap( m_size, other.m_size ); + HashTableDetail::list_swap( m_list, other.m_list ); +} +/// \brief Removes all values from the hash-table. +void clear(){ + HashTable tmp; + tmp.swap( *this ); +} }; #endif diff --git a/libs/container/stack.cpp b/libs/container/stack.cpp index 3a7c7ce2..81d79b27 100644 --- a/libs/container/stack.cpp +++ b/libs/container/stack.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "stack.h" - diff --git a/libs/container/stack.h b/libs/container/stack.h index d83674c3..10040a74 100644 --- a/libs/container/stack.h +++ b/libs/container/stack.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONTAINER_STACK_H) +#if !defined( INCLUDED_CONTAINER_STACK_H ) #define INCLUDED_CONTAINER_STACK_H #include "memory/allocator.h" @@ -36,204 +36,176 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class Stack : public DefaultAllocator { - typedef DefaultAllocator Allocator; +typedef DefaultAllocator Allocator; - enum - { - DEFAULT_CAPACITY = 4, - }; +enum +{ + DEFAULT_CAPACITY = 4, +}; - typedef Type* pointer; - typedef const Type* const_pointer; +typedef Type* pointer; +typedef const Type* const_pointer; public: - typedef const_pointer const_iterator; +typedef const_pointer const_iterator; private: - pointer m_data; - pointer m_end; - std::size_t m_capacity; - - - void insert(const Type& value) - { - Allocator::construct(m_end++, value); - } - void insert_overflow(const Type& value) - { - const std::size_t new_capacity = (m_capacity) ? m_capacity + m_capacity : std::size_t(DEFAULT_CAPACITY); - const pointer new_data = Allocator::allocate(new_capacity); - const pointer new_end = std::copy(m_data, m_end, new_data); - - destroy(); - Allocator::deallocate(m_data, m_capacity); - - m_capacity = new_capacity; - m_data = new_data; - m_end = new_end; - insert(value); - } - void destroy() - { - for(pointer p = m_data; p != m_end; ++p) - { - Allocator::destroy(p); - } - } - void construct(const Stack& other) - { - pointer p = m_data; - for(const_iterator i = other.begin(); i != other.end(); ++i) - { - Allocator::construct(p++, *i); - } - } +pointer m_data; +pointer m_end; +std::size_t m_capacity; + + +void insert( const Type& value ){ + Allocator::construct( m_end++, value ); +} +void insert_overflow( const Type& value ){ + const std::size_t new_capacity = ( m_capacity ) ? m_capacity + m_capacity : std::size_t( DEFAULT_CAPACITY ); + const pointer new_data = Allocator::allocate( new_capacity ); + const pointer new_end = std::copy( m_data, m_end, new_data ); + + destroy(); + Allocator::deallocate( m_data, m_capacity ); + + m_capacity = new_capacity; + m_data = new_data; + m_end = new_end; + insert( value ); +} +void destroy(){ + for ( pointer p = m_data; p != m_end; ++p ) + { + Allocator::destroy( p ); + } +} +void construct( const Stack& other ){ + pointer p = m_data; + for ( const_iterator i = other.begin(); i != other.end(); ++i ) + { + Allocator::construct( p++, *i ); + } +} public: - Stack() : - m_data(0), - m_end(0), - m_capacity(0) - { - } - Stack(const Type& value) : - m_data(0), - m_end(0), - m_capacity(0) - { - push(value); - } - Stack(const Stack& other) : - DefaultAllocator(other) - { - m_capacity = other.m_capacity; - m_data = Allocator::allocate(m_capacity); - construct(other); - m_end = m_data + other.size(); - } - ~Stack() - { - destroy(); - Allocator::deallocate(m_data, m_capacity); - } - - const_iterator begin() const - { - return m_data; - } - const_iterator end() const - { - return m_end; - } - - bool empty() const - { - return end() == begin(); - } - void clear() - { - destroy(); - m_end = m_data; - } - - std::size_t size() const - { - return m_end - m_data; - } - Type operator[](const std::size_t i) const - { - return m_data[i]; - } - /// \brief Pushes \p value onto the stack at the top element. If reserved storage is insufficient for the new element, this will invalidate all iterators. - void push(const Type& value) - { - if(size() == m_capacity) - { - insert_overflow(value); - } - else - { - insert(value); - } - } - /// \brief Removes the top element of the stack. - void pop() - { - Allocator::destroy(--m_end); - } - /// \brief Returns the top element of the mutable stack. - Type& top() - { - return *(m_end-1); - } - /// \brief Returns the top element of the non-mutable stack. - const Type& top() const - { - return *(m_end-1); - } - /// \brief Returns the element below the top element of the mutable stack. - Type& parent() - { - return *(m_end-2); - } - /// \brief Returns the element below the top element of the non-mutable stack. - const Type& parent() const - { - return *(m_end-2); - } - /// \brief Swaps the values of this stack and \p other. - void swap(Stack& other) - { - std::swap(m_data, other.m_data); - std::swap(m_end, other.m_end); - std::swap(m_capacity, other.m_capacity); - } +Stack() : + m_data( 0 ), + m_end( 0 ), + m_capacity( 0 ){ +} +Stack( const Type& value ) : + m_data( 0 ), + m_end( 0 ), + m_capacity( 0 ){ + push( value ); +} +Stack( const Stack& other ) : + DefaultAllocator( other ){ + m_capacity = other.m_capacity; + m_data = Allocator::allocate( m_capacity ); + construct( other ); + m_end = m_data + other.size(); +} +~Stack(){ + destroy(); + Allocator::deallocate( m_data, m_capacity ); +} + +const_iterator begin() const { + return m_data; +} +const_iterator end() const { + return m_end; +} + +bool empty() const { + return end() == begin(); +} +void clear(){ + destroy(); + m_end = m_data; +} + +std::size_t size() const { + return m_end - m_data; +} +Type operator[]( const std::size_t i ) const { + return m_data[i]; +} +/// \brief Pushes \p value onto the stack at the top element. If reserved storage is insufficient for the new element, this will invalidate all iterators. +void push( const Type& value ){ + if ( size() == m_capacity ) { + insert_overflow( value ); + } + else + { + insert( value ); + } +} +/// \brief Removes the top element of the stack. +void pop(){ + Allocator::destroy( --m_end ); +} +/// \brief Returns the top element of the mutable stack. +Type& top(){ + return *( m_end - 1 ); +} +/// \brief Returns the top element of the non-mutable stack. +const Type& top() const { + return *( m_end - 1 ); +} +/// \brief Returns the element below the top element of the mutable stack. +Type& parent(){ + return *( m_end - 2 ); +} +/// \brief Returns the element below the top element of the non-mutable stack. +const Type& parent() const { + return *( m_end - 2 ); +} +/// \brief Swaps the values of this stack and \p other. +void swap( Stack& other ){ + std::swap( m_data, other.m_data ); + std::swap( m_end, other.m_end ); + std::swap( m_capacity, other.m_capacity ); +} #if 1 // use copy-swap technique - Stack& operator=(const Stack& other) - { - Stack temp(other); - temp.swap(*this); - return *this; - } +Stack& operator=( const Stack& other ){ + Stack temp( other ); + temp.swap( *this ); + return *this; +} #else // avoids memory allocation if capacity is already sufficient. - Stack& operator=(const Stack& other) - { - if(&other != this) - { - destroy(); - - if(other.size() > m_capacity) - { - Allocator::deallocate(m_data, m_capacity); - m_capacity = other.m_capacity; - m_data = Allocator::allocate(m_capacity); - } - m_end = m_data + other.size(); - - construct(other); - } - return *this; - } +Stack& operator=( const Stack& other ){ + if ( &other != this ) { + destroy(); + + if ( other.size() > m_capacity ) { + Allocator::deallocate( m_data, m_capacity ); + m_capacity = other.m_capacity; + m_data = Allocator::allocate( m_capacity ); + } + m_end = m_data + other.size(); + + construct( other ); + } + return *this; +} #endif }; /// \brief Returns true if \p self is lexicographically less than \p other. template -inline bool operator<(const Stack& self, const Stack& other) -{ - return std::lexicographical_compare(self.begin(), self.end(), other.begin(), other.end()); +inline bool operator<( const Stack& self, const Stack& other ){ + return std::lexicographical_compare( self.begin(), self.end(), other.begin(), other.end() ); } namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap(). - template - inline void swap(Stack& self, Stack& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap(). +template +inline void swap( Stack& self, Stack& other ){ + self.swap( other ); +} } #endif diff --git a/libs/convert.cpp b/libs/convert.cpp index 0e73aef7..c87038f5 100644 --- a/libs/convert.cpp +++ b/libs/convert.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "convert.h" - diff --git a/libs/convert.h b/libs/convert.h index f7f4f992..b6fe93cc 100644 --- a/libs/convert.h +++ b/libs/convert.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_CONVERT_H) +#if !defined( INCLUDED_CONVERT_H ) #define INCLUDED_CONVERT_H /// \file @@ -33,58 +33,48 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "character.h" /// \brief Returns the number of bytes required to represent \p character in UTF-8 encoding. -inline std::size_t utf8_character_length(const char* character) -{ - if((*character & 0xE0) == 0xC0) // 110xxxxx - { - return 2; - } - else if((*character & 0xF0) == 0xE0) // 1110xxxx - { - return 3; - } - else if((*character & 0xF8) == 0xF0) // 11110xxx - { - return 4; - } - else if((*character & 0xFC) == 0xF8) // 111110xx - { - return 5; - } - else if((*character & 0xFE) == 0xFC) // 1111110x - { - return 6; - } - ERROR_MESSAGE(""); - return 0; +inline std::size_t utf8_character_length( const char* character ){ + if ( ( *character & 0xE0 ) == 0xC0 ) { // 110xxxxx + return 2; + } + else if ( ( *character & 0xF0 ) == 0xE0 ) { // 1110xxxx + return 3; + } + else if ( ( *character & 0xF8 ) == 0xF0 ) { // 11110xxx + return 4; + } + else if ( ( *character & 0xFC ) == 0xF8 ) { // 111110xx + return 5; + } + else if ( ( *character & 0xFE ) == 0xFC ) { // 1111110x + return 6; + } + ERROR_MESSAGE( "" ); + return 0; } struct UTF8Character { - const char* buffer; - std::size_t length; - UTF8Character() : buffer(0), length(0) - { - } - UTF8Character(const char* bytes) : buffer(bytes), length(utf8_character_length(bytes)) - { - } + const char* buffer; + std::size_t length; + UTF8Character() : buffer( 0 ), length( 0 ){ + } + UTF8Character( const char* bytes ) : buffer( bytes ), length( utf8_character_length( bytes ) ){ + } }; -inline bool operator<(const UTF8Character& self, const UTF8Character& other) -{ - return std::lexicographical_compare(self.buffer, self.buffer + self.length, other.buffer, other.buffer + other.length); +inline bool operator<( const UTF8Character& self, const UTF8Character& other ){ + return std::lexicographical_compare( self.buffer, self.buffer + self.length, other.buffer, other.buffer + other.length ); } /// \brief Writes \p c to \p ostream in Hex form. Useful for debugging. template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const UTF8Character& c) -{ - for(const char* p = c.buffer; p != c.buffer + c.length; ++p) - { - ostream << HexChar(*p); - } - return ostream; +inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const UTF8Character& c ){ + for ( const char* p = c.buffer; p != c.buffer + c.length; ++p ) + { + ostream << HexChar( *p ); + } + return ostream; } @@ -94,60 +84,50 @@ inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const /// Obtain the global instance with globalCharacterSet(). class CharacterSet { - const char* m_charSet; +const char* m_charSet; public: - CharacterSet() - { - if(g_get_charset(&m_charSet) != FALSE) - { - m_charSet = 0; - } - } - bool isUTF8() const - { - return m_charSet == 0; - } - const char* get() const - { - return m_charSet; - } +CharacterSet(){ + if ( g_get_charset( &m_charSet ) != FALSE ) { + m_charSet = 0; + } +} +bool isUTF8() const { + return m_charSet == 0; +} +const char* get() const { + return m_charSet; +} }; typedef LazyStatic GlobalCharacterSet; /// \brief Returns the global instance of CharacterSet. -inline CharacterSet& globalCharacterSet() -{ - return GlobalCharacterSet::instance(); +inline CharacterSet& globalCharacterSet(){ + return GlobalCharacterSet::instance(); } class UTF8CharacterToExtendedASCII { public: - UTF8Character m_utf8; - char m_c; - UTF8CharacterToExtendedASCII() : m_c('\0') - { - } - UTF8CharacterToExtendedASCII(const UTF8Character& utf8, char c) : m_utf8(utf8), m_c(c) - { - } +UTF8Character m_utf8; +char m_c; +UTF8CharacterToExtendedASCII() : m_c( '\0' ){ +} +UTF8CharacterToExtendedASCII( const UTF8Character& utf8, char c ) : m_utf8( utf8 ), m_c( c ){ +} }; -inline bool operator<(const UTF8CharacterToExtendedASCII& self, const UTF8CharacterToExtendedASCII& other) -{ - return self.m_utf8 < other.m_utf8; +inline bool operator<( const UTF8CharacterToExtendedASCII& self, const UTF8CharacterToExtendedASCII& other ){ + return self.m_utf8 < other.m_utf8; } -inline std::size_t extended_ascii_to_index(char c) -{ - return static_cast(c & 0x7F); +inline std::size_t extended_ascii_to_index( char c ){ + return static_cast( c & 0x7F ); } -inline char extended_ascii_for_index(std::size_t i) -{ - return static_cast(i | 0x80); +inline char extended_ascii_for_index( std::size_t i ){ + return static_cast( i | 0x80 ); } /// \brief The active extended-ascii character set encoding. @@ -156,149 +136,131 @@ inline char extended_ascii_for_index(std::size_t i) /// Obtain the global instance with globalExtendedASCIICharacterSet(). class ExtendedASCIICharacterSet { - typedef char UTF8CharBuffer[6]; - UTF8CharBuffer m_converted[128]; - UTF8Character m_decodeMap[128]; - UTF8CharacterToExtendedASCII m_encodeMap[128]; +typedef char UTF8CharBuffer[6]; +UTF8CharBuffer m_converted[128]; +UTF8Character m_decodeMap[128]; +UTF8CharacterToExtendedASCII m_encodeMap[128]; public: - ExtendedASCIICharacterSet() - { - if(!globalCharacterSet().isUTF8()) - { - GIConv descriptor = g_iconv_open("UTF-8", globalCharacterSet().get()); - for(std::size_t i = 1; i < 128; ++i) - { - char c = extended_ascii_for_index(i); - char* inbuf = &c; - std::size_t inbytesleft = 1; - char* outbuf = m_converted[i]; - std::size_t outbytesleft = 6; - if(g_iconv(descriptor, &inbuf, &inbytesleft, &outbuf, &outbytesleft) != (size_t)(-1)) - { - UTF8Character utf8(m_converted[i]); - m_decodeMap[i] = utf8; - m_encodeMap[i] = UTF8CharacterToExtendedASCII(utf8, c); - } - } - g_iconv_close(descriptor); - std::sort(m_encodeMap, m_encodeMap + 128); - } - } - /// \brief Prints the (up to) 128 characters in the current extended-ascii character set. - /// Useful for debugging. - void print() const - { - globalOutputStream() << "UTF-8 conversion required from charset: " << globalCharacterSet().get() << "\n"; - for(std::size_t i = 1; i < 128; ++i) - { - if(m_decodeMap[i].buffer != 0) - { - globalOutputStream() << extended_ascii_for_index(i) << " = " << m_decodeMap[i] << "\n"; - } - } - } - /// \brief Returns \p c decoded from extended-ascii to UTF-8. - /// \p c must be an extended-ascii character. - const UTF8Character& decode(char c) const - { - ASSERT_MESSAGE(!globalCharacterSet().isUTF8(), "locale is utf8, no conversion required"); - ASSERT_MESSAGE(!char_is_ascii(c), "decode: ascii character"); - ASSERT_MESSAGE(m_decodeMap[extended_ascii_to_index(c)].buffer != 0, "decode: invalid character: " << HexChar(c)); - return m_decodeMap[extended_ascii_to_index(c)]; - } - /// \brief Returns \p c encoded to extended-ascii from UTF-8. - /// \p c must map to an extended-ascii character. - char encode(const UTF8Character& c) const - { - ASSERT_MESSAGE(!globalCharacterSet().isUTF8(), "locale is utf8, no conversion required"); - ASSERT_MESSAGE(!char_is_ascii(*c.buffer), "encode: ascii character"); - std::pair range - = std::equal_range(m_encodeMap, m_encodeMap + 128, UTF8CharacterToExtendedASCII(c, 0)); - ASSERT_MESSAGE(range.first != range.second, "encode: invalid character: " << c); - return (*range.first).m_c; - } +ExtendedASCIICharacterSet(){ + if ( !globalCharacterSet().isUTF8() ) { + GIConv descriptor = g_iconv_open( "UTF-8", globalCharacterSet().get() ); + for ( std::size_t i = 1; i < 128; ++i ) + { + char c = extended_ascii_for_index( i ); + char* inbuf = &c; + std::size_t inbytesleft = 1; + char* outbuf = m_converted[i]; + std::size_t outbytesleft = 6; + if ( g_iconv( descriptor, &inbuf, &inbytesleft, &outbuf, &outbytesleft ) != (size_t)( -1 ) ) { + UTF8Character utf8( m_converted[i] ); + m_decodeMap[i] = utf8; + m_encodeMap[i] = UTF8CharacterToExtendedASCII( utf8, c ); + } + } + g_iconv_close( descriptor ); + std::sort( m_encodeMap, m_encodeMap + 128 ); + } +} +/// \brief Prints the (up to) 128 characters in the current extended-ascii character set. +/// Useful for debugging. +void print() const { + globalOutputStream() << "UTF-8 conversion required from charset: " << globalCharacterSet().get() << "\n"; + for ( std::size_t i = 1; i < 128; ++i ) + { + if ( m_decodeMap[i].buffer != 0 ) { + globalOutputStream() << extended_ascii_for_index( i ) << " = " << m_decodeMap[i] << "\n"; + } + } +} +/// \brief Returns \p c decoded from extended-ascii to UTF-8. +/// \p c must be an extended-ascii character. +const UTF8Character& decode( char c ) const { + ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); + ASSERT_MESSAGE( !char_is_ascii( c ), "decode: ascii character" ); + ASSERT_MESSAGE( m_decodeMap[extended_ascii_to_index( c )].buffer != 0, "decode: invalid character: " << HexChar( c ) ); + return m_decodeMap[extended_ascii_to_index( c )]; +} +/// \brief Returns \p c encoded to extended-ascii from UTF-8. +/// \p c must map to an extended-ascii character. +char encode( const UTF8Character& c ) const { + ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); + ASSERT_MESSAGE( !char_is_ascii( *c.buffer ), "encode: ascii character" ); + std::pair range + = std::equal_range( m_encodeMap, m_encodeMap + 128, UTF8CharacterToExtendedASCII( c, 0 ) ); + ASSERT_MESSAGE( range.first != range.second, "encode: invalid character: " << c ); + return ( *range.first ).m_c; +} }; typedef LazyStatic GlobalExtendedASCIICharacterSet; /// \brief Returns the global instance of ExtendedASCIICharacterSet. -inline ExtendedASCIICharacterSet& globalExtendedASCIICharacterSet() -{ - return GlobalExtendedASCIICharacterSet::instance(); +inline ExtendedASCIICharacterSet& globalExtendedASCIICharacterSet(){ + return GlobalExtendedASCIICharacterSet::instance(); } class ConvertUTF8ToLocale { public: - StringRange m_range; - ConvertUTF8ToLocale(const char* string) : m_range(StringRange(string, string + strlen(string))) - { - } - ConvertUTF8ToLocale(const StringRange& range) : m_range(range) - { - } +StringRange m_range; +ConvertUTF8ToLocale( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ +} +ConvertUTF8ToLocale( const StringRange& range ) : m_range( range ){ +} }; /// \brief Writes \p convert to \p ostream after encoding each character to extended-ascii from UTF-8. template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const ConvertUTF8ToLocale& convert) -{ - if(globalCharacterSet().isUTF8()) - { - return ostream << convert.m_range; - } - - for(const char* p = convert.m_range.first; p != convert.m_range.last;) - { - if(!char_is_ascii(*p)) - { - UTF8Character c(p); - ostream << globalExtendedASCIICharacterSet().encode(c); - p += c.length; - } - else - { - ostream << *p++; - } - } - return ostream; +inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const ConvertUTF8ToLocale& convert ){ + if ( globalCharacterSet().isUTF8() ) { + return ostream << convert.m_range; + } + + for ( const char* p = convert.m_range.first; p != convert.m_range.last; ) + { + if ( !char_is_ascii( *p ) ) { + UTF8Character c( p ); + ostream << globalExtendedASCIICharacterSet().encode( c ); + p += c.length; + } + else + { + ostream << *p++; + } + } + return ostream; } class ConvertLocaleToUTF8 { public: - StringRange m_range; - ConvertLocaleToUTF8(const char* string) : m_range(StringRange(string, string + strlen(string))) - { - } - ConvertLocaleToUTF8(const StringRange& range) : m_range(range) - { - } +StringRange m_range; +ConvertLocaleToUTF8( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ +} +ConvertLocaleToUTF8( const StringRange& range ) : m_range( range ){ +} }; /// \brief Writes \p convert to \p ostream after decoding each character from extended-ascii to UTF-8. template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const ConvertLocaleToUTF8& convert) -{ - if(globalCharacterSet().isUTF8()) - { - return ostream << convert.m_range; - } - - for(const char* p = convert.m_range.first; p != convert.m_range.last; ++p) - { - if(!char_is_ascii(*p)) - { - UTF8Character c(globalExtendedASCIICharacterSet().decode(*p)); - ostream.write(c.buffer, c.length); - } - else - { - ostream << *p; - } - } - return ostream; +inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const ConvertLocaleToUTF8& convert ){ + if ( globalCharacterSet().isUTF8() ) { + return ostream << convert.m_range; + } + + for ( const char* p = convert.m_range.first; p != convert.m_range.last; ++p ) + { + if ( !char_is_ascii( *p ) ) { + UTF8Character c( globalExtendedASCIICharacterSet().decode( *p ) ); + ostream.write( c.buffer, c.length ); + } + else + { + ostream << *p; + } + } + return ostream; } diff --git a/libs/ddslib.h b/libs/ddslib.h index 3f5f124c..4961f6ef 100644 --- a/libs/ddslib.h +++ b/libs/ddslib.h @@ -1,39 +1,39 @@ /* ----------------------------------------------------------------------------- -DDS Library + DDS Library -Based on code from Nvidia's DDS example: -http://www.nvidia.com/object/dxtc_decompression_code.html + Based on code from Nvidia's DDS example: + http://www.nvidia.com/object/dxtc_decompression_code.html -Copyright (c) 2003 Randy Reddig -All rights reserved. + Copyright (c) 2003 Randy Reddig + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -72,86 +72,86 @@ ddsPF_t; /* 16bpp stuff */ -#define DDS_LOW_5 0x001F; -#define DDS_MID_6 0x07E0; -#define DDS_HIGH_5 0xF800; -#define DDS_MID_555 0x03E0; -#define DDS_HI_555 0x7C00; +#define DDS_LOW_5 0x001F; +#define DDS_MID_6 0x07E0; +#define DDS_HIGH_5 0xF800; +#define DDS_MID_555 0x03E0; +#define DDS_HI_555 0x7C00; /* structures */ typedef struct ddsColorKey_s { - unsigned int colorSpaceLowValue; - unsigned int colorSpaceHighValue; -} + unsigned int colorSpaceLowValue; + unsigned int colorSpaceHighValue; +} ddsColorKey_t; typedef struct ddsCaps_s { - unsigned int caps1; - unsigned int caps2; - unsigned int caps3; - unsigned int caps4; -} + unsigned int caps1; + unsigned int caps2; + unsigned int caps3; + unsigned int caps4; +} ddsCaps_t; typedef struct ddsMultiSampleCaps_s { - unsigned short flipMSTypes; - unsigned short bltMSTypes; + unsigned short flipMSTypes; + unsigned short bltMSTypes; } ddsMultiSampleCaps_t; typedef struct ddsPixelFormat_s { - unsigned int size; - unsigned int flags; - unsigned int fourCC; + unsigned int size; + unsigned int flags; + unsigned int fourCC; union { - unsigned int rgbBitCount; - unsigned int yuvBitCount; - unsigned int zBufferBitDepth; - unsigned int alphaBitDepth; - unsigned int luminanceBitCount; - unsigned int bumpBitCount; - unsigned int privateFormatBitCount; + unsigned int rgbBitCount; + unsigned int yuvBitCount; + unsigned int zBufferBitDepth; + unsigned int alphaBitDepth; + unsigned int luminanceBitCount; + unsigned int bumpBitCount; + unsigned int privateFormatBitCount; }; union { - unsigned int rBitMask; - unsigned int yBitMask; - unsigned int stencilBitDepth; - unsigned int luminanceBitMask; - unsigned int bumpDuBitMask; - unsigned int operations; + unsigned int rBitMask; + unsigned int yBitMask; + unsigned int stencilBitDepth; + unsigned int luminanceBitMask; + unsigned int bumpDuBitMask; + unsigned int operations; }; union { - unsigned int gBitMask; - unsigned int uBitMask; - unsigned int zBitMask; - unsigned int bumpDvBitMask; - ddsMultiSampleCaps_t multiSampleCaps; + unsigned int gBitMask; + unsigned int uBitMask; + unsigned int zBitMask; + unsigned int bumpDvBitMask; + ddsMultiSampleCaps_t multiSampleCaps; }; union { - unsigned int bBitMask; - unsigned int vBitMask; - unsigned int stencilBitMask; - unsigned int bumpLuminanceBitMask; + unsigned int bBitMask; + unsigned int vBitMask; + unsigned int stencilBitMask; + unsigned int bumpLuminanceBitMask; }; union { - unsigned int rgbAlphaBitMask; - unsigned int yuvAlphaBitMask; - unsigned int luminanceAlphaBitMask; - unsigned int rgbZBitMask; - unsigned int yuvZBitMask; + unsigned int rgbAlphaBitMask; + unsigned int yuvAlphaBitMask; + unsigned int luminanceAlphaBitMask; + unsigned int rgbZBitMask; + unsigned int yuvZBitMask; }; } ddsPixelFormat_t; @@ -160,85 +160,85 @@ ddsPixelFormat_t; typedef struct ddsBuffer_s { /* magic: 'dds ' */ - char magic[ 4 ]; - + char magic[ 4 ]; + /* directdraw surface */ - unsigned int size; - unsigned int flags; - unsigned int height; - unsigned int width; + unsigned int size; + unsigned int flags; + unsigned int height; + unsigned int width; union { - int pitch; - unsigned int linearSize; + int pitch; + unsigned int linearSize; }; - unsigned int backBufferCount; + unsigned int backBufferCount; union { - unsigned int mipMapCount; - unsigned int refreshRate; - unsigned int srcVBHandle; + unsigned int mipMapCount; + unsigned int refreshRate; + unsigned int srcVBHandle; }; - unsigned int alphaBitDepth; - unsigned int reserved; - void *surface; + unsigned int alphaBitDepth; + unsigned int reserved; + void *surface; union { - ddsColorKey_t ckDestOverlay; - unsigned int emptyFaceColor; + ddsColorKey_t ckDestOverlay; + unsigned int emptyFaceColor; }; - ddsColorKey_t ckDestBlt; - ddsColorKey_t ckSrcOverlay; - ddsColorKey_t ckSrcBlt; + ddsColorKey_t ckDestBlt; + ddsColorKey_t ckSrcOverlay; + ddsColorKey_t ckSrcBlt; union { - ddsPixelFormat_t pixelFormat; - unsigned int fvf; + ddsPixelFormat_t pixelFormat; + unsigned int fvf; }; - ddsCaps_t ddsCaps; - unsigned int textureStage; - + ddsCaps_t ddsCaps; + unsigned int textureStage; + /* data (Varying size) */ - unsigned char data[ 4 ]; + unsigned char data[ 4 ]; } ddsBuffer_t; typedef struct ddsColorBlock_s { - unsigned short colors[ 2 ]; - unsigned char row[ 4 ]; + unsigned short colors[ 2 ]; + unsigned char row[ 4 ]; } ddsColorBlock_t; typedef struct ddsAlphaBlockExplicit_s { - unsigned short row[ 4 ]; + unsigned short row[ 4 ]; } ddsAlphaBlockExplicit_t; typedef struct ddsAlphaBlock3BitLinear_s { - unsigned char alpha0; - unsigned char alpha1; - unsigned char stuff[ 6 ]; + unsigned char alpha0; + unsigned char alpha1; + unsigned char stuff[ 6 ]; } ddsAlphaBlock3BitLinear_t; typedef struct ddsColor_s { - unsigned char r, g, b, a; + unsigned char r, g, b, a; } ddsColor_t; /* public functions */ -int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ); -int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ); +int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ); +int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ); diff --git a/libs/ddslib/ddslib.c b/libs/ddslib/ddslib.c index 424faeea..b60e506b 100644 --- a/libs/ddslib/ddslib.c +++ b/libs/ddslib/ddslib.c @@ -1,39 +1,39 @@ /* ----------------------------------------------------------------------------- -DDS Library + DDS Library -Based on code from Nvidia's DDS example: -http://www.nvidia.com/object/dxtc_decompression_code.html + Based on code from Nvidia's DDS example: + http://www.nvidia.com/object/dxtc_decompression_code.html -Copyright (c) 2003 Randy Reddig -All rights reserved. + Copyright (c) 2003 Randy Reddig + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -50,147 +50,152 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* endian tomfoolery */ typedef union { - float f; - char c[ 4 ]; + float f; + char c[ 4 ]; } floatSwapUnion; #ifndef __BIG_ENDIAN__ #ifdef _SGI_SOURCE - #define __BIG_ENDIAN__ + #define __BIG_ENDIAN__ #endif #endif #ifdef __BIG_ENDIAN__ - int DDSBigLong( int src ) { return src; } - short DDSBigShort( short src ) { return src; } - float DDSBigFloat( float src ) { return src; } +int DDSBigLong( int src ) { return src; } +short DDSBigShort( short src ) { return src; } +float DDSBigFloat( float src ) { return src; } - int DDSLittleLong( int src ) - { - return ((src & 0xFF000000) >> 24) | - ((src & 0x00FF0000) >> 8) | - ((src & 0x0000FF00) << 8) | - ((src & 0x000000FF) << 24); - } +int DDSLittleLong( int src ){ + return ( ( src & 0xFF000000 ) >> 24 ) | + ( ( src & 0x00FF0000 ) >> 8 ) | + ( ( src & 0x0000FF00 ) << 8 ) | + ( ( src & 0x000000FF ) << 24 ); +} - short DDSLittleShort( short src ) - { - return ((src & 0xFF00) >> 8) | - ((src & 0x00FF) << 8); - } +short DDSLittleShort( short src ){ + return ( ( src & 0xFF00 ) >> 8 ) | + ( ( src & 0x00FF ) << 8 ); +} - float DDSLittleFloat( float src ) - { - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; - } +float DDSLittleFloat( float src ){ + floatSwapUnion in,out; + in.f = src; + out.c[ 0 ] = in.c[ 3 ]; + out.c[ 1 ] = in.c[ 2 ]; + out.c[ 2 ] = in.c[ 1 ]; + out.c[ 3 ] = in.c[ 0 ]; + return out.f; +} #else /*__BIG_ENDIAN__*/ - int DDSLittleLong( int src ) { return src; } - short DDSLittleShort( short src ) { return src; } - float DDSLittleFloat( float src ) { return src; } - - int DDSBigLong( int src ) - { - return ((src & 0xFF000000) >> 24) | - ((src & 0x00FF0000) >> 8) | - ((src & 0x0000FF00) << 8) | - ((src & 0x000000FF) << 24); - } - - short DDSBigShort( short src ) - { - return ((src & 0xFF00) >> 8) | - ((src & 0x00FF) << 8); - } - - float DDSBigFloat( float src ) - { - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; - } +int DDSLittleLong( int src ) { return src; } +short DDSLittleShort( short src ) { return src; } +float DDSLittleFloat( float src ) { return src; } + +int DDSBigLong( int src ){ + return ( ( src & 0xFF000000 ) >> 24 ) | + ( ( src & 0x00FF0000 ) >> 8 ) | + ( ( src & 0x0000FF00 ) << 8 ) | + ( ( src & 0x000000FF ) << 24 ); +} + +short DDSBigShort( short src ){ + return ( ( src & 0xFF00 ) >> 8 ) | + ( ( src & 0x00FF ) << 8 ); +} + +float DDSBigFloat( float src ){ + floatSwapUnion in,out; + in.f = src; + out.c[ 0 ] = in.c[ 3 ]; + out.c[ 1 ] = in.c[ 2 ]; + out.c[ 2 ] = in.c[ 1 ]; + out.c[ 3 ] = in.c[ 0 ]; + return out.f; +} #endif /*__BIG_ENDIAN__*/ /* -DDSDecodePixelFormat() -determines which pixel format the dds texture is in -*/ + DDSDecodePixelFormat() + determines which pixel format the dds texture is in + */ + +static void DDSDecodePixelFormat( ddsBuffer_t *dds, ddsPF_t *pf ){ + unsigned int fourCC; + -static void DDSDecodePixelFormat( ddsBuffer_t *dds, ddsPF_t *pf ) -{ - unsigned int fourCC; - - /* dummy check */ - if( dds == NULL || pf == NULL ) + if ( dds == NULL || pf == NULL ) { return; - + } + /* extract fourCC */ fourCC = dds->pixelFormat.fourCC; - + /* test it */ - if( fourCC == 0 ) + if ( fourCC == 0 ) { *pf = DDS_PF_ARGB8888; - else if( fourCC == *((unsigned int*) "DXT1") ) + } + else if ( fourCC == *( (unsigned int*) "DXT1" ) ) { *pf = DDS_PF_DXT1; - else if( fourCC == *((unsigned int*) "DXT2") ) + } + else if ( fourCC == *( (unsigned int*) "DXT2" ) ) { *pf = DDS_PF_DXT2; - else if( fourCC == *((unsigned int*) "DXT3") ) + } + else if ( fourCC == *( (unsigned int*) "DXT3" ) ) { *pf = DDS_PF_DXT3; - else if( fourCC == *((unsigned int*) "DXT4") ) + } + else if ( fourCC == *( (unsigned int*) "DXT4" ) ) { *pf = DDS_PF_DXT4; - else if( fourCC == *((unsigned int*) "DXT5") ) + } + else if ( fourCC == *( (unsigned int*) "DXT5" ) ) { *pf = DDS_PF_DXT5; - else + } + else{ *pf = DDS_PF_UNKNOWN; + } } /* -DDSGetInfo() -extracts relevant info from a dds texture, returns 0 on success -*/ + DDSGetInfo() + extracts relevant info from a dds texture, returns 0 on success + */ -int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ) -{ +int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ){ /* dummy test */ - if( dds == NULL ) + if ( dds == NULL ) { return -1; - + } + /* test dds header */ - if( *((int*) dds->magic) != *((int*) "DDS ") ) + if ( *( (int*) dds->magic ) != *( (int*) "DDS " ) ) { return -1; - if( DDSLittleLong( dds->size ) != 124 ) + } + if ( DDSLittleLong( dds->size ) != 124 ) { return -1; - + } + /* extract width and height */ - if( width != NULL ) + if ( width != NULL ) { *width = DDSLittleLong( dds->width ); - if( height != NULL ) + } + if ( height != NULL ) { *height = DDSLittleLong( dds->height ); - + } + /* get pixel format */ DDSDecodePixelFormat( dds, pf ); - + /* return ok */ return 0; } @@ -198,91 +203,89 @@ int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ) /* -DDSGetColorBlockColors() -extracts colors from a dds color block -*/ + DDSGetColorBlockColors() + extracts colors from a dds color block + */ + +static void DDSGetColorBlockColors( ddsColorBlock_t *block, ddsColor_t colors[ 4 ] ){ + unsigned short word; -static void DDSGetColorBlockColors( ddsColorBlock_t *block, ddsColor_t colors[ 4 ] ) -{ - unsigned short word; - /* color 0 */ word = DDSLittleShort( block->colors[ 0 ] ); colors[ 0 ].a = 0xff; - + /* extract rgb bits */ colors[ 0 ].b = (unsigned char) word; colors[ 0 ].b <<= 3; - colors[ 0 ].b |= (colors[ 0 ].b >> 5); + colors[ 0 ].b |= ( colors[ 0 ].b >> 5 ); word >>= 5; colors[ 0 ].g = (unsigned char) word; colors[ 0 ].g <<= 2; - colors[ 0 ].g |= (colors[ 0 ].g >> 5); + colors[ 0 ].g |= ( colors[ 0 ].g >> 5 ); word >>= 6; colors[ 0 ].r = (unsigned char) word; colors[ 0 ].r <<= 3; - colors[ 0 ].r |= (colors[ 0 ].r >> 5); + colors[ 0 ].r |= ( colors[ 0 ].r >> 5 ); /* same for color 1 */ word = DDSLittleShort( block->colors[ 1 ] ); colors[ 1 ].a = 0xff; - + /* extract rgb bits */ colors[ 1 ].b = (unsigned char) word; colors[ 1 ].b <<= 3; - colors[ 1 ].b |= (colors[ 1 ].b >> 5); + colors[ 1 ].b |= ( colors[ 1 ].b >> 5 ); word >>= 5; colors[ 1 ].g = (unsigned char) word; colors[ 1 ].g <<= 2; - colors[ 1 ].g |= (colors[ 1 ].g >> 5); + colors[ 1 ].g |= ( colors[ 1 ].g >> 5 ); word >>= 6; colors[ 1 ].r = (unsigned char) word; colors[ 1 ].r <<= 3; - colors[ 1 ].r |= (colors[ 1 ].r >> 5); - + colors[ 1 ].r |= ( colors[ 1 ].r >> 5 ); + /* use this for all but the super-freak math method */ - if( block->colors[ 0 ] > block->colors[ 1 ] ) - { - /* four-color block: derive the other two colors. + if ( block->colors[ 0 ] > block->colors[ 1 ] ) { + /* four-color block: derive the other two colors. 00 = color 0, 01 = color 1, 10 = color 2, 11 = color 3 - these two bit codes correspond to the 2-bit fields + these two bit codes correspond to the 2-bit fields stored in the 64-bit block. */ - word = ((unsigned short) colors[ 0 ].r * 2 + (unsigned short) colors[ 1 ].r ) / 3; - /* no +1 for rounding */ - /* as bits have been shifted to 888 */ + word = ( (unsigned short) colors[ 0 ].r * 2 + (unsigned short) colors[ 1 ].r ) / 3; + /* no +1 for rounding */ + /* as bits have been shifted to 888 */ colors[ 2 ].r = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].g * 2 + (unsigned short) colors[ 1 ].g) / 3; + word = ( (unsigned short) colors[ 0 ].g * 2 + (unsigned short) colors[ 1 ].g ) / 3; colors[ 2 ].g = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].b * 2 + (unsigned short) colors[ 1 ].b) / 3; + word = ( (unsigned short) colors[ 0 ].b * 2 + (unsigned short) colors[ 1 ].b ) / 3; colors[ 2 ].b = (unsigned char) word; colors[ 2 ].a = 0xff; - word = ((unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r * 2) / 3; + word = ( (unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r * 2 ) / 3; colors[ 3 ].r = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g * 2) / 3; + word = ( (unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g * 2 ) / 3; colors[ 3 ].g = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b * 2) / 3; + word = ( (unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b * 2 ) / 3; colors[ 3 ].b = (unsigned char) word; colors[ 3 ].a = 0xff; } else { /* three-color block: derive the other color. - 00 = color 0, 01 = color 1, 10 = color 2, + 00 = color 0, 01 = color 1, 10 = color 2, 11 = transparent. - These two bit codes correspond to the 2-bit fields + These two bit codes correspond to the 2-bit fields stored in the 64-bit block */ - word = ((unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r) / 2; + word = ( (unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r ) / 2; colors[ 2 ].r = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g) / 2; + word = ( (unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g ) / 2; colors[ 2 ].g = (unsigned char) word; - word = ((unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b) / 2; + word = ( (unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b ) / 2; colors[ 2 ].b = (unsigned char) word; colors[ 2 ].a = 0xff; - + /* random color to indicate alpha */ colors[ 3 ].r = 0x00; colors[ 3 ].g = 0xff; @@ -294,56 +297,55 @@ static void DDSGetColorBlockColors( ddsColorBlock_t *block, ddsColor_t colors[ 4 /* -DDSDecodeColorBlock() -decodes a dds color block -fixme: make endian-safe -*/ + DDSDecodeColorBlock() + decodes a dds color block + fixme: make endian-safe + */ + +static void DDSDecodeColorBlock( unsigned int *pixel, ddsColorBlock_t *block, int width, unsigned int colors[ 4 ] ){ + int r, n; + unsigned int bits; + unsigned int masks[] = { 3, 12, 3 << 4, 3 << 6 }; /* bit masks = 00000011, 00001100, 00110000, 11000000 */ + int shift[] = { 0, 2, 4, 6 }; + -static void DDSDecodeColorBlock( unsigned int *pixel, ddsColorBlock_t *block, int width, unsigned int colors[ 4 ] ) -{ - int r, n; - unsigned int bits; - unsigned int masks[] = { 3, 12, 3 << 4, 3 << 6 }; /* bit masks = 00000011, 00001100, 00110000, 11000000 */ - int shift[] = { 0, 2, 4, 6 }; - - /* r steps through lines in y */ - for( r = 0; r < 4; r++, pixel += (width - 4) ) /* no width * 4 as unsigned int ptr inc will * 4 */ + for ( r = 0; r < 4; r++, pixel += ( width - 4 ) ) /* no width * 4 as unsigned int ptr inc will * 4 */ { /* width * 4 bytes per pixel per line, each j dxtc row is 4 lines of pixels */ /* n steps through pixels */ - for( n = 0; n < 4; n++ ) + for ( n = 0; n < 4; n++ ) { bits = block->row[ r ] & masks[ n ]; bits >>= shift[ n ]; - switch( bits ) + switch ( bits ) { - case 0: - *pixel = colors[ 0 ]; - pixel++; - break; - - case 1: - *pixel = colors[ 1 ]; - pixel++; - break; - - case 2: - *pixel = colors[ 2 ]; - pixel++; - break; - - case 3: - *pixel = colors[ 3 ]; - pixel++; - break; - - default: - /* invalid */ - pixel++; - break; + case 0: + *pixel = colors[ 0 ]; + pixel++; + break; + + case 1: + *pixel = colors[ 1 ]; + pixel++; + break; + + case 2: + *pixel = colors[ 2 ]; + pixel++; + break; + + case 3: + *pixel = colors[ 3 ]; + pixel++; + break; + + default: + /* invalid */ + pixel++; + break; } } } @@ -352,37 +354,36 @@ static void DDSDecodeColorBlock( unsigned int *pixel, ddsColorBlock_t *block, in /* -DDSDecodeAlphaExplicit() -decodes a dds explicit alpha block -*/ - -static void DDSDecodeAlphaExplicit( unsigned int *pixel, ddsAlphaBlockExplicit_t *alphaBlock, int width, unsigned int alphaZero ) -{ - int row, pix; - unsigned short word; - ddsColor_t color; - - + DDSDecodeAlphaExplicit() + decodes a dds explicit alpha block + */ + +static void DDSDecodeAlphaExplicit( unsigned int *pixel, ddsAlphaBlockExplicit_t *alphaBlock, int width, unsigned int alphaZero ){ + int row, pix; + unsigned short word; + ddsColor_t color; + + /* clear color */ color.r = 0; color.g = 0; color.b = 0; - + /* walk rows */ - for( row = 0; row < 4; row++, pixel += (width - 4) ) + for ( row = 0; row < 4; row++, pixel += ( width - 4 ) ) { word = DDSLittleShort( alphaBlock->row[ row ] ); - + /* walk pixels */ - for( pix = 0; pix < 4; pix++ ) + for ( pix = 0; pix < 4; pix++ ) { /* zero the alpha bits of image pixel */ *pixel &= alphaZero; color.a = word & 0x000F; - color.a = color.a | (color.a << 4); - *pixel |= *((unsigned int*) &color); - word >>= 4; /* move next bits to lowest 4 */ - pixel++; /* move to next pixel in the row */ + color.a = color.a | ( color.a << 4 ); + *pixel |= *( (unsigned int*) &color ); + word >>= 4; /* move next bits to lowest 4 */ + pixel++; /* move to next pixel in the row */ } } @@ -391,92 +392,90 @@ static void DDSDecodeAlphaExplicit( unsigned int *pixel, ddsAlphaBlockExplicit_t /* -DDSDecodeAlpha3BitLinear() -decodes interpolated alpha block -*/ + DDSDecodeAlpha3BitLinear() + decodes interpolated alpha block + */ + +static void DDSDecodeAlpha3BitLinear( unsigned int *pixel, ddsAlphaBlock3BitLinear_t *alphaBlock, int width, unsigned int alphaZero ){ + + int row, pix; + unsigned int stuff; + unsigned char bits[ 4 ][ 4 ]; + unsigned short alphas[ 8 ]; + ddsColor_t aColors[ 4 ][ 4 ]; + -static void DDSDecodeAlpha3BitLinear( unsigned int *pixel, ddsAlphaBlock3BitLinear_t *alphaBlock, int width, unsigned int alphaZero ) -{ - - int row, pix; - unsigned int stuff; - unsigned char bits[ 4 ][ 4 ]; - unsigned short alphas[ 8 ]; - ddsColor_t aColors[ 4 ][ 4 ]; - - /* get initial alphas */ alphas[ 0 ] = alphaBlock->alpha0; alphas[ 1 ] = alphaBlock->alpha1; - + /* 8-alpha block */ - if( alphas[ 0 ] > alphas[ 1 ] ) - { + if ( alphas[ 0 ] > alphas[ 1 ] ) { /* 000 = alpha_0, 001 = alpha_1, others are interpolated */ - alphas[ 2 ] = ( 6 * alphas[ 0 ] + alphas[ 1 ]) / 7; /* bit code 010 */ - alphas[ 3 ] = ( 5 * alphas[ 0 ] + 2 * alphas[ 1 ]) / 7; /* bit code 011 */ - alphas[ 4 ] = ( 4 * alphas[ 0 ] + 3 * alphas[ 1 ]) / 7; /* bit code 100 */ - alphas[ 5 ] = ( 3 * alphas[ 0 ] + 4 * alphas[ 1 ]) / 7; /* bit code 101 */ - alphas[ 6 ] = ( 2 * alphas[ 0 ] + 5 * alphas[ 1 ]) / 7; /* bit code 110 */ - alphas[ 7 ] = ( alphas[ 0 ] + 6 * alphas[ 1 ]) / 7; /* bit code 111 */ + alphas[ 2 ] = ( 6 * alphas[ 0 ] + alphas[ 1 ] ) / 7; /* bit code 010 */ + alphas[ 3 ] = ( 5 * alphas[ 0 ] + 2 * alphas[ 1 ] ) / 7; /* bit code 011 */ + alphas[ 4 ] = ( 4 * alphas[ 0 ] + 3 * alphas[ 1 ] ) / 7; /* bit code 100 */ + alphas[ 5 ] = ( 3 * alphas[ 0 ] + 4 * alphas[ 1 ] ) / 7; /* bit code 101 */ + alphas[ 6 ] = ( 2 * alphas[ 0 ] + 5 * alphas[ 1 ] ) / 7; /* bit code 110 */ + alphas[ 7 ] = ( alphas[ 0 ] + 6 * alphas[ 1 ] ) / 7; /* bit code 111 */ } - + /* 6-alpha block */ else - { + { /* 000 = alpha_0, 001 = alpha_1, others are interpolated */ - alphas[ 2 ] = (4 * alphas[ 0 ] + alphas[ 1 ]) / 5; /* bit code 010 */ - alphas[ 3 ] = (3 * alphas[ 0 ] + 2 * alphas[ 1 ]) / 5; /* bit code 011 */ - alphas[ 4 ] = (2 * alphas[ 0 ] + 3 * alphas[ 1 ]) / 5; /* bit code 100 */ - alphas[ 5 ] = ( alphas[ 0 ] + 4 * alphas[ 1 ]) / 5; /* bit code 101 */ - alphas[ 6 ] = 0; /* bit code 110 */ - alphas[ 7 ] = 255; /* bit code 111 */ + alphas[ 2 ] = ( 4 * alphas[ 0 ] + alphas[ 1 ] ) / 5; /* bit code 010 */ + alphas[ 3 ] = ( 3 * alphas[ 0 ] + 2 * alphas[ 1 ] ) / 5; /* bit code 011 */ + alphas[ 4 ] = ( 2 * alphas[ 0 ] + 3 * alphas[ 1 ] ) / 5; /* bit code 100 */ + alphas[ 5 ] = ( alphas[ 0 ] + 4 * alphas[ 1 ] ) / 5; /* bit code 101 */ + alphas[ 6 ] = 0; /* bit code 110 */ + alphas[ 7 ] = 255; /* bit code 111 */ } - + /* decode 3-bit fields into array of 16 bytes with same value */ - + /* first two rows of 4 pixels each */ - stuff = *((unsigned int*) &(alphaBlock->stuff[ 0 ])); - - bits[ 0 ][ 0 ] = (unsigned char) (stuff & 0x00000007); + stuff = *( (unsigned int*) &( alphaBlock->stuff[ 0 ] ) ); + + bits[ 0 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 0 ][ 1 ] = (unsigned char) (stuff & 0x00000007); + bits[ 0 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 0 ][ 2 ] = (unsigned char) (stuff & 0x00000007); + bits[ 0 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 0 ][ 3 ] = (unsigned char) (stuff & 0x00000007); + bits[ 0 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 1 ][ 0 ] = (unsigned char) (stuff & 0x00000007); + bits[ 1 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 1 ][ 1 ] = (unsigned char) (stuff & 0x00000007); + bits[ 1 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 1 ][ 2 ] = (unsigned char) (stuff & 0x00000007); + bits[ 1 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 1 ][ 3 ] = (unsigned char) (stuff & 0x00000007); - + bits[ 1 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); + /* last two rows */ - stuff = *((unsigned int*) &(alphaBlock->stuff[ 3 ])); /* last 3 bytes */ - - bits[ 2 ][ 0 ] = (unsigned char) (stuff & 0x00000007); + stuff = *( (unsigned int*) &( alphaBlock->stuff[ 3 ] ) ); /* last 3 bytes */ + + bits[ 2 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 2 ][ 1 ] = (unsigned char) (stuff & 0x00000007); + bits[ 2 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 2 ][ 2 ] = (unsigned char) (stuff & 0x00000007); + bits[ 2 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 2 ][ 3 ] = (unsigned char) (stuff & 0x00000007); + bits[ 2 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 3 ][ 0 ] = (unsigned char) (stuff & 0x00000007); + bits[ 3 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 3 ][ 1 ] = (unsigned char) (stuff & 0x00000007); + bits[ 3 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 3 ][ 2 ] = (unsigned char) (stuff & 0x00000007); + bits[ 3 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); stuff >>= 3; - bits[ 3 ][ 3 ] = (unsigned char) (stuff & 0x00000007); - + bits[ 3 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); + /* decode the codes into alpha values */ - for( row = 0; row < 4; row++ ) + for ( row = 0; row < 4; row++ ) { - for( pix=0; pix < 4; pix++ ) + for ( pix = 0; pix < 4; pix++ ) { aColors[ row ][ pix ].r = 0; aColors[ row ][ pix ].g = 0; @@ -484,17 +483,17 @@ static void DDSDecodeAlpha3BitLinear( unsigned int *pixel, ddsAlphaBlock3BitLine aColors[ row ][ pix ].a = (unsigned char) alphas[ bits[ row ][ pix ] ]; } } - + /* write out alpha values to the image bits */ - for( row = 0; row < 4; row++, pixel += width-4 ) + for ( row = 0; row < 4; row++, pixel += width - 4 ) { - for( pix = 0; pix < 4; pix++ ) + for ( pix = 0; pix < 4; pix++ ) { /* zero the alpha bits of image pixel */ *pixel &= alphaZero; - + /* or the bits into the prev. nulled alpha */ - *pixel |= *((unsigned int*) &(aColors[ row ][ pix ])); + *pixel |= *( (unsigned int*) &( aColors[ row ][ pix ] ) ); pixel++; } } @@ -503,37 +502,36 @@ static void DDSDecodeAlpha3BitLinear( unsigned int *pixel, ddsAlphaBlock3BitLine /* -DDSDecompressDXT1() -decompresses a dxt1 format texture -*/ + DDSDecompressDXT1() + decompresses a dxt1 format texture + */ + +static int DDSDecompressDXT1( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int x, y, xBlocks, yBlocks; + unsigned int *pixel; + ddsColorBlock_t *block; + ddsColor_t colors[ 4 ]; + -static int DDSDecompressDXT1( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int x, y, xBlocks, yBlocks; - unsigned int *pixel; - ddsColorBlock_t *block; - ddsColor_t colors[ 4 ]; - - /* setup */ xBlocks = width / 4; yBlocks = height / 4; - + /* walk y */ - for( y = 0; y < yBlocks; y++ ) + for ( y = 0; y < yBlocks; y++ ) { /* 8 bytes per block */ - block = (ddsColorBlock_t*) ((char *) dds->data + y * xBlocks * 8); + block = (ddsColorBlock_t*) ( (char *) dds->data + y * xBlocks * 8 ); /* walk x */ - for( x = 0; x < xBlocks; x++, block++ ) + for ( x = 0; x < xBlocks; x++, block++ ) { DDSGetColorBlockColors( block, colors ); - pixel = (unsigned int*) (pixels + x * 16 + (y * 4) * width * 4); + pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); } } - + /* return ok */ return 0; } @@ -541,55 +539,54 @@ static int DDSDecompressDXT1( ddsBuffer_t *dds, int width, int height, unsigned /* -DDSDecompressDXT3() -decompresses a dxt3 format texture -*/ + DDSDecompressDXT3() + decompresses a dxt3 format texture + */ -static int DDSDecompressDXT3( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int x, y, xBlocks, yBlocks; - unsigned int *pixel, alphaZero; - ddsColorBlock_t *block; - ddsAlphaBlockExplicit_t *alphaBlock; - ddsColor_t colors[ 4 ]; +static int DDSDecompressDXT3( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int x, y, xBlocks, yBlocks; + unsigned int *pixel, alphaZero; + ddsColorBlock_t *block; + ddsAlphaBlockExplicit_t *alphaBlock; + ddsColor_t colors[ 4 ]; /* setup */ xBlocks = width / 4; yBlocks = height / 4; - + /* create zero alpha */ colors[ 0 ].a = 0; colors[ 0 ].r = 0xFF; colors[ 0 ].g = 0xFF; colors[ 0 ].b = 0xFF; - alphaZero = *((unsigned int*) &colors[ 0 ]); - + alphaZero = *( (unsigned int*) &colors[ 0 ] ); + /* walk y */ - for( y = 0; y < yBlocks; y++ ) + for ( y = 0; y < yBlocks; y++ ) { /* 8 bytes per block, 1 block for alpha, 1 block for color */ - block = (ddsColorBlock_t*) ((char *) dds->data + y * xBlocks * 16); + block = (ddsColorBlock_t*) ( (char *) dds->data + y * xBlocks * 16 ); /* walk x */ - for( x = 0; x < xBlocks; x++, block++ ) + for ( x = 0; x < xBlocks; x++, block++ ) { /* get alpha block */ alphaBlock = (ddsAlphaBlockExplicit_t*) block; - + /* get color block */ block++; DDSGetColorBlockColors( block, colors ); - + /* decode color block */ - pixel = (unsigned int*) (pixels + x * 16 + (y * 4) * width * 4); + pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); - + /* overwrite alpha bits with alpha block */ DDSDecodeAlphaExplicit( pixel, alphaBlock, width, alphaZero ); } } - + /* return ok */ return 0; } @@ -597,55 +594,54 @@ static int DDSDecompressDXT3( ddsBuffer_t *dds, int width, int height, unsigned /* -DDSDecompressDXT5() -decompresses a dxt5 format texture -*/ + DDSDecompressDXT5() + decompresses a dxt5 format texture + */ -static int DDSDecompressDXT5( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int x, y, xBlocks, yBlocks; - unsigned int *pixel, alphaZero; - ddsColorBlock_t *block; - ddsAlphaBlock3BitLinear_t *alphaBlock; - ddsColor_t colors[ 4 ]; +static int DDSDecompressDXT5( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int x, y, xBlocks, yBlocks; + unsigned int *pixel, alphaZero; + ddsColorBlock_t *block; + ddsAlphaBlock3BitLinear_t *alphaBlock; + ddsColor_t colors[ 4 ]; /* setup */ xBlocks = width / 4; yBlocks = height / 4; - + /* create zero alpha */ colors[ 0 ].a = 0; colors[ 0 ].r = 0xFF; colors[ 0 ].g = 0xFF; colors[ 0 ].b = 0xFF; - alphaZero = *((unsigned int*) &colors[ 0 ]); - + alphaZero = *( (unsigned int*) &colors[ 0 ] ); + /* walk y */ - for( y = 0; y < yBlocks; y++ ) + for ( y = 0; y < yBlocks; y++ ) { /* 8 bytes per block, 1 block for alpha, 1 block for color */ - block = (ddsColorBlock_t*) ((char *) dds->data + y * xBlocks * 16); + block = (ddsColorBlock_t*) ( (char *) dds->data + y * xBlocks * 16 ); /* walk x */ - for( x = 0; x < xBlocks; x++, block++ ) + for ( x = 0; x < xBlocks; x++, block++ ) { /* get alpha block */ alphaBlock = (ddsAlphaBlock3BitLinear_t*) block; - + /* get color block */ block++; DDSGetColorBlockColors( block, colors ); - + /* decode color block */ - pixel = (unsigned int*) (pixels + x * 16 + (y * 4) * width * 4); + pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); - + /* overwrite alpha bits with alpha block */ DDSDecodeAlpha3BitLinear( pixel, alphaBlock, width, alphaZero ); } } - + /* return ok */ return 0; } @@ -653,18 +649,17 @@ static int DDSDecompressDXT5( ddsBuffer_t *dds, int width, int height, unsigned /* -DDSDecompressDXT2() -decompresses a dxt2 format texture (fixme: un-premultiply alpha) -*/ + DDSDecompressDXT2() + decompresses a dxt2 format texture (fixme: un-premultiply alpha) + */ + +static int DDSDecompressDXT2( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int r; + -static int DDSDecompressDXT2( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int r; - - /* decompress dxt3 first */ r = DDSDecompressDXT3( dds, width, height, pixels ); - + /* return to sender */ return r; } @@ -672,18 +667,17 @@ static int DDSDecompressDXT2( ddsBuffer_t *dds, int width, int height, unsigned /* -DDSDecompressDXT4() -decompresses a dxt4 format texture (fixme: un-premultiply alpha) -*/ + DDSDecompressDXT4() + decompresses a dxt4 format texture (fixme: un-premultiply alpha) + */ + +static int DDSDecompressDXT4( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int r; + -static int DDSDecompressDXT4( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int r; - - /* decompress dxt5 first */ r = DDSDecompressDXT5( dds, width, height, pixels ); - + /* return to sender */ return r; } @@ -691,25 +685,24 @@ static int DDSDecompressDXT4( ddsBuffer_t *dds, int width, int height, unsigned /* -DDSDecompressARGB8888() -decompresses an argb 8888 format texture -*/ + DDSDecompressARGB8888() + decompresses an argb 8888 format texture + */ + +static int DDSDecompressARGB8888( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ + int x, y; + unsigned char *in, *out; + -static int DDSDecompressARGB8888( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ) -{ - int x, y; - unsigned char *in, *out; - - /* setup */ in = dds->data; out = pixels; - + /* walk y */ - for( y = 0; y < height; y++ ) + for ( y = 0; y < height; y++ ) { /* walk x */ - for( x = 0; x < width; x++ ) + for ( x = 0; x < width; x++ ) { *out++ = *in++; *out++ = *in++; @@ -717,7 +710,7 @@ static int DDSDecompressARGB8888( ddsBuffer_t *dds, int width, int height, unsig *out++ = *in++; } } - + /* return ok */ return 0; } @@ -725,57 +718,56 @@ static int DDSDecompressARGB8888( ddsBuffer_t *dds, int width, int height, unsig /* -DDSDecompress() -decompresses a dds texture into an rgba image buffer, returns 0 on success -*/ + DDSDecompress() + decompresses a dds texture into an rgba image buffer, returns 0 on success + */ + +int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ){ + int width, height, r; + ddsPF_t pf; + -int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ) -{ - int width, height, r; - ddsPF_t pf; - - /* get dds info */ r = DDSGetInfo( dds, &width, &height, &pf ); - if( r ) + if ( r ) { return r; - + } + /* decompress */ - switch( pf ) + switch ( pf ) { - case DDS_PF_ARGB8888: - /* fixme: support other [a]rgb formats */ - r = DDSDecompressARGB8888( dds, width, height, pixels ); - break; - - case DDS_PF_DXT1: - r = DDSDecompressDXT1( dds, width, height, pixels ); - break; - - case DDS_PF_DXT2: - r = DDSDecompressDXT2( dds, width, height, pixels ); - break; - - case DDS_PF_DXT3: - r = DDSDecompressDXT3( dds, width, height, pixels ); - break; - - case DDS_PF_DXT4: - r = DDSDecompressDXT4( dds, width, height, pixels ); - break; - - case DDS_PF_DXT5: - r = DDSDecompressDXT5( dds, width, height, pixels ); - break; - - default: - case DDS_PF_UNKNOWN: - memset( pixels, 0xFF, width * height * 4 ); - r = -1; - break; + case DDS_PF_ARGB8888: + /* fixme: support other [a]rgb formats */ + r = DDSDecompressARGB8888( dds, width, height, pixels ); + break; + + case DDS_PF_DXT1: + r = DDSDecompressDXT1( dds, width, height, pixels ); + break; + + case DDS_PF_DXT2: + r = DDSDecompressDXT2( dds, width, height, pixels ); + break; + + case DDS_PF_DXT3: + r = DDSDecompressDXT3( dds, width, height, pixels ); + break; + + case DDS_PF_DXT4: + r = DDSDecompressDXT4( dds, width, height, pixels ); + break; + + case DDS_PF_DXT5: + r = DDSDecompressDXT5( dds, width, height, pixels ); + break; + + default: + case DDS_PF_UNKNOWN: + memset( pixels, 0xFF, width * height * 4 ); + r = -1; + break; } - + /* return to sender */ return r; } - diff --git a/libs/debugging/debugging.cpp b/libs/debugging/debugging.cpp index 23784950..b292840f 100644 --- a/libs/debugging/debugging.cpp +++ b/libs/debugging/debugging.cpp @@ -1,28 +1,27 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "debugging.h" -void TEST_ASSERT() -{ - ERROR_MESSAGE("test"); - ASSERT_NOTNULL(0); +void TEST_ASSERT(){ + ERROR_MESSAGE( "test" ); + ASSERT_NOTNULL( 0 ); } diff --git a/libs/debugging/debugging.h b/libs/debugging/debugging.h index 4c03e9d7..34dc9445 100644 --- a/libs/debugging/debugging.h +++ b/libs/debugging/debugging.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_DEBUGGING_DEBUGGING_H) +#if !defined( INCLUDED_DEBUGGING_DEBUGGING_H ) #define INCLUDED_DEBUGGING_DEBUGGING_H /// \file @@ -29,108 +29,100 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "warnings.h" #include "generic/static.h" -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined( _MSC_VER ) && defined( _M_IX86 ) #define DEBUGGER_BREAKPOINT() __asm { int 3 } -#elif defined (__i386__) && defined (__GNUC__) && __GNUC__ >= 2 -#define DEBUGGER_BREAKPOINT() __asm__ __volatile__ ("int $03") +#elif defined ( __i386__ ) && defined ( __GNUC__ ) && __GNUC__ >= 2 +#define DEBUGGER_BREAKPOINT() __asm__ __volatile__ ( "int $03" ) #else #include -#define DEBUGGER_BREAKPOINT() raise(SIGTRAP); +#define DEBUGGER_BREAKPOINT() raise( SIGTRAP ); #endif -#define STR(x) #x -#define STR2(x) STR(x) -#define FILE_LINE __FILE__ ":" STR2(__LINE__) +#define STR( x ) # x +#define STR2( x ) STR( x ) +#define FILE_LINE __FILE__ ":" STR2( __LINE__ ) -#if defined(_DEBUG) || 1 +#if defined( _DEBUG ) || 1 #define DEBUG_ASSERTS #endif class DebugMessageHandler { public: - virtual TextOutputStream& getOutputStream() = 0; - virtual bool handleMessage() = 0; +virtual TextOutputStream& getOutputStream() = 0; +virtual bool handleMessage() = 0; }; class NullDebugMessageHandler : public NullOutputStream, public DebugMessageHandler { public: - virtual TextOutputStream& getOutputStream() - { - return *this; - } - virtual bool handleMessage() - { - return false; - } +virtual TextOutputStream& getOutputStream(){ + return *this; +} +virtual bool handleMessage(){ + return false; +} }; class DefaultDebugMessageHandler : public DebugMessageHandler { public: - virtual TextOutputStream& getOutputStream() - { - return globalErrorStream(); - } - virtual bool handleMessage() - { -#if defined(_DEBUG) - return false; // send debug-break +virtual TextOutputStream& getOutputStream(){ + return globalErrorStream(); +} +virtual bool handleMessage(){ +#if defined( _DEBUG ) + return false; // send debug-break #else - return true; + return true; #endif - } +} }; class DebugMessageHandlerRef : public DefaultDebugMessageHandler { - DebugMessageHandler* m_handler; +DebugMessageHandler* m_handler; public: - DebugMessageHandlerRef() - : m_handler(this) - { - } - void setHandler(DebugMessageHandler& handler) - { - m_handler = &handler; - } - DebugMessageHandler& getHandler() - { - return *m_handler; - } +DebugMessageHandlerRef() + : m_handler( this ){ +} +void setHandler( DebugMessageHandler& handler ){ + m_handler = &handler; +} +DebugMessageHandler& getHandler(){ + return *m_handler; +} }; typedef Static GlobalDebugMessageHandler; -inline DebugMessageHandler& globalDebugMessageHandler() -{ - return GlobalDebugMessageHandler::instance().getHandler(); +inline DebugMessageHandler& globalDebugMessageHandler(){ + return GlobalDebugMessageHandler::instance().getHandler(); } -#if defined(DEBUG_ASSERTS) +#if defined( DEBUG_ASSERTS ) /// \brief Sends a \p message to the current debug-message-handler text-output-stream if \p condition evaluates to false. -#define ASSERT_MESSAGE(condition, message) do{\ -if(!(condition))\ -{\ - globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nassertion failure: " << message << "\n";\ - if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }\ -}} while(0) +#define ASSERT_MESSAGE( condition, message ) do { \ + if ( !( condition ) ) \ + { \ + globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nassertion failure: " << message << "\n"; \ + if ( !globalDebugMessageHandler().handleMessage() ) { DEBUGGER_BREAKPOINT(); } \ + }} while ( 0 ) /// \brief Sends a \p message to the current debug-message-handler text-output-stream. -#define ERROR_MESSAGE(message) do{\ -globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nruntime error: " << message << "\n";\ -if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }} while(0) +#define ERROR_MESSAGE( message ) do { \ + globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nruntime error: " << message << "\n"; \ + if ( !globalDebugMessageHandler().handleMessage() ) { DEBUGGER_BREAKPOINT(); }} while ( 0 ) -#define ASSERT_NOTNULL(ptr) ASSERT_MESSAGE(ptr != 0, "pointer \"" #ptr "\" is null") +#define ASSERT_NOTNULL( ptr ) ASSERT_MESSAGE( ptr != 0, "pointer \"" # ptr "\" is null" ) #else -#define ASSERT_MESSAGE(condition, message) -#define ERROR_MESSAGE(message) -#define ASSERT_NOTNULL(ptr) +#define ASSERT_MESSAGE( condition, message ) +#define ERROR_MESSAGE( message ) +#define ASSERT_NOTNULL( ptr ) #endif diff --git a/libs/dragplanes.cpp b/libs/dragplanes.cpp index 9c7e18f8..89da6662 100644 --- a/libs/dragplanes.cpp +++ b/libs/dragplanes.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "dragplanes.h" - diff --git a/libs/dragplanes.h b/libs/dragplanes.h index a8b54dc1..e85a5cdc 100644 --- a/libs/dragplanes.h +++ b/libs/dragplanes.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_DRAGPLANES_H) +#if !defined( INCLUDED_DRAGPLANES_H ) #define INCLUDED_DRAGPLANES_H #include "selectable.h" @@ -28,232 +28,201 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "math/line.h" // local must be a pure rotation -inline Vector3 translation_to_local(const Vector3& translation, const Matrix4& local) -{ - return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3(matrix4_transposed(local), translation), - local - ) - ); +inline Vector3 translation_to_local( const Vector3& translation, const Matrix4& local ){ + return matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( matrix4_transposed( local ), translation ), + local + ) + ); } // local must be a pure rotation -inline Vector3 translation_from_local(const Vector3& translation, const Matrix4& local) -{ - return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3(local, translation), - matrix4_transposed(local) - ) - ); +inline Vector3 translation_from_local( const Vector3& translation, const Matrix4& local ){ + return matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3( local, translation ), + matrix4_transposed( local ) + ) + ); } class DragPlanes { public: - ObservedSelectable m_selectable_right; // +x - ObservedSelectable m_selectable_left; // -x - ObservedSelectable m_selectable_front; // +y - ObservedSelectable m_selectable_back; // -y - ObservedSelectable m_selectable_top; // +z - ObservedSelectable m_selectable_bottom; // -z - AABB m_bounds; - - DragPlanes(const SelectionChangeCallback& onchanged) : - m_selectable_right(onchanged), - m_selectable_left(onchanged), - m_selectable_front(onchanged), - m_selectable_back(onchanged), - m_selectable_top(onchanged), - m_selectable_bottom(onchanged) - { - } - bool isSelected() const - { - return m_selectable_right.isSelected() - || m_selectable_left.isSelected() - || m_selectable_front.isSelected() - || m_selectable_back.isSelected() - || m_selectable_top.isSelected() - || m_selectable_bottom.isSelected(); - } - void setSelected(bool selected) - { - m_selectable_right.setSelected(selected); - m_selectable_left.setSelected(selected); - m_selectable_front.setSelected(selected); - m_selectable_back.setSelected(selected); - m_selectable_top.setSelected(selected); - m_selectable_bottom.setSelected(selected); - } - void selectPlanes(const AABB& aabb, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback, const Matrix4& rotation = g_matrix4_identity) - { - Line line(test.getNear(), test.getFar()); - Vector3 corners[8]; - aabb_corners_oriented(aabb, rotation, corners); - - Plane3 planes[6]; - aabb_planes_oriented(aabb, rotation, planes); - - for(Vector3* i = corners; i != corners + 8; ++i) - { - *i = vector3_subtracted(line_closest_point(line, *i), *i); - } - - if(vector3_dot(planes[0].normal(), corners[1]) > 0 - && vector3_dot(planes[0].normal(), corners[2]) > 0 - && vector3_dot(planes[0].normal(), corners[5]) > 0 - && vector3_dot(planes[0].normal(), corners[6]) > 0) - { - Selector_add(selector, m_selectable_right); - selectedPlaneCallback(planes[0]); - //globalOutputStream() << "right\n"; - } - if(vector3_dot(planes[1].normal(), corners[0]) > 0 - && vector3_dot(planes[1].normal(), corners[3]) > 0 - && vector3_dot(planes[1].normal(), corners[4]) > 0 - && vector3_dot(planes[1].normal(), corners[7]) > 0) - { - Selector_add(selector, m_selectable_left); - selectedPlaneCallback(planes[1]); - //globalOutputStream() << "left\n"; - } - if(vector3_dot(planes[2].normal(), corners[0]) > 0 - && vector3_dot(planes[2].normal(), corners[1]) > 0 - && vector3_dot(planes[2].normal(), corners[4]) > 0 - && vector3_dot(planes[2].normal(), corners[5]) > 0) - { - Selector_add(selector, m_selectable_front); - selectedPlaneCallback(planes[2]); - //globalOutputStream() << "front\n"; - } - if(vector3_dot(planes[3].normal(), corners[2]) > 0 - && vector3_dot(planes[3].normal(), corners[3]) > 0 - && vector3_dot(planes[3].normal(), corners[6]) > 0 - && vector3_dot(planes[3].normal(), corners[7]) > 0) - { - Selector_add(selector, m_selectable_back); - selectedPlaneCallback(planes[3]); - //globalOutputStream() << "back\n"; - } - if(vector3_dot(planes[4].normal(), corners[0]) > 0 - && vector3_dot(planes[4].normal(), corners[1]) > 0 - && vector3_dot(planes[4].normal(), corners[2]) > 0 - && vector3_dot(planes[4].normal(), corners[3]) > 0) - { - Selector_add(selector, m_selectable_top); - selectedPlaneCallback(planes[4]); - //globalOutputStream() << "top\n"; - } - if(vector3_dot(planes[5].normal(), corners[4]) > 0 - && vector3_dot(planes[5].normal(), corners[5]) > 0 - && vector3_dot(planes[5].normal(), corners[6]) > 0 - && vector3_dot(planes[5].normal(), corners[7]) > 0) - { - Selector_add(selector, m_selectable_bottom); - selectedPlaneCallback(planes[5]); - //globalOutputStream() << "bottom\n"; - } - - m_bounds = aabb; - } - void selectReversedPlanes(const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity) - { - Plane3 planes[6]; - aabb_planes_oriented(aabb, rotation, planes); - - if(selectedPlanes.contains(plane3_flipped(planes[0]))) - { - Selector_add(selector, m_selectable_right); - } - if(selectedPlanes.contains(plane3_flipped(planes[1]))) - { - Selector_add(selector, m_selectable_left); - } - if(selectedPlanes.contains(plane3_flipped(planes[2]))) - { - Selector_add(selector, m_selectable_front); - } - if(selectedPlanes.contains(plane3_flipped(planes[3]))) - { - Selector_add(selector, m_selectable_back); - } - if(selectedPlanes.contains(plane3_flipped(planes[4]))) - { - Selector_add(selector, m_selectable_top); - } - if(selectedPlanes.contains(plane3_flipped(planes[5]))) - { - Selector_add(selector, m_selectable_bottom); - } - } - AABB evaluateResize(const Vector3& translation) const - { - Vector3 min = m_bounds.origin - m_bounds.extents; - Vector3 max = m_bounds.origin + m_bounds.extents; - if(m_bounds.extents[0] != 0) - { - if(m_selectable_right.isSelected()) - { - max[0] += translation[0]; - //globalOutputStream() << "moving right\n"; - } - if(m_selectable_left.isSelected()) - { - min[0] += translation[0]; - //globalOutputStream() << "moving left\n"; - } - } - if(m_bounds.extents[1] != 0) - { - if(m_selectable_front.isSelected()) - { - max[1] += translation[1]; - //globalOutputStream() << "moving front\n"; - } - if(m_selectable_back.isSelected()) - { - min[1] += translation[1]; - //globalOutputStream() << "moving back\n"; - } - } - if(m_bounds.extents[2] != 0) - { - if(m_selectable_top.isSelected()) - { - max[2] += translation[2]; - //globalOutputStream() << "moving top\n"; - } - if(m_selectable_bottom.isSelected()) - { - min[2] += translation[2]; - //globalOutputStream() << "moving bottom\n"; - } - } - - return AABB(vector3_mid(min, max), vector3_scaled(vector3_subtracted(max, min), 0.5)); - } - AABB evaluateResize(const Vector3& translation, const Matrix4& rotation) const - { - AABB aabb(evaluateResize(translation_to_local(translation, rotation))); - aabb.origin = m_bounds.origin + translation_from_local(aabb.origin - m_bounds.origin, rotation); - return aabb; - } - Matrix4 evaluateTransform(const Vector3& translation) const - { - AABB aabb(evaluateResize(translation)); - Vector3 scale( - m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, - m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, - m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 - ); - - Matrix4 matrix(matrix4_translation_for_vec3(aabb.origin - m_bounds.origin)); - matrix4_pivoted_scale_by_vec3(matrix, scale, m_bounds.origin); - - return matrix; - } +ObservedSelectable m_selectable_right; // +x +ObservedSelectable m_selectable_left; // -x +ObservedSelectable m_selectable_front; // +y +ObservedSelectable m_selectable_back; // -y +ObservedSelectable m_selectable_top; // +z +ObservedSelectable m_selectable_bottom; // -z +AABB m_bounds; + +DragPlanes( const SelectionChangeCallback& onchanged ) : + m_selectable_right( onchanged ), + m_selectable_left( onchanged ), + m_selectable_front( onchanged ), + m_selectable_back( onchanged ), + m_selectable_top( onchanged ), + m_selectable_bottom( onchanged ){ +} +bool isSelected() const { + return m_selectable_right.isSelected() + || m_selectable_left.isSelected() + || m_selectable_front.isSelected() + || m_selectable_back.isSelected() + || m_selectable_top.isSelected() + || m_selectable_bottom.isSelected(); +} +void setSelected( bool selected ){ + m_selectable_right.setSelected( selected ); + m_selectable_left.setSelected( selected ); + m_selectable_front.setSelected( selected ); + m_selectable_back.setSelected( selected ); + m_selectable_top.setSelected( selected ); + m_selectable_bottom.setSelected( selected ); +} +void selectPlanes( const AABB& aabb, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback, const Matrix4& rotation = g_matrix4_identity ){ + Line line( test.getNear(), test.getFar() ); + Vector3 corners[8]; + aabb_corners_oriented( aabb, rotation, corners ); + + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); + + for ( Vector3* i = corners; i != corners + 8; ++i ) + { + *i = vector3_subtracted( line_closest_point( line, *i ), *i ); + } + + if ( vector3_dot( planes[0].normal(), corners[1] ) > 0 + && vector3_dot( planes[0].normal(), corners[2] ) > 0 + && vector3_dot( planes[0].normal(), corners[5] ) > 0 + && vector3_dot( planes[0].normal(), corners[6] ) > 0 ) { + Selector_add( selector, m_selectable_right ); + selectedPlaneCallback( planes[0] ); + //globalOutputStream() << "right\n"; + } + if ( vector3_dot( planes[1].normal(), corners[0] ) > 0 + && vector3_dot( planes[1].normal(), corners[3] ) > 0 + && vector3_dot( planes[1].normal(), corners[4] ) > 0 + && vector3_dot( planes[1].normal(), corners[7] ) > 0 ) { + Selector_add( selector, m_selectable_left ); + selectedPlaneCallback( planes[1] ); + //globalOutputStream() << "left\n"; + } + if ( vector3_dot( planes[2].normal(), corners[0] ) > 0 + && vector3_dot( planes[2].normal(), corners[1] ) > 0 + && vector3_dot( planes[2].normal(), corners[4] ) > 0 + && vector3_dot( planes[2].normal(), corners[5] ) > 0 ) { + Selector_add( selector, m_selectable_front ); + selectedPlaneCallback( planes[2] ); + //globalOutputStream() << "front\n"; + } + if ( vector3_dot( planes[3].normal(), corners[2] ) > 0 + && vector3_dot( planes[3].normal(), corners[3] ) > 0 + && vector3_dot( planes[3].normal(), corners[6] ) > 0 + && vector3_dot( planes[3].normal(), corners[7] ) > 0 ) { + Selector_add( selector, m_selectable_back ); + selectedPlaneCallback( planes[3] ); + //globalOutputStream() << "back\n"; + } + if ( vector3_dot( planes[4].normal(), corners[0] ) > 0 + && vector3_dot( planes[4].normal(), corners[1] ) > 0 + && vector3_dot( planes[4].normal(), corners[2] ) > 0 + && vector3_dot( planes[4].normal(), corners[3] ) > 0 ) { + Selector_add( selector, m_selectable_top ); + selectedPlaneCallback( planes[4] ); + //globalOutputStream() << "top\n"; + } + if ( vector3_dot( planes[5].normal(), corners[4] ) > 0 + && vector3_dot( planes[5].normal(), corners[5] ) > 0 + && vector3_dot( planes[5].normal(), corners[6] ) > 0 + && vector3_dot( planes[5].normal(), corners[7] ) > 0 ) { + Selector_add( selector, m_selectable_bottom ); + selectedPlaneCallback( planes[5] ); + //globalOutputStream() << "bottom\n"; + } + + m_bounds = aabb; +} +void selectReversedPlanes( const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity ){ + Plane3 planes[6]; + aabb_planes_oriented( aabb, rotation, planes ); + + if ( selectedPlanes.contains( plane3_flipped( planes[0] ) ) ) { + Selector_add( selector, m_selectable_right ); + } + if ( selectedPlanes.contains( plane3_flipped( planes[1] ) ) ) { + Selector_add( selector, m_selectable_left ); + } + if ( selectedPlanes.contains( plane3_flipped( planes[2] ) ) ) { + Selector_add( selector, m_selectable_front ); + } + if ( selectedPlanes.contains( plane3_flipped( planes[3] ) ) ) { + Selector_add( selector, m_selectable_back ); + } + if ( selectedPlanes.contains( plane3_flipped( planes[4] ) ) ) { + Selector_add( selector, m_selectable_top ); + } + if ( selectedPlanes.contains( plane3_flipped( planes[5] ) ) ) { + Selector_add( selector, m_selectable_bottom ); + } +} +AABB evaluateResize( const Vector3& translation ) const { + Vector3 min = m_bounds.origin - m_bounds.extents; + Vector3 max = m_bounds.origin + m_bounds.extents; + if ( m_bounds.extents[0] != 0 ) { + if ( m_selectable_right.isSelected() ) { + max[0] += translation[0]; + //globalOutputStream() << "moving right\n"; + } + if ( m_selectable_left.isSelected() ) { + min[0] += translation[0]; + //globalOutputStream() << "moving left\n"; + } + } + if ( m_bounds.extents[1] != 0 ) { + if ( m_selectable_front.isSelected() ) { + max[1] += translation[1]; + //globalOutputStream() << "moving front\n"; + } + if ( m_selectable_back.isSelected() ) { + min[1] += translation[1]; + //globalOutputStream() << "moving back\n"; + } + } + if ( m_bounds.extents[2] != 0 ) { + if ( m_selectable_top.isSelected() ) { + max[2] += translation[2]; + //globalOutputStream() << "moving top\n"; + } + if ( m_selectable_bottom.isSelected() ) { + min[2] += translation[2]; + //globalOutputStream() << "moving bottom\n"; + } + } + + return AABB( vector3_mid( min, max ), vector3_scaled( vector3_subtracted( max, min ), 0.5 ) ); +} +AABB evaluateResize( const Vector3& translation, const Matrix4& rotation ) const { + AABB aabb( evaluateResize( translation_to_local( translation, rotation ) ) ); + aabb.origin = m_bounds.origin + translation_from_local( aabb.origin - m_bounds.origin, rotation ); + return aabb; +} +Matrix4 evaluateTransform( const Vector3& translation ) const { + AABB aabb( evaluateResize( translation ) ); + Vector3 scale( + m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, + m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, + m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 + ); + + Matrix4 matrix( matrix4_translation_for_vec3( aabb.origin - m_bounds.origin ) ); + matrix4_pivoted_scale_by_vec3( matrix, scale, m_bounds.origin ); + + return matrix; +} }; #endif diff --git a/libs/eclasslib.cpp b/libs/eclasslib.cpp index a320bc26..04d0d690 100644 --- a/libs/eclasslib.cpp +++ b/libs/eclasslib.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "eclasslib.h" diff --git a/libs/eclasslib.h b/libs/eclasslib.h index 7bee547b..d2730d62 100644 --- a/libs/eclasslib.h +++ b/libs/eclasslib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_ECLASSLIB_H) +#if !defined ( INCLUDED_ECLASSLIB_H ) #define INCLUDED_ECLASSLIB_H #include @@ -38,303 +38,268 @@ typedef Vector3 Colour3; class ListAttributeType { - typedef std::pair ListItem; - typedef std::vector ListItems; - ListItems m_items; +typedef std::pair ListItem; +typedef std::vector ListItems; +ListItems m_items; public: - typedef ListItems::const_iterator const_iterator; - const_iterator begin() const - { - return m_items.begin(); - } - const_iterator end() const - { - return m_items.end(); - } - - const ListItem& operator[](std::size_t i) const - { - return m_items[i]; - } - const_iterator findValue(const char* value) const - { - for(ListItems::const_iterator i = m_items.begin(); i != m_items.end(); ++i) - { - if(string_equal(value, (*i).second.c_str())) - { - return i; - } - } - return m_items.end(); - } - - void push_back(const char* name, const char* value) - { - m_items.push_back(ListItems::value_type(name, value)); - } +typedef ListItems::const_iterator const_iterator; +const_iterator begin() const { + return m_items.begin(); +} +const_iterator end() const { + return m_items.end(); +} + +const ListItem& operator[]( std::size_t i ) const { + return m_items[i]; +} +const_iterator findValue( const char* value ) const { + for ( ListItems::const_iterator i = m_items.begin(); i != m_items.end(); ++i ) + { + if ( string_equal( value, ( *i ).second.c_str() ) ) { + return i; + } + } + return m_items.end(); +} + +void push_back( const char* name, const char* value ){ + m_items.push_back( ListItems::value_type( name, value ) ); +} }; class EntityClassAttribute { public: - CopiedString m_type; - CopiedString m_name; - CopiedString m_value; - CopiedString m_description; - EntityClassAttribute() - { - } - EntityClassAttribute(const char* type, const char* name, const char* value = "", const char* description = "") : m_type(type), m_name(name), m_value(value), m_description(description) - { - } +CopiedString m_type; +CopiedString m_name; +CopiedString m_value; +CopiedString m_description; +EntityClassAttribute(){ +} +EntityClassAttribute( const char* type, const char* name, const char* value = "", const char* description = "" ) : m_type( type ), m_name( name ), m_value( value ), m_description( description ){ +} }; typedef std::pair EntityClassAttributePair; typedef std::list EntityClassAttributes; typedef std::list StringList; -inline const char* EntityClassAttributePair_getName(const EntityClassAttributePair& attributePair) -{ - if(!string_empty(attributePair.second.m_name.c_str())) - { - return attributePair.second.m_name.c_str(); - } - return attributePair.first.c_str(); +inline const char* EntityClassAttributePair_getName( const EntityClassAttributePair& attributePair ){ + if ( !string_empty( attributePair.second.m_name.c_str() ) ) { + return attributePair.second.m_name.c_str(); + } + return attributePair.first.c_str(); } -inline const char* EntityClassAttributePair_getDescription(const EntityClassAttributePair& attributePair) -{ - if(!string_empty(attributePair.second.m_description.c_str())) - { - return attributePair.second.m_description.c_str(); - } - return EntityClassAttributePair_getName(attributePair); +inline const char* EntityClassAttributePair_getDescription( const EntityClassAttributePair& attributePair ){ + if ( !string_empty( attributePair.second.m_description.c_str() ) ) { + return attributePair.second.m_description.c_str(); + } + return EntityClassAttributePair_getName( attributePair ); } class EntityClass { public: - CopiedString m_name; - StringList m_parent; - bool fixedsize; - bool unknown; // wasn't found in source - Vector3 mins; - Vector3 maxs; - - Colour3 color; - Shader* m_state_fill; - Shader* m_state_wire; - Shader* m_state_blend; - - CopiedString m_comments; - char flagnames[MAX_FLAGS][32]; - - CopiedString m_modelpath; - CopiedString m_skin; - - void (*free)(EntityClass*); - - EntityClassAttributes m_attributes; - - bool inheritanceResolved; - bool sizeSpecified; - bool colorSpecified; - - const char* name() const - { - return m_name.c_str(); - } - const char* comments() const - { - return m_comments.c_str(); - } - const char* modelpath() const - { - return m_modelpath.c_str(); - } - const char* skin() const - { - return m_skin.c_str(); - } +CopiedString m_name; +StringList m_parent; +bool fixedsize; +bool unknown; // wasn't found in source +Vector3 mins; +Vector3 maxs; + +Colour3 color; +Shader* m_state_fill; +Shader* m_state_wire; +Shader* m_state_blend; + +CopiedString m_comments; +char flagnames[MAX_FLAGS][32]; + +CopiedString m_modelpath; +CopiedString m_skin; + +void ( *free )( EntityClass* ); + +EntityClassAttributes m_attributes; + +bool inheritanceResolved; +bool sizeSpecified; +bool colorSpecified; + +const char* name() const { + return m_name.c_str(); +} +const char* comments() const { + return m_comments.c_str(); +} +const char* modelpath() const { + return m_modelpath.c_str(); +} +const char* skin() const { + return m_skin.c_str(); +} }; -inline const char* EntityClass_valueForKey(const EntityClass& entityClass, const char* key) -{ - for(EntityClassAttributes::const_iterator i = entityClass.m_attributes.begin(); i != entityClass.m_attributes.end(); ++i) - { - if(string_equal(key, (*i).first.c_str())) - { - return (*i).second.m_value.c_str(); - } - } - return ""; +inline const char* EntityClass_valueForKey( const EntityClass& entityClass, const char* key ){ + for ( EntityClassAttributes::const_iterator i = entityClass.m_attributes.begin(); i != entityClass.m_attributes.end(); ++i ) + { + if ( string_equal( key, ( *i ).first.c_str() ) ) { + return ( *i ).second.m_value.c_str(); + } + } + return ""; } -inline EntityClassAttributePair& EntityClass_insertAttribute(EntityClass& entityClass, const char* key, const EntityClassAttribute& attribute = EntityClassAttribute()) -{ - entityClass.m_attributes.push_back(EntityClassAttributePair(key, attribute)); - return entityClass.m_attributes.back(); +inline EntityClassAttributePair& EntityClass_insertAttribute( EntityClass& entityClass, const char* key, const EntityClassAttribute& attribute = EntityClassAttribute() ){ + entityClass.m_attributes.push_back( EntityClassAttributePair( key, attribute ) ); + return entityClass.m_attributes.back(); } -inline void buffer_write_colour_fill(char buffer[128], const Colour3& colour) -{ - sprintf(buffer, "(%g %g %g)", colour[0], colour[1], colour[2]); +inline void buffer_write_colour_fill( char buffer[128], const Colour3& colour ){ + sprintf( buffer, "(%g %g %g)", colour[0], colour[1], colour[2] ); } -inline void buffer_write_colour_wire(char buffer[128], const Colour3& colour) -{ - sprintf(buffer, "<%g %g %g>", colour[0], colour[1], colour[2]); +inline void buffer_write_colour_wire( char buffer[128], const Colour3& colour ){ + sprintf( buffer, "<%g %g %g>", colour[0], colour[1], colour[2] ); } -inline void buffer_write_colour_blend(char buffer[128], const Colour3& colour) -{ - sprintf(buffer, "[%g %g %g]", colour[0], colour[1], colour[2]); +inline void buffer_write_colour_blend( char buffer[128], const Colour3& colour ){ + sprintf( buffer, "[%g %g %g]", colour[0], colour[1], colour[2] ); } -inline Shader* colour_capture_state_fill(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_fill(buffer, colour); - return GlobalShaderCache().capture(buffer); +inline Shader* colour_capture_state_fill( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_fill( buffer, colour ); + return GlobalShaderCache().capture( buffer ); } -inline void colour_release_state_fill(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_fill(buffer, colour); - GlobalShaderCache().release(buffer); +inline void colour_release_state_fill( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_fill( buffer, colour ); + GlobalShaderCache().release( buffer ); } -inline Shader* colour_capture_state_wire(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_wire(buffer, colour); - return GlobalShaderCache().capture(buffer); +inline Shader* colour_capture_state_wire( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_wire( buffer, colour ); + return GlobalShaderCache().capture( buffer ); } -inline void colour_release_state_wire(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_wire(buffer, colour); - GlobalShaderCache().release(buffer); +inline void colour_release_state_wire( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_wire( buffer, colour ); + GlobalShaderCache().release( buffer ); } -inline Shader* colour_capture_state_blend(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_blend(buffer, colour); - return GlobalShaderCache().capture(buffer); +inline Shader* colour_capture_state_blend( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_blend( buffer, colour ); + return GlobalShaderCache().capture( buffer ); } -inline void colour_release_state_blend(const Colour3& colour) -{ - char buffer[128]; - buffer_write_colour_blend(buffer, colour); - GlobalShaderCache().release(buffer); +inline void colour_release_state_blend( const Colour3& colour ){ + char buffer[128]; + buffer_write_colour_blend( buffer, colour ); + GlobalShaderCache().release( buffer ); } -inline void eclass_capture_state(EntityClass* eclass) -{ - eclass->m_state_fill = colour_capture_state_fill(eclass->color); - eclass->m_state_wire = colour_capture_state_wire(eclass->color); - eclass->m_state_blend = colour_capture_state_blend(eclass->color); +inline void eclass_capture_state( EntityClass* eclass ){ + eclass->m_state_fill = colour_capture_state_fill( eclass->color ); + eclass->m_state_wire = colour_capture_state_wire( eclass->color ); + eclass->m_state_blend = colour_capture_state_blend( eclass->color ); } -inline void eclass_release_state(EntityClass* eclass) -{ - colour_release_state_fill(eclass->color); - colour_release_state_wire(eclass->color); - colour_release_state_blend(eclass->color); +inline void eclass_release_state( EntityClass* eclass ){ + colour_release_state_fill( eclass->color ); + colour_release_state_wire( eclass->color ); + colour_release_state_blend( eclass->color ); } // eclass constructor -inline EntityClass* Eclass_Alloc() -{ - EntityClass* e = new EntityClass; +inline EntityClass* Eclass_Alloc(){ + EntityClass* e = new EntityClass; - e->fixedsize = false; - e->unknown = false; - memset(e->flagnames, 0, MAX_FLAGS*32); + e->fixedsize = false; + e->unknown = false; + memset( e->flagnames, 0, MAX_FLAGS * 32 ); - e->maxs = Vector3(-1,-1,-1); - e->mins = Vector3(1, 1, 1); + e->maxs = Vector3( -1,-1,-1 ); + e->mins = Vector3( 1, 1, 1 ); - e->free = 0; + e->free = 0; - e->inheritanceResolved = true; - e->sizeSpecified = false; - e->colorSpecified = false; + e->inheritanceResolved = true; + e->sizeSpecified = false; + e->colorSpecified = false; - return e; + return e; } // eclass destructor -inline void Eclass_Free(EntityClass* e) -{ - eclass_release_state(e); +inline void Eclass_Free( EntityClass* e ){ + eclass_release_state( e ); - delete e; + delete e; } -inline bool classname_equal(const char* classname, const char* other) -{ - return string_equal(classname, other); +inline bool classname_equal( const char* classname, const char* other ){ + return string_equal( classname, other ); } -inline EntityClass* EClass_Create(const char* name, const Vector3& colour, const char* comments) -{ - EntityClass *e = Eclass_Alloc(); - e->free = &Eclass_Free; +inline EntityClass* EClass_Create( const char* name, const Vector3& colour, const char* comments ){ + EntityClass *e = Eclass_Alloc(); + e->free = &Eclass_Free; - e->m_name = name; + e->m_name = name; e->color = colour; - eclass_capture_state(e); + eclass_capture_state( e ); - if (comments) - e->m_comments = comments; + if ( comments ) { + e->m_comments = comments; + } - return e; + return e; } -inline EntityClass* EClass_Create_FixedSize(const char* name, const Vector3& colour, const Vector3& mins, const Vector3& maxs, const char* comments) -{ - EntityClass *e = Eclass_Alloc(); - e->free = &Eclass_Free; +inline EntityClass* EClass_Create_FixedSize( const char* name, const Vector3& colour, const Vector3& mins, const Vector3& maxs, const char* comments ){ + EntityClass *e = Eclass_Alloc(); + e->free = &Eclass_Free; - e->m_name = name; + e->m_name = name; e->color = colour; - eclass_capture_state(e); + eclass_capture_state( e ); - e->fixedsize = true; + e->fixedsize = true; - e->mins = mins; - e->maxs = maxs; + e->mins = mins; + e->maxs = maxs; - if (comments) - e->m_comments = comments; + if ( comments ) { + e->m_comments = comments; + } - return e; + return e; } const Vector3 smallbox[2] = { - Vector3(-8,-8,-8), - Vector3( 8, 8, 8), + Vector3( -8,-8,-8 ), + Vector3( 8, 8, 8 ), }; -inline EntityClass *EntityClass_Create_Default(const char *name, bool has_brushes) -{ +inline EntityClass *EntityClass_Create_Default( const char *name, bool has_brushes ){ // create a new class for it - if (has_brushes) - { - return EClass_Create(name, Vector3(0.0f, 0.5f, 0.0f), "Not found in source."); + if ( has_brushes ) { + return EClass_Create( name, Vector3( 0.0f, 0.5f, 0.0f ), "Not found in source." ); } else { - return EClass_Create_FixedSize(name, Vector3(0.0f, 0.5f, 0.0f), smallbox[0], smallbox[1], "Not found in source."); + return EClass_Create_FixedSize( name, Vector3( 0.0f, 0.5f, 0.0f ), smallbox[0], smallbox[1], "Not found in source." ); } } diff --git a/libs/entitylib.cpp b/libs/entitylib.cpp index 385d0f2e..48f3138e 100644 --- a/libs/entitylib.cpp +++ b/libs/entitylib.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "entitylib.h" diff --git a/libs/entitylib.h b/libs/entitylib.h index 667adf72..7f1bb0c1 100644 --- a/libs/entitylib.h +++ b/libs/entitylib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_ENTITYLIB_H) +#if !defined ( INCLUDED_ENTITYLIB_H ) #define INCLUDED_ENTITYLIB_H #include "ireference.h" @@ -43,262 +43,247 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include #include -inline void arrow_draw(const Vector3& origin, const Vector3& direction_forward, const Vector3& direction_left, const Vector3& direction_up) -{ - Vector3 endpoint(vector3_added(origin, vector3_scaled(direction_forward, 32.0))); +inline void arrow_draw( const Vector3& origin, const Vector3& direction_forward, const Vector3& direction_left, const Vector3& direction_up ){ + Vector3 endpoint( vector3_added( origin, vector3_scaled( direction_forward, 32.0 ) ) ); - Vector3 tip1(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_up, -4.0))); - Vector3 tip2(vector3_added(tip1, vector3_scaled(direction_up, 8.0))); - Vector3 tip3(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_left, -4.0))); - Vector3 tip4(vector3_added(tip3, vector3_scaled(direction_left, 8.0))); + Vector3 tip1( vector3_added( vector3_added( endpoint, vector3_scaled( direction_forward, -8.0 ) ), vector3_scaled( direction_up, -4.0 ) ) ); + Vector3 tip2( vector3_added( tip1, vector3_scaled( direction_up, 8.0 ) ) ); + Vector3 tip3( vector3_added( vector3_added( endpoint, vector3_scaled( direction_forward, -8.0 ) ), vector3_scaled( direction_left, -4.0 ) ) ); + Vector3 tip4( vector3_added( tip3, vector3_scaled( direction_left, 8.0 ) ) ); - glBegin (GL_LINES); + glBegin( GL_LINES ); - glVertex3fv(vector3_to_array(origin)); - glVertex3fv(vector3_to_array(endpoint)); + glVertex3fv( vector3_to_array( origin ) ); + glVertex3fv( vector3_to_array( endpoint ) ); - glVertex3fv(vector3_to_array(endpoint)); - glVertex3fv(vector3_to_array(tip1)); + glVertex3fv( vector3_to_array( endpoint ) ); + glVertex3fv( vector3_to_array( tip1 ) ); - glVertex3fv(vector3_to_array(endpoint)); - glVertex3fv(vector3_to_array(tip2)); + glVertex3fv( vector3_to_array( endpoint ) ); + glVertex3fv( vector3_to_array( tip2 ) ); - glVertex3fv(vector3_to_array(endpoint)); - glVertex3fv(vector3_to_array(tip3)); + glVertex3fv( vector3_to_array( endpoint ) ); + glVertex3fv( vector3_to_array( tip3 ) ); - glVertex3fv(vector3_to_array(endpoint)); - glVertex3fv(vector3_to_array(tip4)); + glVertex3fv( vector3_to_array( endpoint ) ); + glVertex3fv( vector3_to_array( tip4 ) ); - glVertex3fv(vector3_to_array(tip1)); - glVertex3fv(vector3_to_array(tip3)); + glVertex3fv( vector3_to_array( tip1 ) ); + glVertex3fv( vector3_to_array( tip3 ) ); - glVertex3fv(vector3_to_array(tip3)); - glVertex3fv(vector3_to_array(tip2)); + glVertex3fv( vector3_to_array( tip3 ) ); + glVertex3fv( vector3_to_array( tip2 ) ); - glVertex3fv(vector3_to_array(tip2)); - glVertex3fv(vector3_to_array(tip4)); + glVertex3fv( vector3_to_array( tip2 ) ); + glVertex3fv( vector3_to_array( tip4 ) ); - glVertex3fv(vector3_to_array(tip4)); - glVertex3fv(vector3_to_array(tip1)); + glVertex3fv( vector3_to_array( tip4 ) ); + glVertex3fv( vector3_to_array( tip1 ) ); - glEnd(); + glEnd(); } class SelectionIntersection; -inline void aabb_testselect(const AABB& aabb, SelectionTest& test, SelectionIntersection& best) -{ - const IndexPointer::index_type indices[24] = { - 2, 1, 5, 6, - 1, 0, 4, 5, - 0, 1, 2, 3, - 3, 7, 4, 0, - 3, 2, 6, 7, - 7, 6, 5, 4, - }; - - Vector3 points[8]; - aabb_corners(aabb, points); - test.TestQuads(VertexPointer(reinterpret_cast(points), sizeof(Vector3)), IndexPointer(indices, 24), best); +inline void aabb_testselect( const AABB& aabb, SelectionTest& test, SelectionIntersection& best ){ + const IndexPointer::index_type indices[24] = { + 2, 1, 5, 6, + 1, 0, 4, 5, + 0, 1, 2, 3, + 3, 7, 4, 0, + 3, 2, 6, 7, + 7, 6, 5, 4, + }; + + Vector3 points[8]; + aabb_corners( aabb, points ); + test.TestQuads( VertexPointer( reinterpret_cast( points ), sizeof( Vector3 ) ), IndexPointer( indices, 24 ), best ); } -inline void aabb_draw_wire(const Vector3 points[8]) -{ - unsigned int indices[26] = { - 0, 1, 1, 2, 2, 3, 3, 0, - 4, 5, 5, 6, 6, 7, 7, 4, - 0, 4, 1, 5, 2, 6, 3, 7, - // 0, 6, 1, 7, 2, 4, 3, 5 // X cross - 1, 7 // diagonal line (connect mins to maxs corner) - }; +inline void aabb_draw_wire( const Vector3 points[8] ){ + unsigned int indices[26] = { + 0, 1, 1, 2, 2, 3, 3, 0, + 4, 5, 5, 6, 6, 7, 7, 4, + 0, 4, 1, 5, 2, 6, 3, 7, + // 0, 6, 1, 7, 2, 4, 3, 5 // X cross + 1, 7 // diagonal line (connect mins to maxs corner) + }; #if 1 - glVertexPointer(3, GL_FLOAT, 0, points); - glDrawElements(GL_LINES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_INT, indices); + glVertexPointer( 3, GL_FLOAT, 0, points ); + glDrawElements( GL_LINES, sizeof( indices ) / sizeof( indices[0] ), GL_UNSIGNED_INT, indices ); #else - glBegin(GL_LINES); - for(std::size_t i = 0; i < sizeof(indices)/sizeof(indices[0]); ++i) - { - glVertex3fv(points[indices[i]]); - } - glEnd(); + glBegin( GL_LINES ); + for ( std::size_t i = 0; i < sizeof( indices ) / sizeof( indices[0] ); ++i ) + { + glVertex3fv( points[indices[i]] ); + } + glEnd(); #endif } -inline void aabb_draw_flatshade(const Vector3 points[8]) -{ - glBegin(GL_QUADS); - - glNormal3fv(vector3_to_array(aabb_normals[0])); - glVertex3fv(vector3_to_array(points[2])); - glVertex3fv(vector3_to_array(points[1])); - glVertex3fv(vector3_to_array(points[5])); - glVertex3fv(vector3_to_array(points[6])); - - glNormal3fv(vector3_to_array(aabb_normals[1])); - glVertex3fv(vector3_to_array(points[1])); - glVertex3fv(vector3_to_array(points[0])); - glVertex3fv(vector3_to_array(points[4])); - glVertex3fv(vector3_to_array(points[5])); - - glNormal3fv(vector3_to_array(aabb_normals[2])); - glVertex3fv(vector3_to_array(points[0])); - glVertex3fv(vector3_to_array(points[1])); - glVertex3fv(vector3_to_array(points[2])); - glVertex3fv(vector3_to_array(points[3])); - - glNormal3fv(vector3_to_array(aabb_normals[3])); - glVertex3fv(vector3_to_array(points[0])); - glVertex3fv(vector3_to_array(points[3])); - glVertex3fv(vector3_to_array(points[7])); - glVertex3fv(vector3_to_array(points[4])); - - glNormal3fv(vector3_to_array(aabb_normals[4])); - glVertex3fv(vector3_to_array(points[3])); - glVertex3fv(vector3_to_array(points[2])); - glVertex3fv(vector3_to_array(points[6])); - glVertex3fv(vector3_to_array(points[7])); - - glNormal3fv(vector3_to_array(aabb_normals[5])); - glVertex3fv(vector3_to_array(points[7])); - glVertex3fv(vector3_to_array(points[6])); - glVertex3fv(vector3_to_array(points[5])); - glVertex3fv(vector3_to_array(points[4])); - - glEnd(); +inline void aabb_draw_flatshade( const Vector3 points[8] ){ + glBegin( GL_QUADS ); + + glNormal3fv( vector3_to_array( aabb_normals[0] ) ); + glVertex3fv( vector3_to_array( points[2] ) ); + glVertex3fv( vector3_to_array( points[1] ) ); + glVertex3fv( vector3_to_array( points[5] ) ); + glVertex3fv( vector3_to_array( points[6] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[1] ) ); + glVertex3fv( vector3_to_array( points[1] ) ); + glVertex3fv( vector3_to_array( points[0] ) ); + glVertex3fv( vector3_to_array( points[4] ) ); + glVertex3fv( vector3_to_array( points[5] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[2] ) ); + glVertex3fv( vector3_to_array( points[0] ) ); + glVertex3fv( vector3_to_array( points[1] ) ); + glVertex3fv( vector3_to_array( points[2] ) ); + glVertex3fv( vector3_to_array( points[3] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[3] ) ); + glVertex3fv( vector3_to_array( points[0] ) ); + glVertex3fv( vector3_to_array( points[3] ) ); + glVertex3fv( vector3_to_array( points[7] ) ); + glVertex3fv( vector3_to_array( points[4] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[4] ) ); + glVertex3fv( vector3_to_array( points[3] ) ); + glVertex3fv( vector3_to_array( points[2] ) ); + glVertex3fv( vector3_to_array( points[6] ) ); + glVertex3fv( vector3_to_array( points[7] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[5] ) ); + glVertex3fv( vector3_to_array( points[7] ) ); + glVertex3fv( vector3_to_array( points[6] ) ); + glVertex3fv( vector3_to_array( points[5] ) ); + glVertex3fv( vector3_to_array( points[4] ) ); + + glEnd(); } -inline void aabb_draw_wire(const AABB& aabb) -{ - Vector3 points[8]; - aabb_corners(aabb, points); - aabb_draw_wire(points); +inline void aabb_draw_wire( const AABB& aabb ){ + Vector3 points[8]; + aabb_corners( aabb, points ); + aabb_draw_wire( points ); } -inline void aabb_draw_flatshade(const AABB& aabb) -{ - Vector3 points[8]; - aabb_corners(aabb, points); - aabb_draw_flatshade(points); +inline void aabb_draw_flatshade( const AABB& aabb ){ + Vector3 points[8]; + aabb_corners( aabb, points ); + aabb_draw_flatshade( points ); } -inline void aabb_draw_textured(const AABB& aabb) -{ - Vector3 points[8]; - aabb_corners(aabb, points); - - glBegin(GL_QUADS); - - glNormal3fv(vector3_to_array(aabb_normals[0])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[2])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[1])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[5])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[6])); - - glNormal3fv(vector3_to_array(aabb_normals[1])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[1])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[0])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[4])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[5])); - - glNormal3fv(vector3_to_array(aabb_normals[2])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[0])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[1])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[2])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[3])); - - glNormal3fv(vector3_to_array(aabb_normals[3])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[0])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[3])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[7])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[4])); - - glNormal3fv(vector3_to_array(aabb_normals[4])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[3])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[2])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[6])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[7])); - - glNormal3fv(vector3_to_array(aabb_normals[5])); - glTexCoord2fv(aabb_texcoord_topleft); - glVertex3fv(vector3_to_array(points[7])); - glTexCoord2fv(aabb_texcoord_topright); - glVertex3fv(vector3_to_array(points[6])); - glTexCoord2fv(aabb_texcoord_botright); - glVertex3fv(vector3_to_array(points[5])); - glTexCoord2fv(aabb_texcoord_botleft); - glVertex3fv(vector3_to_array(points[4])); - - glEnd(); +inline void aabb_draw_textured( const AABB& aabb ){ + Vector3 points[8]; + aabb_corners( aabb, points ); + + glBegin( GL_QUADS ); + + glNormal3fv( vector3_to_array( aabb_normals[0] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[2] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[1] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[5] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[6] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[1] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[1] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[0] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[4] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[5] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[2] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[0] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[1] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[2] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[3] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[3] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[0] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[3] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[7] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[4] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[4] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[3] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[2] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[6] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[7] ) ); + + glNormal3fv( vector3_to_array( aabb_normals[5] ) ); + glTexCoord2fv( aabb_texcoord_topleft ); + glVertex3fv( vector3_to_array( points[7] ) ); + glTexCoord2fv( aabb_texcoord_topright ); + glVertex3fv( vector3_to_array( points[6] ) ); + glTexCoord2fv( aabb_texcoord_botright ); + glVertex3fv( vector3_to_array( points[5] ) ); + glTexCoord2fv( aabb_texcoord_botleft ); + glVertex3fv( vector3_to_array( points[4] ) ); + + glEnd(); } -inline void aabb_draw_solid(const AABB& aabb, RenderStateFlags state) -{ - if(state & RENDER_TEXTURE) - { - aabb_draw_textured(aabb); - } - else - { - aabb_draw_flatshade(aabb); - } +inline void aabb_draw_solid( const AABB& aabb, RenderStateFlags state ){ + if ( state & RENDER_TEXTURE ) { + aabb_draw_textured( aabb ); + } + else + { + aabb_draw_flatshade( aabb ); + } } -inline void aabb_draw(const AABB& aabb, RenderStateFlags state) -{ - if(state & RENDER_FILL) - { - aabb_draw_solid(aabb, state); - } - else - { - aabb_draw_wire(aabb); - } +inline void aabb_draw( const AABB& aabb, RenderStateFlags state ){ + if ( state & RENDER_FILL ) { + aabb_draw_solid( aabb, state ); + } + else + { + aabb_draw_wire( aabb ); + } } class RenderableSolidAABB : public OpenGLRenderable { - const AABB& m_aabb; +const AABB& m_aabb; public: - RenderableSolidAABB(const AABB& aabb) : m_aabb(aabb) - { - } - void render(RenderStateFlags state) const - { - aabb_draw_solid(m_aabb, state); - } +RenderableSolidAABB( const AABB& aabb ) : m_aabb( aabb ){ +} +void render( RenderStateFlags state ) const { + aabb_draw_solid( m_aabb, state ); +} }; class RenderableWireframeAABB : public OpenGLRenderable { - const AABB& m_aabb; +const AABB& m_aabb; public: - RenderableWireframeAABB(const AABB& aabb) : m_aabb(aabb) - { - } - void render(RenderStateFlags state) const - { - aabb_draw_wire(m_aabb); - } +RenderableWireframeAABB( const AABB& aabb ) : m_aabb( aabb ){ +} +void render( RenderStateFlags state ) const { + aabb_draw_wire( m_aabb ); +} }; @@ -308,96 +293,80 @@ public: /// - Provides undo support through the global undo system. class KeyValue : public EntityKeyValue { - typedef UnsortedSet KeyObservers; - - std::size_t m_refcount; - KeyObservers m_observers; - CopiedString m_string; - const char* m_empty; - ObservedUndoableObject m_undo; - static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; +typedef UnsortedSet KeyObservers; + +std::size_t m_refcount; +KeyObservers m_observers; +CopiedString m_string; +const char* m_empty; +ObservedUndoableObject m_undo; +static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; public: - KeyValue(const char* string, const char* empty) - : m_refcount(0), m_string(string), m_empty(empty), m_undo(m_string, UndoImportCaller(*this)) - { - notify(); - } - ~KeyValue() - { - ASSERT_MESSAGE(m_observers.empty(), "KeyValue::~KeyValue: observers still attached"); - } - - static void setKeyValueChangedFunc(EntityCreator::KeyValueChangedFunc func) - { - m_entityKeyValueChanged = func; - } - - void IncRef() - { - ++m_refcount; - } - void DecRef() - { - if(--m_refcount == 0) - { - delete this; - } - } - - void instanceAttach(MapFile* map) - { - m_undo.instanceAttach(map); - } - void instanceDetach(MapFile* map) - { - m_undo.instanceDetach(map); - } - - void attach(const KeyObserver& observer) - { - (*m_observers.insert(observer))(c_str()); - } - void detach(const KeyObserver& observer) - { - observer(m_empty); - m_observers.erase(observer); - } - const char* c_str() const - { - if(string_empty(m_string.c_str())) - { - return m_empty; - } - return m_string.c_str(); - } - void assign(const char* other) - { - if(!string_equal(m_string.c_str(), other)) - { - m_undo.save(); - m_string = other; - notify(); - } - } - - void notify() - { - m_entityKeyValueChanged(); - KeyObservers::reverse_iterator i = m_observers.rbegin(); - while(i != m_observers.rend()) - { - (*i++)(c_str()); - } - } - - void importState(const CopiedString& string) - { - m_string = string; - - notify(); - } - typedef MemberCaller1 UndoImportCaller; +KeyValue( const char* string, const char* empty ) + : m_refcount( 0 ), m_string( string ), m_empty( empty ), m_undo( m_string, UndoImportCaller( *this ) ){ + notify(); +} +~KeyValue(){ + ASSERT_MESSAGE( m_observers.empty(), "KeyValue::~KeyValue: observers still attached" ); +} + +static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ + m_entityKeyValueChanged = func; +} + +void IncRef(){ + ++m_refcount; +} +void DecRef(){ + if ( --m_refcount == 0 ) { + delete this; + } +} + +void instanceAttach( MapFile* map ){ + m_undo.instanceAttach( map ); +} +void instanceDetach( MapFile* map ){ + m_undo.instanceDetach( map ); +} + +void attach( const KeyObserver& observer ){ + ( *m_observers.insert ( observer ) )( c_str() ); +} +void detach( const KeyObserver& observer ){ + observer( m_empty ); + m_observers.erase( observer ); +} +const char* c_str() const { + if ( string_empty( m_string.c_str() ) ) { + return m_empty; + } + return m_string.c_str(); +} +void assign( const char* other ){ + if ( !string_equal( m_string.c_str(), other ) ) { + m_undo.save(); + m_string = other; + notify(); + } +} + +void notify(){ + m_entityKeyValueChanged(); + KeyObservers::reverse_iterator i = m_observers.rbegin(); + while ( i != m_observers.rend() ) + { + ( *i++ )( c_str() ); + } +} + +void importState( const CopiedString& string ){ + m_string = string; + + notify(); +} +typedef MemberCaller1 UndoImportCaller; }; /// \brief An unsorted list of key/value pairs. @@ -408,349 +377,302 @@ public: class EntityKeyValues : public Entity { public: - typedef KeyValue Value; + typedef KeyValue Value; - static StringPool& getPool() - { - return Static::instance(); - } + static StringPool& getPool(){ + return Static::instance(); + } private: - static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; - static Counter* m_counter; - - EntityClass* m_eclass; - - class KeyContext{}; - typedef Static KeyPool; - typedef PooledString Key; - typedef SmartPointer KeyValuePtr; - typedef UnsortedMap KeyValues; - KeyValues m_keyValues; - - typedef UnsortedSet Observers; - Observers m_observers; - - ObservedUndoableObject m_undo; - bool m_instanced; - - bool m_observerMutex; - - void notifyInsert(const char* key, Value& value) - { - m_observerMutex = true; - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->insert(key, value); - } - m_observerMutex = false; - } - void notifyErase(const char* key, Value& value) - { - m_observerMutex = true; - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->erase(key, value); - } - m_observerMutex = false; - } - void forEachKeyValue_notifyInsert() - { - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - notifyInsert((*i).first.c_str(), *(*i).second); - } - } - void forEachKeyValue_notifyErase() - { - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - notifyErase((*i).first.c_str(), *(*i).second); - } - } - - void insert(const char* key, const KeyValuePtr& keyValue) - { - KeyValues::iterator i = m_keyValues.insert(KeyValues::value_type(key, keyValue)); - notifyInsert(key, *(*i).second); - - if(m_instanced) - { - (*i).second->instanceAttach(m_undo.map()); - } - } - - void insert(const char* key, const char* value) - { - KeyValues::iterator i = m_keyValues.find(key); - if(i != m_keyValues.end()) - { - (*i).second->assign(value); - } - else - { - m_undo.save(); - insert(key, KeyValuePtr(new KeyValue(value, EntityClass_valueForKey(*m_eclass, key)))); - } - } - - void erase(KeyValues::iterator i) - { - if(m_instanced) - { - (*i).second->instanceDetach(m_undo.map()); - } - - Key key((*i).first); - KeyValuePtr value((*i).second); - m_keyValues.erase(i); - notifyErase(key.c_str(), *value); - } - - void erase(const char* key) - { - KeyValues::iterator i = m_keyValues.find(key); - if(i != m_keyValues.end()) - { - m_undo.save(); - erase(i); - } - } + static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; + static Counter* m_counter; + + EntityClass* m_eclass; + + class KeyContext {}; + typedef Static KeyPool; + typedef PooledString Key; + typedef SmartPointer KeyValuePtr; + typedef UnsortedMap KeyValues; + KeyValues m_keyValues; + + typedef UnsortedSet Observers; + Observers m_observers; + + ObservedUndoableObject m_undo; + bool m_instanced; + + bool m_observerMutex; + + void notifyInsert( const char* key, Value& value ){ + m_observerMutex = true; + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->insert( key, value ); + } + m_observerMutex = false; + } + void notifyErase( const char* key, Value& value ){ + m_observerMutex = true; + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->erase( key, value ); + } + m_observerMutex = false; + } + void forEachKeyValue_notifyInsert(){ + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + notifyInsert( ( *i ).first.c_str(), *( *i ).second ); + } + } + void forEachKeyValue_notifyErase(){ + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + notifyErase( ( *i ).first.c_str(), *( *i ).second ); + } + } + + void insert( const char* key, const KeyValuePtr& keyValue ){ + KeyValues::iterator i = m_keyValues.insert( KeyValues::value_type( key, keyValue ) ); + notifyInsert( key, *( *i ).second ); + + if ( m_instanced ) { + ( *i ).second->instanceAttach( m_undo.map() ); + } + } + + void insert( const char* key, const char* value ){ + KeyValues::iterator i = m_keyValues.find( key ); + if ( i != m_keyValues.end() ) { + ( *i ).second->assign( value ); + } + else + { + m_undo.save(); + insert( key, KeyValuePtr( new KeyValue( value, EntityClass_valueForKey( *m_eclass, key ) ) ) ); + } + } + + void erase( KeyValues::iterator i ){ + if ( m_instanced ) { + ( *i ).second->instanceDetach( m_undo.map() ); + } + + Key key( ( *i ).first ); + KeyValuePtr value( ( *i ).second ); + m_keyValues.erase( i ); + notifyErase( key.c_str(), *value ); + } + + void erase( const char* key ){ + KeyValues::iterator i = m_keyValues.find( key ); + if ( i != m_keyValues.end() ) { + m_undo.save(); + erase( i ); + } + } public: - bool m_isContainer; - - EntityKeyValues(EntityClass* eclass) : - m_eclass(eclass), - m_undo(m_keyValues, UndoImportCaller(*this)), - m_instanced(false), - m_observerMutex(false), - m_isContainer(!eclass->fixedsize) - { - } - EntityKeyValues(const EntityKeyValues& other) : - Entity(other), - m_eclass(&other.getEntityClass()), - m_undo(m_keyValues, UndoImportCaller(*this)), - m_instanced(false), - m_observerMutex(false), - m_isContainer(other.m_isContainer) - { - for(KeyValues::const_iterator i = other.m_keyValues.begin(); i != other.m_keyValues.end(); ++i) - { - insert((*i).first.c_str(), (*i).second->c_str()); - } - } - ~EntityKeyValues() - { - for(Observers::iterator i = m_observers.begin(); i != m_observers.end();) - { - // post-increment to allow current element to be removed safely - (*i++)->clear(); - } - ASSERT_MESSAGE(m_observers.empty(), "EntityKeyValues::~EntityKeyValues: observers still attached"); - } - - static void setKeyValueChangedFunc(EntityCreator::KeyValueChangedFunc func) - { - m_entityKeyValueChanged = func; - KeyValue::setKeyValueChangedFunc(func); - } - static void setCounter(Counter* counter) - { - m_counter = counter; - } - - void importState(const KeyValues& keyValues) - { - for(KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end();) - { - erase(i++); - } - - for(KeyValues::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i) - { - insert((*i).first.c_str(), (*i).second); - } - - m_entityKeyValueChanged(); - } - typedef MemberCaller1 UndoImportCaller; - - void attach(Observer& observer) - { - ASSERT_MESSAGE(!m_observerMutex, "observer cannot be attached during iteration"); - m_observers.insert(&observer); - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - observer.insert((*i).first.c_str(), *(*i).second); - } - } - void detach(Observer& observer) - { - ASSERT_MESSAGE(!m_observerMutex, "observer cannot be detached during iteration"); - m_observers.erase(&observer); - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - observer.erase((*i).first.c_str(), *(*i).second); - } - } - - void forEachKeyValue_instanceAttach(MapFile* map) - { - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - (*i).second->instanceAttach(map); - } - } - void forEachKeyValue_instanceDetach(MapFile* map) - { - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - (*i).second->instanceDetach(map); - } - } - - void instanceAttach(MapFile* map) - { - if(m_counter != 0) - { - m_counter->increment(); - } - - m_instanced = true; - forEachKeyValue_instanceAttach(map); - m_undo.instanceAttach(map); - } - void instanceDetach(MapFile* map) - { - if(m_counter != 0) - { - m_counter->decrement(); - } - - m_undo.instanceDetach(map); - forEachKeyValue_instanceDetach(map); - m_instanced = false; - } - - // entity - EntityClass& getEntityClass() const - { - return *m_eclass; - } - void forEachKeyValue(Visitor& visitor) const - { - for(KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i) - { - visitor.visit((*i).first.c_str(), (*i).second->c_str()); - } - } - void setKeyValue(const char* key, const char* value) - { - if(value[0] == '\0' - /*|| string_equal(EntityClass_valueForKey(*m_eclass, key), value)*/) // don't delete values equal to default - { - erase(key); - } - else - { - insert(key, value); - } - m_entityKeyValueChanged(); - } - const char* getKeyValue(const char* key) const - { - KeyValues::const_iterator i = m_keyValues.find(key); - if(i != m_keyValues.end()) - { - return (*i).second->c_str(); - } - - return EntityClass_valueForKey(*m_eclass, key); - } - - bool isContainer() const - { - return m_isContainer; - } + bool m_isContainer; + + EntityKeyValues( EntityClass* eclass ) : + m_eclass( eclass ), + m_undo( m_keyValues, UndoImportCaller( *this ) ), + m_instanced( false ), + m_observerMutex( false ), + m_isContainer( !eclass->fixedsize ){ + } + EntityKeyValues( const EntityKeyValues& other ) : + Entity( other ), + m_eclass( &other.getEntityClass() ), + m_undo( m_keyValues, UndoImportCaller( *this ) ), + m_instanced( false ), + m_observerMutex( false ), + m_isContainer( other.m_isContainer ){ + for ( KeyValues::const_iterator i = other.m_keyValues.begin(); i != other.m_keyValues.end(); ++i ) + { + insert( ( *i ).first.c_str(), ( *i ).second->c_str() ); + } + } + ~EntityKeyValues(){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ) + { + // post-increment to allow current element to be removed safely + ( *i++ )->clear(); + } + ASSERT_MESSAGE( m_observers.empty(), "EntityKeyValues::~EntityKeyValues: observers still attached" ); + } + + static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ + m_entityKeyValueChanged = func; + KeyValue::setKeyValueChangedFunc( func ); + } + static void setCounter( Counter* counter ){ + m_counter = counter; + } + + void importState( const KeyValues& keyValues ){ + for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ) + { + erase( i++ ); + } + + for ( KeyValues::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i ) + { + insert( ( *i ).first.c_str(), ( *i ).second ); + } + + m_entityKeyValueChanged(); + } + typedef MemberCaller1 UndoImportCaller; + + void attach( Observer& observer ){ + ASSERT_MESSAGE( !m_observerMutex, "observer cannot be attached during iteration" ); + m_observers.insert( &observer ); + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + observer.insert( ( *i ).first.c_str(), *( *i ).second ); + } + } + void detach( Observer& observer ){ + ASSERT_MESSAGE( !m_observerMutex, "observer cannot be detached during iteration" ); + m_observers.erase( &observer ); + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + observer.erase( ( *i ).first.c_str(), *( *i ).second ); + } + } + + void forEachKeyValue_instanceAttach( MapFile* map ){ + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + ( *i ).second->instanceAttach( map ); + } + } + void forEachKeyValue_instanceDetach( MapFile* map ){ + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + ( *i ).second->instanceDetach( map ); + } + } + + void instanceAttach( MapFile* map ){ + if ( m_counter != 0 ) { + m_counter->increment(); + } + + m_instanced = true; + forEachKeyValue_instanceAttach( map ); + m_undo.instanceAttach( map ); + } + void instanceDetach( MapFile* map ){ + if ( m_counter != 0 ) { + m_counter->decrement(); + } + + m_undo.instanceDetach( map ); + forEachKeyValue_instanceDetach( map ); + m_instanced = false; + } + + // entity + EntityClass& getEntityClass() const { + return *m_eclass; + } + void forEachKeyValue( Visitor& visitor ) const { + for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) + { + visitor.visit( ( *i ).first.c_str(), ( *i ).second->c_str() ); + } + } + void setKeyValue( const char* key, const char* value ){ + if ( value[0] == '\0' + /*|| string_equal(EntityClass_valueForKey(*m_eclass, key), value)*/ ) { // don't delete values equal to default + erase( key ); + } + else + { + insert( key, value ); + } + m_entityKeyValueChanged(); + } + const char* getKeyValue( const char* key ) const { + KeyValues::const_iterator i = m_keyValues.find( key ); + if ( i != m_keyValues.end() ) { + return ( *i ).second->c_str(); + } + + return EntityClass_valueForKey( *m_eclass, key ); + } + + bool isContainer() const { + return m_isContainer; + } }; /// \brief A Resource reference with a controlled lifetime. /// \brief The resource is released when the ResourceReference is destroyed. class ResourceReference { - CopiedString m_name; - Resource* m_resource; + CopiedString m_name; + Resource* m_resource; public: - ResourceReference(const char* name) - : m_name(name) - { - capture(); - } - ResourceReference(const ResourceReference& other) - : m_name(other.m_name) - { - capture(); - } - ResourceReference& operator=(const ResourceReference& other) - { - ResourceReference tmp(other); - tmp.swap(*this); - return *this; - } - ~ResourceReference() - { - release(); - } - - void capture() - { - m_resource = GlobalReferenceCache().capture(m_name.c_str()); - } - void release() - { - GlobalReferenceCache().release(m_name.c_str()); - } - - const char* getName() const - { - return m_name.c_str(); - } - void setName(const char* name) - { - ResourceReference tmp(name); - tmp.swap(*this); - } - - void swap(ResourceReference& other) - { - std::swap(m_resource, other.m_resource); - std::swap(m_name, other.m_name); - } - - void attach(ModuleObserver& observer) - { - m_resource->attach(observer); - } - void detach(ModuleObserver& observer) - { - m_resource->detach(observer); - } - - Resource* get() - { - return m_resource; - } + ResourceReference( const char* name ) + : m_name( name ){ + capture(); + } + ResourceReference( const ResourceReference& other ) + : m_name( other.m_name ){ + capture(); + } + ResourceReference& operator=( const ResourceReference& other ){ + ResourceReference tmp( other ); + tmp.swap( *this ); + return *this; + } + ~ResourceReference(){ + release(); + } + + void capture(){ + m_resource = GlobalReferenceCache().capture( m_name.c_str() ); + } + void release(){ + GlobalReferenceCache().release( m_name.c_str() ); + } + + const char* getName() const { + return m_name.c_str(); + } + void setName( const char* name ){ + ResourceReference tmp( name ); + tmp.swap( *this ); + } + + void swap( ResourceReference& other ){ + std::swap( m_resource, other.m_resource ); + std::swap( m_name, other.m_name ); + } + + void attach( ModuleObserver& observer ){ + m_resource->attach( observer ); + } + void detach( ModuleObserver& observer ){ + m_resource->detach( observer ); + } + + Resource* get(){ + return m_resource; + } }; namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - inline void swap(ResourceReference& self, ResourceReference& other) - { - self.swap(other); - } + /// \brief Swaps the values of \p self and \p other. + /// Overloads std::swap. + inline void swap( ResourceReference& self, ResourceReference& other ){ + self.swap( other ); + } } #endif diff --git a/libs/entityxml.cpp b/libs/entityxml.cpp index 175c4818..13b74088 100644 --- a/libs/entityxml.cpp +++ b/libs/entityxml.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "entityxml.h" diff --git a/libs/entityxml.h b/libs/entityxml.h index 50df739b..89a9406f 100644 --- a/libs/entityxml.h +++ b/libs/entityxml.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_ENTITYXML_H) +#if !defined( INCLUDED_ENTITYXML_H ) #define INCLUDED_ENTITYXML_H #include "ientity.h" @@ -28,79 +28,69 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class entity_import : public XMLImporter { - Entity& m_entity; +Entity& m_entity; public: - entity_import(Entity& entity) - : m_entity(entity) - { - } - void pushElement(const XMLElement& element) - { - if(strcmp(element.name(), "epair") == 0) - m_entity.setKeyValue(element.attribute("key"), element.attribute("value")); - } - void popElement(const char* name) - { - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } +entity_import( Entity& entity ) + : m_entity( entity ){ +} +void pushElement( const XMLElement& element ){ + if ( strcmp( element.name(), "epair" ) == 0 ) { + m_entity.setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); + } +} +void popElement( const char* name ){ +} +std::size_t write( const char* data, std::size_t length ){ + return length; +} }; class entity_export : public XMLExporter { - class ExportXMLVisitor : public Entity::Visitor - { - XMLImporter& m_importer; - public: - ExportXMLVisitor(XMLImporter& importer) : m_importer(importer) - { - } - void visit(const char* key, const char* value) - { - StaticElement element("epair"); - element.insertAttribute("key", key); - element.insertAttribute("value", value); - m_importer.pushElement(element); - m_importer.popElement(element.name()); - } - }; - - const Entity& m_entity; +class ExportXMLVisitor : public Entity::Visitor +{ +XMLImporter& m_importer; +public: +ExportXMLVisitor( XMLImporter& importer ) : m_importer( importer ){ +} +void visit( const char* key, const char* value ){ + StaticElement element( "epair" ); + element.insertAttribute( "key", key ); + element.insertAttribute( "value", value ); + m_importer.pushElement( element ); + m_importer.popElement( element.name() ); +} +}; + +const Entity& m_entity; public: - entity_export(const Entity& entity) : m_entity(entity) - { - } - void exportXML(XMLImporter& observer) - { - ExportXMLVisitor visitor(observer); - - m_entity.forEachKeyValue(visitor); - } +entity_export( const Entity& entity ) : m_entity( entity ){ +} +void exportXML( XMLImporter& observer ){ + ExportXMLVisitor visitor( observer ); + + m_entity.forEachKeyValue( visitor ); +} }; -inline void entity_copy(Entity& entity, const Entity& other) -{ - entity_export exporter(other); - entity_import importer(entity); - exporter.exportXML(importer); +inline void entity_copy( Entity& entity, const Entity& other ){ + entity_export exporter( other ); + entity_import importer( entity ); + exporter.exportXML( importer ); } template class EntityConstruction { public: - typedef EntityClass* type; - static type get(const EntityType& entity) - { - return &entity.getEntity().getEntityClass(); - } - static void copy(EntityType& entity, const EntityType& other) - { - entity_copy(entity.getEntity(), other.getEntity()); - } +typedef EntityClass* type; +static type get( const EntityType& entity ){ + return &entity.getEntity().getEntityClass(); +} +static void copy( EntityType& entity, const EntityType& other ){ + entity_copy( entity.getEntity(), other.getEntity() ); +} }; diff --git a/libs/filematch.c b/libs/filematch.c index 7989cbb2..5b01db73 100644 --- a/libs/filematch.c +++ b/libs/filematch.c @@ -3,67 +3,72 @@ // LordHavoc: some portable directory listing code I wrote for lmp2pcx, now used in darkplaces to load id1/*.pak and such... -int matchpattern(const char *in, const char *pattern, int caseinsensitive) -{ - return matchpattern_with_separator(in, pattern, caseinsensitive, "/\\:", 0); +int matchpattern( const char *in, const char *pattern, int caseinsensitive ){ + return matchpattern_with_separator( in, pattern, caseinsensitive, "/\\:", 0 ); } // wildcard_least_one: if true * matches 1 or more characters // if false * matches 0 or more characters -int matchpattern_with_separator(const char *in, const char *pattern, int caseinsensitive, const char *separators, int wildcard_least_one) -{ +int matchpattern_with_separator( const char *in, const char *pattern, int caseinsensitive, const char *separators, int wildcard_least_one ){ int c1, c2; - while (*pattern) + while ( *pattern ) { - switch (*pattern) + switch ( *pattern ) { case 0: return 1; // end of pattern case '?': // match any single character - if (*in == 0 || strchr(separators, *in)) + if ( *in == 0 || strchr( separators, *in ) ) { return 0; // no match + } in++; pattern++; break; case '*': // match anything until following string - if(wildcard_least_one) - { - if (*in == 0 || strchr(separators, *in)) + if ( wildcard_least_one ) { + if ( *in == 0 || strchr( separators, *in ) ) { return 0; // no match + } in++; } pattern++; - while (*in) + while ( *in ) { - if (strchr(separators, *in)) + if ( strchr( separators, *in ) ) { break; + } // see if pattern matches at this offset - if (matchpattern_with_separator(in, pattern, caseinsensitive, separators, wildcard_least_one)) + if ( matchpattern_with_separator( in, pattern, caseinsensitive, separators, wildcard_least_one ) ) { return 1; + } // nope, advance to next offset in++; } break; default: - if (*in != *pattern) - { - if (!caseinsensitive) + if ( *in != *pattern ) { + if ( !caseinsensitive ) { return 0; // no match + } c1 = *in; - if (c1 >= 'A' && c1 <= 'Z') + if ( c1 >= 'A' && c1 <= 'Z' ) { c1 += 'a' - 'A'; + } c2 = *pattern; - if (c2 >= 'A' && c2 <= 'Z') + if ( c2 >= 'A' && c2 <= 'Z' ) { c2 += 'a' - 'A'; - if (c1 != c2) + } + if ( c1 != c2 ) { return 0; // no match + } } in++; pattern++; break; } } - if (*in) + if ( *in ) { return 0; // reached end of pattern but not end of input + } return 1; // success } diff --git a/libs/filematch.h b/libs/filematch.h index f075b75c..cdb340a8 100644 --- a/libs/filematch.h +++ b/libs/filematch.h @@ -1,4 +1,4 @@ -#if !defined(INCLUDED_FILEMATCH_H) +#if !defined( INCLUDED_FILEMATCH_H ) #define INCLUDED_FILEMATCH_H #ifdef __cplusplus @@ -6,8 +6,8 @@ extern "C" { #endif -int matchpattern(const char *in, const char *pattern, int caseinsensitive); -int matchpattern_with_separator(const char *in, const char *pattern, int caseinsensitive, const char *separators, int wildcard_least_one); +int matchpattern( const char *in, const char *pattern, int caseinsensitive ); +int matchpattern_with_separator( const char *in, const char *pattern, int caseinsensitive, const char *separators, int wildcard_least_one ); #ifdef __cplusplus } diff --git a/libs/fs_filesystem.cpp b/libs/fs_filesystem.cpp index f0820982..9b781a3d 100644 --- a/libs/fs_filesystem.cpp +++ b/libs/fs_filesystem.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "fs_filesystem.h" diff --git a/libs/fs_filesystem.h b/libs/fs_filesystem.h index 0c22a4b3..5cd42a63 100644 --- a/libs/fs_filesystem.h +++ b/libs/fs_filesystem.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_FS_FILESYSTEM_H) +#if !defined( INCLUDED_FS_FILESYSTEM_H ) #define INCLUDED_FS_FILESYSTEM_H #include "string/string.h" @@ -27,19 +27,17 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include -inline unsigned int path_get_depth(const char* path) -{ - unsigned int depth = 0; - while(path != 0 && path[0] != '\0') - { - path = strchr(path, '/'); - if(path != 0) - { - ++path; - } - ++depth; - } - return depth; +inline unsigned int path_get_depth( const char* path ){ + unsigned int depth = 0; + while ( path != 0 && path[0] != '\0' ) + { + path = strchr( path, '/' ); + if ( path != 0 ) { + ++path; + } + ++depth; + } + return depth; } /// \brief A generic unix-style file-system which maps paths to files and directories. @@ -48,136 +46,115 @@ inline unsigned int path_get_depth(const char* path) template class GenericFileSystem { - class Path - { - CopiedString m_path; - unsigned int m_depth; - public: - Path(const char* path) - : m_path(path), m_depth(path_get_depth(c_str())) - { - } - Path(StringRange range) - : m_path(range), m_depth(path_get_depth(c_str())) - { - } - bool operator<(const Path& other) const - { - return string_less_nocase(c_str(), other.c_str()); - } - unsigned int depth() const - { - return m_depth; - } - const char* c_str() const - { - return m_path.c_str(); - } - }; - - class Entry - { - file_type* m_file; - public: - Entry() : m_file(0) - { - } - Entry(file_type* file) : m_file(file) - { - } - file_type* file() const - { - return m_file; - } - bool is_directory() const - { - return file() == 0; - } - }; - - typedef std::map Entries; - Entries m_entries; +class Path +{ +CopiedString m_path; +unsigned int m_depth; +public: +Path( const char* path ) + : m_path( path ), m_depth( path_get_depth( c_str() ) ){ +} +Path( StringRange range ) + : m_path( range ), m_depth( path_get_depth( c_str() ) ){ +} +bool operator<( const Path& other ) const { + return string_less_nocase( c_str(), other.c_str() ); +} +unsigned int depth() const { + return m_depth; +} +const char* c_str() const { + return m_path.c_str(); +} +}; +class Entry +{ +file_type* m_file; public: - typedef typename Entries::iterator iterator; - typedef typename Entries::value_type value_type; - typedef Entry entry_type; - - iterator begin() - { - return m_entries.begin(); - } - iterator end() - { - return m_entries.end(); - } - - /// \brief Returns the file at \p path. - /// Creates all directories below \p path if they do not exist. - /// O(log n) on average. - entry_type& operator[](const Path& path) - { - { - const char* end = path_remove_directory(path.c_str()); - while(end[0] != '\0') - { - Path dir(StringRange(path.c_str(), end)); - m_entries.insert(value_type(dir, Entry(0))); - end = path_remove_directory(end); - } - } - - return m_entries[path]; - } - - /// \brief Returns the file at \p path or end() if not found. - iterator find(const Path& path) - { - return m_entries.find(path); - } - - iterator begin(const char* root) - { - if(root[0] == '\0') - { - return m_entries.begin(); - } - iterator i = m_entries.find(root); - if(i == m_entries.end()) - { - return i; - } - return ++i; - } - - /// \brief Performs a depth-first traversal of the file-system subtree rooted at \p root. - /// Traverses the entire tree if \p root is "". - /// Calls \p visitor.file() with the path to each file relative to the filesystem root. - /// Calls \p visitor.directory() with the path to each directory relative to the filesystem root. - template - void traverse(visitor_type visitor, const char* root) - { - unsigned int start_depth = path_get_depth(root); - unsigned int skip_depth = 0; - for(iterator i = begin(root); i != end() && i->first.depth() > start_depth; ++i) - { - if(i->first.depth() == skip_depth) - { - skip_depth = 0; - } - if(skip_depth == 0) - { - if(!i->second.is_directory()) - { - visitor.file(i->first.c_str()); - } - else if(visitor.directory(i->first.c_str(), i->first.depth() - start_depth)) - { - skip_depth = i->first.depth(); - } - } - } - } +Entry() : m_file( 0 ){ +} +Entry( file_type* file ) : m_file( file ){ +} +file_type* file() const { + return m_file; +} +bool is_directory() const { + return file() == 0; +} +}; + +typedef std::map Entries; +Entries m_entries; + +public: +typedef typename Entries::iterator iterator; +typedef typename Entries::value_type value_type; +typedef Entry entry_type; + +iterator begin(){ + return m_entries.begin(); +} +iterator end(){ + return m_entries.end(); +} + +/// \brief Returns the file at \p path. +/// Creates all directories below \p path if they do not exist. +/// O(log n) on average. +entry_type& operator[]( const Path& path ){ + { + const char* end = path_remove_directory( path.c_str() ); + while ( end[0] != '\0' ) + { + Path dir( StringRange( path.c_str(), end ) ); + m_entries.insert( value_type( dir, Entry( 0 ) ) ); + end = path_remove_directory( end ); + } + } + + return m_entries[path]; +} + +/// \brief Returns the file at \p path or end() if not found. +iterator find( const Path& path ){ + return m_entries.find( path ); +} + +iterator begin( const char* root ){ + if ( root[0] == '\0' ) { + return m_entries.begin(); + } + iterator i = m_entries.find( root ); + if ( i == m_entries.end() ) { + return i; + } + return ++i; +} + +/// \brief Performs a depth-first traversal of the file-system subtree rooted at \p root. +/// Traverses the entire tree if \p root is "". +/// Calls \p visitor.file() with the path to each file relative to the filesystem root. +/// Calls \p visitor.directory() with the path to each directory relative to the filesystem root. +template +void traverse( visitor_type visitor, const char* root ){ + unsigned int start_depth = path_get_depth( root ); + unsigned int skip_depth = 0; + for ( iterator i = begin( root ); i != end() && i->first.depth() > start_depth; ++i ) + { + if ( i->first.depth() == skip_depth ) { + skip_depth = 0; + } + if ( skip_depth == 0 ) { + if ( !i->second.is_directory() ) { + visitor.file( i->first.c_str() ); + } + else if ( visitor.directory( i->first.c_str(), i->first.depth() - start_depth ) ) { + skip_depth = i->first.depth(); + } + } + } +} }; #endif diff --git a/libs/fs_path.cpp b/libs/fs_path.cpp index 5cd36406..f38bf1c5 100644 --- a/libs/fs_path.cpp +++ b/libs/fs_path.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "fs_path.h" diff --git a/libs/fs_path.h b/libs/fs_path.h index df409ef0..2baf297e 100644 --- a/libs/fs_path.h +++ b/libs/fs_path.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_FS_PATH_H) +#if !defined( INCLUDED_FS_PATH_H ) #define INCLUDED_FS_PATH_H #include "stream/stringstream.h" @@ -30,63 +30,53 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// - Provides a limited STL-style interface to push and pop file or directory names at the end of the path. class UnixPath { - StringBuffer m_string; +StringBuffer m_string; - void check_separator() - { - if(!empty() && m_string.back() != '/') - { - m_string.push_back('/'); - } - } +void check_separator(){ + if ( !empty() && m_string.back() != '/' ) { + m_string.push_back( '/' ); + } +} public: - /// \brief Constructs with the directory \p root. - UnixPath(const char* root) - : m_string(root) - { - check_separator(); - } +/// \brief Constructs with the directory \p root. +UnixPath( const char* root ) + : m_string( root ){ + check_separator(); +} - bool empty() const - { - return m_string.empty(); - } +bool empty() const { + return m_string.empty(); +} - const char* c_str() const - { - return m_string.c_str(); - } +const char* c_str() const { + return m_string.c_str(); +} - /// \brief Appends the directory \p name. - void push(const char* name) - { - m_string.push_string(name); - check_separator(); - } - /// \brief Appends the directory [\p first, \p last). - void push(const char* first, const char* last) - { - m_string.push_range(first, last); - check_separator(); - } - /// \brief Appends the filename \p name. - void push_filename(const char* name) - { - m_string.push_string(name); - } - /// \brief Removes the last directory or filename appended. - void pop() - { - if(m_string.back() == '/') - { - m_string.pop_back(); - } - while(!empty() && m_string.back() != '/') - { - m_string.pop_back(); - } - } +/// \brief Appends the directory \p name. +void push( const char* name ){ + m_string.push_string( name ); + check_separator(); +} +/// \brief Appends the directory [\p first, \p last). +void push( const char* first, const char* last ){ + m_string.push_range( first, last ); + check_separator(); +} +/// \brief Appends the filename \p name. +void push_filename( const char* name ){ + m_string.push_string( name ); +} +/// \brief Removes the last directory or filename appended. +void pop(){ + if ( m_string.back() == '/' ) { + m_string.pop_back(); + } + while ( !empty() && m_string.back() != '/' ) + { + m_string.pop_back(); + } +} }; #endif diff --git a/libs/generic/arrayrange.cpp b/libs/generic/arrayrange.cpp index b04ba068..0ee018b2 100644 --- a/libs/generic/arrayrange.cpp +++ b/libs/generic/arrayrange.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "arrayrange.h" - diff --git a/libs/generic/arrayrange.h b/libs/generic/arrayrange.h index a05489a1..e036cf3d 100644 --- a/libs/generic/arrayrange.h +++ b/libs/generic/arrayrange.h @@ -1,73 +1,69 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_ARRAYRANGE_H) +#if !defined( INCLUDED_GENERIC_ARRAYRANGE_H ) #define INCLUDED_GENERIC_ARRAYRANGE_H /// \file -/// \brief Macros for automatically converting a compile-time-sized array to a range. +/// \brief Macros for automatically converting a compile-time-sized array to a range. template struct ArrayRange { - typedef Element* Iterator; - ArrayRange(Iterator first, Iterator last) - : first(first), last(last) - { - } - Iterator first; - Iterator last; + typedef Element* Iterator; + ArrayRange( Iterator first, Iterator last ) + : first( first ), last( last ){ + } + Iterator first; + Iterator last; }; template -inline ArrayRange makeArrayRange(Element* first, Element* last) -{ - return ArrayRange(first, last); +inline ArrayRange makeArrayRange( Element* first, Element* last ){ + return ArrayRange( first, last ); } template struct ArrayConstRange { - typedef const Element* Iterator; - ArrayConstRange(Iterator first, Iterator last) - : first(first), last(last) - { - } - Iterator first; - Iterator last; + typedef const Element* Iterator; + ArrayConstRange( Iterator first, Iterator last ) + : first( first ), last( last ){ + } + Iterator first; + Iterator last; }; template -inline ArrayConstRange makeArrayRange(const Element* first, const Element* last) -{ - return ArrayConstRange(first, last); +inline ArrayConstRange makeArrayRange( const Element* first, const Element* last ){ + return ArrayConstRange( first, last ); } -#define ARRAY_SIZE(array) (sizeof(array) / sizeof(*array)) -#define ARRAY_END(array) (array + ARRAY_SIZE(array)) -#define ARRAY_RANGE(array) (makeArrayRange(array, ARRAY_END(array))) +#define ARRAY_SIZE( array ) ( sizeof( array ) / sizeof( *array ) ) +#define ARRAY_END( array ) ( array + ARRAY_SIZE( array ) ) +#define ARRAY_RANGE( array ) ( makeArrayRange( array, ARRAY_END( array ) ) ) typedef ArrayConstRange StringArrayRange; -#define STRING_ARRAY_RANGE(array) (StringArrayRange(array, ARRAY_END(array))) +#define STRING_ARRAY_RANGE( array ) ( StringArrayRange( array, ARRAY_END( array ) ) ) typedef ArrayRange StringRange; diff --git a/libs/generic/bitfield.cpp b/libs/generic/bitfield.cpp index 96d15c9c..7e46a347 100644 --- a/libs/generic/bitfield.cpp +++ b/libs/generic/bitfield.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "bitfield.h" - diff --git a/libs/generic/bitfield.h b/libs/generic/bitfield.h index 652f0539..f9427aac 100644 --- a/libs/generic/bitfield.h +++ b/libs/generic/bitfield.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_BITFIELD_H) +#if !defined( INCLUDED_GENERIC_BITFIELD_H ) #define INCLUDED_GENERIC_BITFIELD_H /// \file @@ -35,99 +35,81 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class BitFieldValue : public Enumeration { - unsigned m_value; +unsigned m_value; protected: - explicit BitFieldValue(unsigned value) : m_value(value) - { - } +explicit BitFieldValue( unsigned value ) : m_value( value ){ +} public: - BitFieldValue() : m_value(0) - { - } - explicit BitFieldValue(typename Enumeration::Value value) : m_value(1 << value) - { - } - unsigned get() const - { - return m_value; - } +BitFieldValue() : m_value( 0 ){ +} +explicit BitFieldValue( typename Enumeration::Value value ) : m_value( 1 << value ){ +} +unsigned get() const { + return m_value; +} }; template class BitFieldValueUnsafe : public BitFieldValue { public: - explicit BitFieldValueUnsafe(unsigned value) : BitFieldValue(value) - { - } +explicit BitFieldValueUnsafe( unsigned value ) : BitFieldValue( value ){ +} }; template -inline bool operator==(BitFieldValue self, BitFieldValue other) -{ - return self.get() == other.get(); +inline bool operator==( BitFieldValue self, BitFieldValue other ){ + return self.get() == other.get(); } template -inline bool operator!=(BitFieldValue self, BitFieldValue other) -{ - return !operator==(self, other); +inline bool operator!=( BitFieldValue self, BitFieldValue other ){ + return !operator==( self, other ); } template -inline BitFieldValue operator|(BitFieldValue self, BitFieldValue other) -{ - return BitFieldValueUnsafe(self.get() | other.get()); +inline BitFieldValue operator|( BitFieldValue self, BitFieldValue other ){ + return BitFieldValueUnsafe( self.get() | other.get() ); } template -inline BitFieldValue& operator|=(BitFieldValue& self, BitFieldValue other) -{ - return self = self | other; +inline BitFieldValue& operator|=( BitFieldValue& self, BitFieldValue other ){ + return self = self | other; } template -inline BitFieldValue operator&(BitFieldValue self, BitFieldValue other) -{ - return BitFieldValueUnsafe(self.get() & other.get()); +inline BitFieldValue operator&( BitFieldValue self, BitFieldValue other ){ + return BitFieldValueUnsafe( self.get() & other.get() ); } template -inline BitFieldValue& operator&=(BitFieldValue& self, BitFieldValue other) -{ - return self = self & other; +inline BitFieldValue& operator&=( BitFieldValue& self, BitFieldValue other ){ + return self = self & other; } template -inline BitFieldValue operator~(BitFieldValue self) -{ - return BitFieldValueUnsafe(~self.get()); +inline BitFieldValue operator~( BitFieldValue self ){ + return BitFieldValueUnsafe( ~self.get() ); } -inline unsigned int bitfield_enable(unsigned int bitfield, unsigned int mask) -{ - return bitfield | mask; +inline unsigned int bitfield_enable( unsigned int bitfield, unsigned int mask ){ + return bitfield | mask; } -inline unsigned int bitfield_disable(unsigned int bitfield, unsigned int mask) -{ - return bitfield & ~mask; +inline unsigned int bitfield_disable( unsigned int bitfield, unsigned int mask ){ + return bitfield & ~mask; } -inline bool bitfield_enabled(unsigned int bitfield, unsigned int mask) -{ - return (bitfield & mask) != 0; +inline bool bitfield_enabled( unsigned int bitfield, unsigned int mask ){ + return ( bitfield & mask ) != 0; } template -inline BitFieldValue bitfield_enable(BitFieldValue bitfield, BitFieldValue mask) -{ - return bitfield | mask; +inline BitFieldValue bitfield_enable( BitFieldValue bitfield, BitFieldValue mask ){ + return bitfield | mask; } template -inline BitFieldValue bitfield_disable(BitFieldValue bitfield, BitFieldValue mask) -{ - return bitfield & ~mask; +inline BitFieldValue bitfield_disable( BitFieldValue bitfield, BitFieldValue mask ){ + return bitfield & ~mask; } template -inline bool bitfield_enabled(BitFieldValue bitfield, BitFieldValue mask) -{ - return (bitfield & mask).get() != 0; +inline bool bitfield_enabled( BitFieldValue bitfield, BitFieldValue mask ){ + return ( bitfield & mask ).get() != 0; } #endif diff --git a/libs/generic/callback.cpp b/libs/generic/callback.cpp index 2344830a..db04d53e 100644 --- a/libs/generic/callback.cpp +++ b/libs/generic/callback.cpp @@ -1,285 +1,256 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "callback.h" -#if defined(_DEBUG) || defined(DOXYGEN) +#if defined( _DEBUG ) || defined( DOXYGEN ) namespace ExampleMemberCaller { - // MemberCaller example - class Integer - { - public: - int value; +// MemberCaller example +class Integer +{ +public: +int value; - void printValue() const - { - // print this->value here; - } +void printValue() const { + // print this->value here; +} - void setValue() - { - value = 3; - } - // a typedef to make things more readable - typedef MemberCaller SetValueCaller; - }; +void setValue(){ + value = 3; +} +// a typedef to make things more readable +typedef MemberCaller SetValueCaller; +}; - void example() - { - Integer foo = { 0 }; +void example(){ + Integer foo = { 0 }; - { - Callback bar = ConstMemberCaller(foo); + { + Callback bar = ConstMemberCaller( foo ); - // invoke the callback - bar(); // foo.printValue() - } + // invoke the callback + bar(); // foo.printValue() + } - { - // use the typedef to improve readability - Callback bar = Integer::SetValueCaller(foo); + { + // use the typedef to improve readability + Callback bar = Integer::SetValueCaller( foo ); - // invoke the callback - bar(); // foo.setValue() - } - } - // end example + // invoke the callback + bar(); // foo.setValue() + } +} +// end example } namespace ExampleReferenceCaller { - // ReferenceCaller example - void Int_printValue(const int& value) - { - // print value here; - } +// ReferenceCaller example +void Int_printValue( const int& value ){ + // print value here; +} - void Int_setValue(int& value) - { - value = 3; - } +void Int_setValue( int& value ){ + value = 3; +} - // a typedef to make things more readable - typedef ReferenceCaller IntSetValueCaller; +// a typedef to make things more readable +typedef ReferenceCaller IntSetValueCaller; - void example() - { - int foo = 0; +void example(){ + int foo = 0; - { - Callback bar = ConstReferenceCaller(foo); + { + Callback bar = ConstReferenceCaller( foo ); - // invoke the callback - bar(); // Int_printValue(foo) - } + // invoke the callback + bar(); // Int_printValue(foo) + } - { - // use the typedef to improve readability - Callback bar = IntSetValueCaller(foo); + { + // use the typedef to improve readability + Callback bar = IntSetValueCaller( foo ); - // invoke the callback - bar(); // Int_setValue(foo) - } - } - // end example + // invoke the callback + bar(); // Int_setValue(foo) + } +} +// end example } #endif namespace { - class A1 - { - }; - class A2 - { - }; - class A3 - { - }; - class A4 - { - }; - - class Test - { - public: - void test0() - { - } - typedef Member Test0; - typedef MemberCaller Test0Caller; - void test0const() const - { - } - typedef ConstMember Test0Const; - typedef ConstMemberCaller Test0ConstCaller; - void test1(A1) - { - } - typedef Member1 Test1; - typedef MemberCaller1 Test1Caller; - void test1const(A1) const - { - } - typedef ConstMember1 Test1Const; - typedef ConstMemberCaller1 Test1ConstCaller; - void test2(A1, A2) - { - } - typedef Member2 Test2; - void test2const(A1, A2) const - { - } - typedef ConstMember2 Test2Const; - void test3(A1, A2, A3) - { - } - typedef Member3 Test3; - void test3const(A1, A2, A3) const - { - } - typedef ConstMember3 Test3Const; - }; - - void test0free() - { - } - typedef FreeCaller<&test0free> Test0FreeCaller; - void test1free(A1) - { - } - typedef FreeCaller1 Test1FreeCaller; - void test2free(A1, A2) - { - } - typedef Function2 Test2Free; - void test3free(A1, A2, A3) - { - } - typedef Function3 Test3Free; - - - void test0(Test& test) - { - } - typedef ReferenceCaller Test0Caller; - - void test0const(const Test& test) - { - } - typedef ConstReferenceCaller Test0ConstCaller; - - void test0p(Test* test) - { - } - typedef PointerCaller Test0PCaller; - - void test0constp(const Test* test) - { - } - typedef ConstPointerCaller Test0ConstPCaller; - - void test1(Test& test, A1) - { - } - typedef ReferenceCaller1 Test1Caller; - - void test1const(const Test& test, A1) - { - } - typedef ConstReferenceCaller1 Test1ConstCaller; - - void test1p(Test* test, A1) - { - } - typedef PointerCaller1 Test1PCaller; - - void test1constp(const Test* test, A1) - { - } - typedef ConstPointerCaller1 Test1ConstPCaller; - - void test2(Test& test, A1, A2) - { - } - typedef Function3 Test2; - - void test3(Test& test, A1, A2, A3) - { - } - typedef Function4 Test3; - - void instantiate() - { - Test test; - const Test& testconst = test; - { - Callback a = Test0FreeCaller(); - Callback b = Test::Test0Caller(test); - b = makeCallback0(Test::Test0(), test); - Callback c = Test::Test0ConstCaller(testconst); - c = makeCallback0(Test::Test0Const(), test); - Callback d = Test0Caller(test); - Callback e = Test0ConstCaller(testconst); - Callback f = Test0PCaller(&test); - Callback g = Test0ConstPCaller(&testconst); - a(); - bool u = a != b; - } - { - typedef Callback1 TestCallback1; - TestCallback1 a = Test1FreeCaller(); - TestCallback1 b = Test::Test1Caller(test); - b = makeCallback1(Test::Test1(), test); - TestCallback1 c = Test::Test1ConstCaller(testconst); - c = makeCallback1(Test::Test1Const(), test); - TestCallback1 d = Test1Caller(test); - TestCallback1 e = Test1ConstCaller(testconst); - TestCallback1 f = Test1PCaller(&test); - TestCallback1 g = Test1ConstPCaller(&testconst); - a(A1()); - bool u = a != b; - } - { - typedef Callback2 TestCallback2; - TestCallback2 a = makeStatelessCallback2(Test2Free()); - TestCallback2 b = makeCallback2(Test2(), test); - TestCallback2 c = makeCallback2(Test::Test2(), test); - TestCallback2 d = makeCallback2(Test::Test2Const(), test); - a(A1(), A2()); - bool u = a != b; - } - { - typedef Callback3 TestCallback3; - TestCallback3 a = makeStatelessCallback3(Test3Free()); - TestCallback3 b = makeCallback3(Test3(), test); - TestCallback3 c = makeCallback3(Test::Test3(), test); - TestCallback3 d = makeCallback3(Test::Test3Const(), test); - a(A1(), A2(), A3()); - bool u = a != b; - } - } +class A1 +{ +}; +class A2 +{ +}; +class A3 +{ +}; +class A4 +{ +}; + +class Test +{ +public: +void test0(){ +} +typedef Member Test0; +typedef MemberCaller Test0Caller; +void test0const() const { +} +typedef ConstMember Test0Const; +typedef ConstMemberCaller Test0ConstCaller; +void test1( A1 ){ +} +typedef Member1 Test1; +typedef MemberCaller1 Test1Caller; +void test1const( A1 ) const { +} +typedef ConstMember1 Test1Const; +typedef ConstMemberCaller1 Test1ConstCaller; +void test2( A1, A2 ){ +} +typedef Member2 Test2; +void test2const( A1, A2 ) const { +} +typedef ConstMember2 Test2Const; +void test3( A1, A2, A3 ){ +} +typedef Member3 Test3; +void test3const( A1, A2, A3 ) const { +} +typedef ConstMember3 Test3Const; +}; + +void test0free(){ +} +typedef FreeCaller<&test0free> Test0FreeCaller; +void test1free( A1 ){ +} +typedef FreeCaller1 Test1FreeCaller; +void test2free( A1, A2 ){ +} +typedef Function2 Test2Free; +void test3free( A1, A2, A3 ){ +} +typedef Function3 Test3Free; + + +void test0( Test& test ){ +} +typedef ReferenceCaller Test0Caller; + +void test0const( const Test& test ){ +} +typedef ConstReferenceCaller Test0ConstCaller; + +void test0p( Test* test ){ +} +typedef PointerCaller Test0PCaller; + +void test0constp( const Test* test ){ +} +typedef ConstPointerCaller Test0ConstPCaller; + +void test1( Test& test, A1 ){ +} +typedef ReferenceCaller1 Test1Caller; + +void test1const( const Test& test, A1 ){ +} +typedef ConstReferenceCaller1 Test1ConstCaller; + +void test1p( Test* test, A1 ){ +} +typedef PointerCaller1 Test1PCaller; + +void test1constp( const Test* test, A1 ){ +} +typedef ConstPointerCaller1 Test1ConstPCaller; + +void test2( Test& test, A1, A2 ){ +} +typedef Function3 Test2; + +void test3( Test& test, A1, A2, A3 ){ +} +typedef Function4 Test3; + +void instantiate(){ + Test test; + const Test& testconst = test; + { + Callback a = Test0FreeCaller(); + Callback b = Test::Test0Caller( test ); + b = makeCallback0( Test::Test0(), test ); + Callback c = Test::Test0ConstCaller( testconst ); + c = makeCallback0( Test::Test0Const(), test ); + Callback d = Test0Caller( test ); + Callback e = Test0ConstCaller( testconst ); + Callback f = Test0PCaller( &test ); + Callback g = Test0ConstPCaller( &testconst ); + a(); + bool u = a != b; + } + { + typedef Callback1 TestCallback1; + TestCallback1 a = Test1FreeCaller(); + TestCallback1 b = Test::Test1Caller( test ); + b = makeCallback1( Test::Test1(), test ); + TestCallback1 c = Test::Test1ConstCaller( testconst ); + c = makeCallback1( Test::Test1Const(), test ); + TestCallback1 d = Test1Caller( test ); + TestCallback1 e = Test1ConstCaller( testconst ); + TestCallback1 f = Test1PCaller( &test ); + TestCallback1 g = Test1ConstPCaller( &testconst ); + a( A1() ); + bool u = a != b; + } + { + typedef Callback2 TestCallback2; + TestCallback2 a = makeStatelessCallback2( Test2Free() ); + TestCallback2 b = makeCallback2( Test2(), test ); + TestCallback2 c = makeCallback2( Test::Test2(), test ); + TestCallback2 d = makeCallback2( Test::Test2Const(), test ); + a( A1(), A2() ); + bool u = a != b; + } + { + typedef Callback3 TestCallback3; + TestCallback3 a = makeStatelessCallback3( Test3Free() ); + TestCallback3 b = makeCallback3( Test3(), test ); + TestCallback3 c = makeCallback3( Test::Test3(), test ); + TestCallback3 d = makeCallback3( Test::Test3Const(), test ); + a( A1(), A2(), A3() ); + bool u = a != b; + } +} } diff --git a/libs/generic/callback.h b/libs/generic/callback.h index 7141da4a..2ce007fc 100644 --- a/libs/generic/callback.h +++ b/libs/generic/callback.h @@ -1,53 +1,49 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_CLOSURE_H) +#if !defined( INCLUDED_GENERIC_CLOSURE_H ) #define INCLUDED_GENERIC_CLOSURE_H /// \file -/// \brief Type-safe techniques for binding the first argument of an opaque callback. +/// \brief Type-safe techniques for binding the first argument of an opaque callback. #include #include "functional.h" #include "callbackfwd.h" template -inline void* convertToOpaque(Type* t) -{ - return t; +inline void* convertToOpaque( Type* t ){ + return t; } template -inline void* convertToOpaque(const Type* t) -{ - return const_cast(t); +inline void* convertToOpaque( const Type* t ){ + return const_cast( t ); } template -inline void* convertToOpaque(Type& t) -{ - return &t; +inline void* convertToOpaque( Type& t ){ + return &t; } template -inline void* convertToOpaque(const Type& t) -{ - return const_cast(&t); +inline void* convertToOpaque( const Type& t ){ + return const_cast( &t ); } @@ -60,20 +56,18 @@ template class ConvertFromOpaque { public: - static Type& apply(void* p) - { - return *static_cast(p); - } +static Type& apply( void* p ){ + return *static_cast( p ); +} }; template class ConvertFromOpaque { public: - static const Type& apply(void* p) - { - return *static_cast(p); - } +static const Type& apply( void* p ){ + return *static_cast( p ); +} }; @@ -81,175 +75,147 @@ template class ConvertFromOpaque { public: - static Type* apply(void* p) - { - return static_cast(p); - } +static Type* apply( void* p ){ + return static_cast( p ); +} }; template class ConvertFromOpaque { public: - static const Type* apply(void* p) - { - return static_cast(p); - } +static const Type* apply( void* p ){ + return static_cast( p ); +} }; template class BindFirstOpaque { - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; +typedef typename Caller::first_argument_type FirstBound; +FirstBound firstBound; public: - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()() const - { - return Caller::call(firstBound); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment) - { - return Caller::call(ConvertFromOpaque::apply(environment)); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } +typedef typename Caller::result_type result_type; +explicit BindFirstOpaque( FirstBound firstBound ) : firstBound( firstBound ){ +} +result_type operator()() const { + return Caller::call( firstBound ); +} +FirstBound getBound() const { + return firstBound; +} +static result_type thunk( void* environment ){ + return Caller::call( ConvertFromOpaque::apply( environment ) ); +} +void* getEnvironment() const { + return convertToOpaque( firstBound ); +} }; template class BindFirstOpaque1 { - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; +typedef typename Caller::first_argument_type FirstBound; +FirstBound firstBound; public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque1(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1) const - { - return Caller::call(firstBound, a1); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } +typedef typename Caller::second_argument_type first_argument_type; +typedef typename Caller::result_type result_type; +explicit BindFirstOpaque1( FirstBound firstBound ) : firstBound( firstBound ){ +} +result_type operator()( first_argument_type a1 ) const { + return Caller::call( firstBound, a1 ); +} +FirstBound getBound() const { + return firstBound; +} +static result_type thunk( void* environment, first_argument_type a1 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1 ); +} +void* getEnvironment() const { + return convertToOpaque( firstBound ); +} }; template class BindFirstOpaque2 { - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; +typedef typename Caller::first_argument_type FirstBound; +FirstBound firstBound; public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::third_argument_type second_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque2(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1, second_argument_type a2) const - { - return Caller::call(firstBound, a1, a2); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1, a2); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } +typedef typename Caller::second_argument_type first_argument_type; +typedef typename Caller::third_argument_type second_argument_type; +typedef typename Caller::result_type result_type; +explicit BindFirstOpaque2( FirstBound firstBound ) : firstBound( firstBound ){ +} +result_type operator()( first_argument_type a1, second_argument_type a2 ) const { + return Caller::call( firstBound, a1, a2 ); +} +FirstBound getBound() const { + return firstBound; +} +static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2 ); +} +void* getEnvironment() const { + return convertToOpaque( firstBound ); +} }; template class BindFirstOpaque3 { - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; +typedef typename Caller::first_argument_type FirstBound; +FirstBound firstBound; public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::third_argument_type second_argument_type; - typedef typename Caller::fourth_argument_type third_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque3(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1, second_argument_type a2, third_argument_type a3) const - { - return Caller::call(firstBound, a1, a2, a3); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1, a2, a3); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } +typedef typename Caller::second_argument_type first_argument_type; +typedef typename Caller::third_argument_type second_argument_type; +typedef typename Caller::fourth_argument_type third_argument_type; +typedef typename Caller::result_type result_type; +explicit BindFirstOpaque3( FirstBound firstBound ) : firstBound( firstBound ){ +} +result_type operator()( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) const { + return Caller::call( firstBound, a1, a2, a3 ); +} +FirstBound getBound() const { + return firstBound; +} +static result_type thunk( void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ + return Caller::call( ConvertFromOpaque::apply( environment ), a1, a2, a3 ); +} +void* getEnvironment() const { + return convertToOpaque( firstBound ); +} }; template class CallbackBase { - void* m_environment; - Thunk_ m_thunk; +void* m_environment; +Thunk_ m_thunk; public: - typedef Thunk_ Thunk; - CallbackBase(void* environment, Thunk function) : m_environment(environment), m_thunk(function) - { - } - void* getEnvironment() const - { - return m_environment; - } - Thunk getThunk() const - { - return m_thunk; - } +typedef Thunk_ Thunk; +CallbackBase( void* environment, Thunk function ) : m_environment( environment ), m_thunk( function ){ +} +void* getEnvironment() const { + return m_environment; +} +Thunk getThunk() const { + return m_thunk; +} }; template -inline bool operator==(const CallbackBase& self, const CallbackBase& other) -{ - return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); +inline bool operator==( const CallbackBase& self, const CallbackBase& other ){ + return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); } template -inline bool operator!=(const CallbackBase& self, const CallbackBase& other) -{ - return !(self == other); +inline bool operator!=( const CallbackBase& self, const CallbackBase& other ){ + return !( self == other ); } template -inline bool operator<(const CallbackBase& self, const CallbackBase& other) -{ - return self.getEnvironment() < other.getEnvironment() || - (!(other.getEnvironment() < self.getEnvironment()) && self.getThunk() < other.getThunk()); +inline bool operator<( const CallbackBase& self, const CallbackBase& other ){ + return self.getEnvironment() < other.getEnvironment() || + ( !( other.getEnvironment() < self.getEnvironment() ) && self.getThunk() < other.getThunk() ); } @@ -257,201 +223,173 @@ inline bool operator<(const CallbackBase& self, const CallbackBase /// /// Use with the callback constructors MemberCaller, ConstMemberCaller, ReferenceCaller, ConstReferenceCaller, PointerCaller, ConstPointerCaller and FreeCaller. template -class Callback0 : public CallbackBase +class Callback0 : public CallbackBase { - typedef CallbackBase Base; - static Result nullThunk(void*) - { - } +typedef CallbackBase Base; +static Result nullThunk( void* ){ +} public: - typedef Result result_type; - - Callback0() : Base(0, nullThunk) - { - } - template - Callback0(const BindFirstOpaque& caller) : Base(caller.getEnvironment(), BindFirstOpaque::thunk) - { - } - Callback0(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()() const - { - return Base::getThunk()(Base::getEnvironment()); - } +typedef Result result_type; + +Callback0() : Base( 0, nullThunk ){ +} +template +Callback0( const BindFirstOpaque& caller ) : Base( caller.getEnvironment(), BindFirstOpaque::thunk ){ +} +Callback0( void* environment, typename Base::Thunk function ) : Base( environment, function ){ +} +result_type operator()() const { + return Base::getThunk() ( Base::getEnvironment() ); +} }; template -inline Callback0 makeCallback0(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback0(BindFirstOpaque(callee)); +inline Callback0 makeCallback0( const Caller& caller, typename Caller::first_argument_type callee ){ + return Callback0( BindFirstOpaque( callee ) ); } template -inline Callback0 makeStatelessCallback0(const Caller& caller) -{ - return makeCallback0(Caller0To1(), 0); +inline Callback0 makeStatelessCallback0( const Caller& caller ){ + return makeCallback0( Caller0To1(), 0 ); } typedef Callback0 Callback; -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and one other argument. +/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and one other argument. /// /// Use with the callback constructors MemberCaller1, ConstMemberCaller1, ReferenceCaller1, ConstReferenceCaller1, PointerCaller1, ConstPointerCaller1 and FreeCaller1. template -class Callback1 : public CallbackBase +class Callback1 : public CallbackBase { - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument) - { - } +typedef CallbackBase Base; +static Result nullThunk( void*, FirstArgument ){ +} public: - typedef FirstArgument first_argument_type; - typedef Result result_type; - - Callback1() : Base(0, nullThunk) - { - } - template - Callback1(const BindFirstOpaque1& caller) : Base(caller.getEnvironment(), BindFirstOpaque1::thunk) - { - } - Callback1(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument); - } +typedef FirstArgument first_argument_type; +typedef Result result_type; + +Callback1() : Base( 0, nullThunk ){ +} +template +Callback1( const BindFirstOpaque1& caller ) : Base( caller.getEnvironment(), BindFirstOpaque1::thunk ){ +} +Callback1( void* environment, typename Base::Thunk function ) : Base( environment, function ){ +} +result_type operator()( FirstArgument firstArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument ); +} }; template -inline Callback1 makeCallback1(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback1(BindFirstOpaque1(callee)); +inline Callback1 makeCallback1( const Caller& caller, typename Caller::first_argument_type callee ){ + return Callback1( BindFirstOpaque1( callee ) ); } template -inline Callback1 makeStatelessCallback1(const Caller& caller) -{ - return makeCallback1(Caller1To2(), 0); +inline Callback1 makeStatelessCallback1( const Caller& caller ){ + return makeCallback1( Caller1To2(), 0 ); } -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and two other arguments. +/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and two other arguments. /// template -class Callback2 : public CallbackBase +class Callback2 : public CallbackBase { - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument, SecondArgument) - { - } +typedef CallbackBase Base; +static Result nullThunk( void*, FirstArgument, SecondArgument ){ +} public: - typedef FirstArgument first_argument_type; - typedef SecondArgument second_argument_type; - typedef Result result_type; - - Callback2() : Base(0, nullThunk) - { - } - template - Callback2(const BindFirstOpaque2& caller) : Base(caller.getEnvironment(), BindFirstOpaque2::thunk) - { - } - Callback2(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument); - } +typedef FirstArgument first_argument_type; +typedef SecondArgument second_argument_type; +typedef Result result_type; + +Callback2() : Base( 0, nullThunk ){ +} +template +Callback2( const BindFirstOpaque2& caller ) : Base( caller.getEnvironment(), BindFirstOpaque2::thunk ){ +} +Callback2( void* environment, typename Base::Thunk function ) : Base( environment, function ){ +} +result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument ); +} }; template inline Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type -> makeCallback2(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type - >(BindFirstOpaque2(callee)); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type + > makeCallback2( const Caller& caller, typename Caller::first_argument_type callee ){ + return Callback2< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type + >( BindFirstOpaque2( callee ) ); } template inline Callback2< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::result_type -> makeStatelessCallback2(const Caller& caller) -{ - return makeCallback2(Caller2To3(), 0); + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::result_type + > makeStatelessCallback2( const Caller& caller ){ + return makeCallback2( Caller2To3(), 0 ); } -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and three other arguments. +/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and three other arguments. /// template -class Callback3 : public CallbackBase +class Callback3 : public CallbackBase { - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument, SecondArgument, ThirdArgument) - { - } +typedef CallbackBase Base; +static Result nullThunk( void*, FirstArgument, SecondArgument, ThirdArgument ){ +} public: - typedef FirstArgument first_argument_type; - typedef SecondArgument second_argument_type; - typedef ThirdArgument third_argument_type; - typedef Result result_type; - - Callback3() : Base(0, nullThunk) - { - } - template - Callback3(const BindFirstOpaque3& caller) : Base(caller.getEnvironment(), BindFirstOpaque3::thunk) - { - } - Callback3(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument, thirdArgument); - } +typedef FirstArgument first_argument_type; +typedef SecondArgument second_argument_type; +typedef ThirdArgument third_argument_type; +typedef Result result_type; + +Callback3() : Base( 0, nullThunk ){ +} +template +Callback3( const BindFirstOpaque3& caller ) : Base( caller.getEnvironment(), BindFirstOpaque3::thunk ){ +} +Callback3( void* environment, typename Base::Thunk function ) : Base( environment, function ){ +} +result_type operator()( FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument ) const { + return Base::getThunk() ( Base::getEnvironment(), firstArgument, secondArgument, thirdArgument ); +} }; template inline Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type -> makeCallback3(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type - >(BindFirstOpaque3(callee)); + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type + > makeCallback3( const Caller& caller, typename Caller::first_argument_type callee ){ + return Callback3< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type + >( BindFirstOpaque3( callee ) ); } template inline Callback3< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type -> makeStatelessCallback3(const Caller& caller) -{ - return makeCallback3(Caller3To4(), 0); + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type + > makeStatelessCallback3( const Caller& caller ){ + return makeCallback3( Caller3To4(), 0 ); } @@ -460,13 +398,12 @@ inline Callback3< /// \dontinclude generic/callback.cpp /// \skipline MemberCaller example /// \until end example -template +template class MemberCaller : public BindFirstOpaque< Member > { public: - MemberCaller(Environment& environment) : BindFirstOpaque< Member >(environment) - { - } +MemberCaller( Environment& environment ) : BindFirstOpaque< Member >( environment ){ +} }; /// \brief Forms a Callback from a const Environment reference and a const Environment member-function. @@ -474,33 +411,30 @@ public: /// \dontinclude generic/callback.cpp /// \skipline MemberCaller example /// \until end example -template +template class ConstMemberCaller : public BindFirstOpaque< ConstMember > { public: - ConstMemberCaller(const Environment& environment) : BindFirstOpaque< ConstMember >(environment) - { - } +ConstMemberCaller( const Environment& environment ) : BindFirstOpaque< ConstMember >( environment ){ +} }; /// \brief Forms a Callback from a non-const Environment reference and a const Environment member-function which takes one argument. -template +template class MemberCaller1 : public BindFirstOpaque1< Member1 > { public: - MemberCaller1(Environment& environment) : BindFirstOpaque1< Member1 >(environment) - { - } +MemberCaller1( Environment& environment ) : BindFirstOpaque1< Member1 >( environment ){ +} }; /// \brief Forms a Callback from a const Environment reference and a const Environment member-function which takes one argument. -template +template class ConstMemberCaller1 : public BindFirstOpaque1< ConstMember1 > { public: - ConstMemberCaller1(const Environment& environment) : BindFirstOpaque1< ConstMember1 >(environment) - { - } +ConstMemberCaller1( const Environment& environment ) : BindFirstOpaque1< ConstMember1 >( environment ){ +} }; /// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference. @@ -508,13 +442,12 @@ public: /// \dontinclude generic/callback.cpp /// \skipline ReferenceCaller example /// \until end example -template +template class ReferenceCaller : public BindFirstOpaque< Function1 > { public: - ReferenceCaller(Environment& environment) : BindFirstOpaque< Function1 >(environment) - { - } +ReferenceCaller( Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ +} }; /// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference. @@ -522,132 +455,119 @@ public: /// \dontinclude generic/callback.cpp /// \skipline ReferenceCaller example /// \until end example -template +template class ConstReferenceCaller : public BindFirstOpaque< Function1 > { public: - ConstReferenceCaller(const Environment& environment) : BindFirstOpaque< Function1 >(environment) - { - } +ConstReferenceCaller( const Environment& environment ) : BindFirstOpaque< Function1 >( environment ){ +} }; /// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference and one other argument. -template +template class ReferenceCaller1 : public BindFirstOpaque1< Function2 > { public: - ReferenceCaller1(Environment& environment) : BindFirstOpaque1< Function2 >(environment) - { - } +ReferenceCaller1( Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ +} }; /// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference and one other argument. -template +template class ConstReferenceCaller1 : public BindFirstOpaque1< Function2 > { public: - ConstReferenceCaller1(const Environment& environment) : BindFirstOpaque1< Function2 >(environment) - { - } +ConstReferenceCaller1( const Environment& environment ) : BindFirstOpaque1< Function2 >( environment ){ +} }; /// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer. -template +template class PointerCaller : public BindFirstOpaque< Function1 > { public: - PointerCaller(Environment* environment) : BindFirstOpaque< Function1 >(environment) - { - } +PointerCaller( Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ +} }; /// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer. -template +template class ConstPointerCaller : public BindFirstOpaque< Function1 > { public: - ConstPointerCaller(const Environment* environment) : BindFirstOpaque< Function1 >(environment) - { - } +ConstPointerCaller( const Environment* environment ) : BindFirstOpaque< Function1 >( environment ){ +} }; /// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer and one other argument. -template +template class PointerCaller1 : public BindFirstOpaque1< Function2 > { public: - PointerCaller1(Environment* environment) : BindFirstOpaque1< Function2 >(environment) - { - } +PointerCaller1( Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ +} }; /// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer and one other argument. -template +template class ConstPointerCaller1 : public BindFirstOpaque1< Function2 > { public: - ConstPointerCaller1(const Environment* environment) : BindFirstOpaque1< Function2 >(environment) - { - } +ConstPointerCaller1( const Environment* environment ) : BindFirstOpaque1< Function2 >( environment ){ +} }; /// \brief Forms a Callback from a free function which takes no arguments. -template +template class FreeCaller : public BindFirstOpaque< Caller0To1< Function0 > > { public: - FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >(0) - { - } +FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >( 0 ){ +} }; /// \brief Forms a Callback from a free function which takes a single argument. -template +template class FreeCaller1 : public BindFirstOpaque1< Caller1To2< Function1 > > { public: - FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >(0) - { - } +FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >( 0 ){ +} }; /// \brief Constructs a Callback from a non-const \p functor with zero arguments. -/// +/// /// \param Functor Must define \c operator()(). template -inline Callback makeCallback(Functor& functor) -{ - return Callback(MemberCaller(functor)); +inline Callback makeCallback( Functor& functor ){ + return Callback( MemberCaller( functor ) ); } /// \brief Constructs a Callback from a const \p functor with zero arguments. -/// +/// /// \param Functor Must define const \c operator()(). template -inline Callback makeCallback(const Functor& functor) -{ - return Callback(ConstMemberCaller(functor)); +inline Callback makeCallback( const Functor& functor ){ + return Callback( ConstMemberCaller( functor ) ); } /// \brief Constructs a Callback1 from a non-const \p functor with one argument. -/// +/// /// \param Functor Must define \c first_argument_type and \c operator()(first_argument_type). template -inline Callback1 makeCallback1(Functor& functor) -{ - typedef typename Functor::first_argument_type FirstArgument; - return Callback1(MemberCaller1(functor)); +inline Callback1 makeCallback1( Functor& functor ){ + typedef typename Functor::first_argument_type FirstArgument; + return Callback1( MemberCaller1( functor ) ); } /// \brief Constructs a Callback1 from a const \p functor with one argument. -/// +/// /// \param Functor Must define \c first_argument_type and const \c operator()(first_argument_type). template -inline Callback1 makeCallback1(const Functor& functor) -{ - typedef typename Functor::first_argument_type FirstArgument; - return Callback1(ConstMemberCaller1(functor)); +inline Callback1 makeCallback1( const Functor& functor ){ + typedef typename Functor::first_argument_type FirstArgument; + return Callback1( ConstMemberCaller1( functor ) ); } diff --git a/libs/generic/callbackfwd.cpp b/libs/generic/callbackfwd.cpp index a2faa664..af157742 100644 --- a/libs/generic/callbackfwd.cpp +++ b/libs/generic/callbackfwd.cpp @@ -1,3 +1,2 @@ #include "callbackfwd.h" - diff --git a/libs/generic/callbackfwd.h b/libs/generic/callbackfwd.h index f89f9090..48c01d39 100644 --- a/libs/generic/callbackfwd.h +++ b/libs/generic/callbackfwd.h @@ -1,5 +1,5 @@ -#if !defined(INCLUDED_CALLBACKFWD_H) +#if !defined( INCLUDED_CALLBACKFWD_H ) #define INCLUDED_CALLBACKFWD_H template diff --git a/libs/generic/constant.cpp b/libs/generic/constant.cpp index ff54c9cc..7c3c2fa6 100644 --- a/libs/generic/constant.cpp +++ b/libs/generic/constant.cpp @@ -1,40 +1,40 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "constant.h" -#if defined(_DEBUG) || defined(DOXYGEN) +#if defined( _DEBUG ) || defined( DOXYGEN ) namespace ExampleConstant { - class Bleh - { - public: +class Bleh +{ +public: - STRING_CONSTANT(Name, "Bleh"); - INTEGER_CONSTANT(Version, 1); - }; +STRING_CONSTANT( Name, "Bleh" ); +INTEGER_CONSTANT( Version, 1 ); +}; - int version = Bleh::Version(); - const char* name = Bleh::Name(); +int version = Bleh::Version(); +const char* name = Bleh::Name(); } #endif diff --git a/libs/generic/constant.h b/libs/generic/constant.h index 42b2fa5d..83817947 100644 --- a/libs/generic/constant.h +++ b/libs/generic/constant.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_CONSTANT_H) +#if !defined( INCLUDED_GENERIC_CONSTANT_H ) #define INCLUDED_GENERIC_CONSTANT_H /// \file @@ -29,22 +29,21 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template struct ConstantWrapper { - typedef typename Type::Value Value; - operator Value() const - { - return Type::evaluate(); - } + typedef typename Type::Value Value; + operator Value() const + { + return Type::evaluate(); + } }; template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const ConstantWrapper& c) -{ - return ostream_write(ostream, typename Type::Value(c)); +inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const ConstantWrapper& c ){ + return ostream_write( ostream, typename Type::Value( c ) ); } -#define TYPE_CONSTANT(name, value, type) struct name##_CONSTANT_ { typedef type Value; static Value evaluate() { return value; } }; typedef ConstantWrapper name -#define STRING_CONSTANT(name, value) TYPE_CONSTANT(name, value, const char*) -#define INTEGER_CONSTANT(name, value) TYPE_CONSTANT(name, value, int) +#define TYPE_CONSTANT( name, value, type ) struct name ## _CONSTANT_ { typedef type Value; static Value evaluate() { return value; } }; typedef ConstantWrapper name +#define STRING_CONSTANT( name, value ) TYPE_CONSTANT ( name, value, const char* ) +#define INTEGER_CONSTANT( name, value ) TYPE_CONSTANT ( name, value, int ) -STRING_CONSTANT(EmptyString, ""); +STRING_CONSTANT( EmptyString, "" ); #endif diff --git a/libs/generic/enumeration.cpp b/libs/generic/enumeration.cpp index 4591fda9..c6071cd4 100644 --- a/libs/generic/enumeration.cpp +++ b/libs/generic/enumeration.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "enumeration.h" - diff --git a/libs/generic/enumeration.h b/libs/generic/enumeration.h index 31e43052..8d6c75eb 100644 --- a/libs/generic/enumeration.h +++ b/libs/generic/enumeration.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_ENUMERATION_H) +#if !defined( INCLUDED_GENERIC_ENUMERATION_H ) #define INCLUDED_GENERIC_ENUMERATION_H /// \file @@ -35,26 +35,22 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class EnumeratedValue : public Enumeration { - typename Enumeration::Value m_value; +typename Enumeration::Value m_value; public: - explicit EnumeratedValue(typename Enumeration::Value value) : m_value(value) - { - } - typename Enumeration::Value get() const - { - return m_value; - } +explicit EnumeratedValue( typename Enumeration::Value value ) : m_value( value ){ +} +typename Enumeration::Value get() const { + return m_value; +} }; template -inline bool operator==(EnumeratedValue self, EnumeratedValue other) -{ - return self.get() == other.get(); +inline bool operator==( EnumeratedValue self, EnumeratedValue other ){ + return self.get() == other.get(); } template -inline bool operator!=(EnumeratedValue self, EnumeratedValue other) -{ - return !operator==(self, other); +inline bool operator!=( EnumeratedValue self, EnumeratedValue other ){ + return !operator==( self, other ); } #endif diff --git a/libs/generic/functional.cpp b/libs/generic/functional.cpp index 4717c8e2..e6cc8572 100644 --- a/libs/generic/functional.cpp +++ b/libs/generic/functional.cpp @@ -1,3 +1,2 @@ #include "functional.h" - diff --git a/libs/generic/functional.h b/libs/generic/functional.h index bd253486..940d4e7f 100644 --- a/libs/generic/functional.h +++ b/libs/generic/functional.h @@ -1,312 +1,288 @@ -#if !defined(INCLUDED_FUNCTIONAL_H) +#if !defined( INCLUDED_FUNCTIONAL_H ) #define INCLUDED_FUNCTIONAL_H -template +template class Member { public: - typedef Object& first_argument_type; - typedef R result_type; - static result_type call(first_argument_type object) - { - return (object.*member)(); - } +typedef Object& first_argument_type; +typedef R result_type; +static result_type call( first_argument_type object ){ + return ( object.*member )(); +} }; -template +template class ConstMember { public: - typedef const Object& first_argument_type; - typedef R result_type; - static result_type call(first_argument_type object) - { - return (object.*member)(); - } +typedef const Object& first_argument_type; +typedef R result_type; +static result_type call( first_argument_type object ){ + return ( object.*member )(); +} }; -template +template class Member1 { public: - typedef Object& first_argument_type; - typedef A1 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a1) - { - return (object.*member)(a1); - } +typedef Object& first_argument_type; +typedef A1 second_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a1 ){ + return ( object.*member )( a1 ); +} }; -template +template class ConstMember1 { public: - typedef const Object& first_argument_type; - typedef A1 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a1) - { - return (object.*member)(a1); - } +typedef const Object& first_argument_type; +typedef A1 second_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a1 ){ + return ( object.*member )( a1 ); +} }; -template +template class Member2 { public: - typedef Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) - { - return (object.*member)(a2, a3); - } +typedef Object& first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ + return ( object.*member )( a2, a3 ); +} }; -template +template class ConstMember2 { public: - typedef const Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) - { - return (object.*member)(a2, a3); - } +typedef const Object& first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3 ){ + return ( object.*member )( a2, a3 ); +} }; -template +template class Member3 { public: - typedef Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (object.*member)(a2, a3, a4); - } +typedef Object& first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef A4 fourth_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return ( object.*member )( a2, a3, a4 ); +} }; -template +template class ConstMember3 { public: - typedef const Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (object.*member)(a2, a3, a4); - } +typedef const Object& first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef A4 fourth_argument_type; +typedef R result_type; +static result_type call( first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return ( object.*member )( a2, a3, a4 ); +} }; -template +template class Function0 { public: - typedef R result_type; - static result_type call() - { - return (func)(); - } +typedef R result_type; +static result_type call(){ + return (func)( ); +} }; -template +template class Function1 { public: - typedef A1 first_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1) - { - return (func)(a1); - } +typedef A1 first_argument_type; +typedef R result_type; +static result_type call( first_argument_type a1 ){ + return (func)( a1 ); +} }; -template +template class Function2 { public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2) - { - return (func)(a1, a2); - } +typedef A1 first_argument_type; +typedef A2 second_argument_type; +typedef R result_type; +static result_type call( first_argument_type a1, second_argument_type a2 ){ + return (func)( a1, a2 ); +} }; -template +template class Function3 { public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3) - { - return (func)(a1, a2, a3); - } +typedef A1 first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef R result_type; +static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3 ){ + return (func)( a1, a2, a3 ); +} }; -template +template class Function4 { public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (func)(a1, a2, a3, a4); - } +typedef A1 first_argument_type; +typedef A2 second_argument_type; +typedef A3 third_argument_type; +typedef A4 fourth_argument_type; +typedef R result_type; +static result_type call( first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return (func)( a1, a2, a3, a4 ); +} }; -template +template class Caller0To1 { public: - typedef FirstArgument first_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type) - { - return Caller::call(); - } +typedef FirstArgument first_argument_type; +typedef typename Caller::result_type result_type; +static result_type call( first_argument_type ){ + return Caller::call(); +} }; -template +template class Caller1To2 { public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2) - { - return Caller::call(a2); - } +typedef FirstArgument first_argument_type; +typedef typename Caller::first_argument_type second_argument_type; +typedef typename Caller::result_type result_type; +static result_type call( first_argument_type, second_argument_type a2 ){ + return Caller::call( a2 ); +} }; -template +template class Caller2To3 { public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::second_argument_type third_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3) - { - return Caller::call(a2, a3); - } +typedef FirstArgument first_argument_type; +typedef typename Caller::first_argument_type second_argument_type; +typedef typename Caller::second_argument_type third_argument_type; +typedef typename Caller::result_type result_type; +static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3 ){ + return Caller::call( a2, a3 ); +} }; -template +template class Caller3To4 { public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::second_argument_type third_argument_type; - typedef typename Caller::third_argument_type fourth_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return Caller::call(a2, a3, a4); - } +typedef FirstArgument first_argument_type; +typedef typename Caller::first_argument_type second_argument_type; +typedef typename Caller::second_argument_type third_argument_type; +typedef typename Caller::third_argument_type fourth_argument_type; +typedef typename Caller::result_type result_type; +static result_type call( first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4 ){ + return Caller::call( a2, a3, a4 ); +} }; template class FunctorInvoke { public: - typedef typename Functor::result_type result_type; - inline result_type operator()(Functor functor) - { - return functor(); - } +typedef typename Functor::result_type result_type; +inline result_type operator()( Functor functor ){ + return functor(); +} }; template class Functor1Invoke { - typename Functor::first_argument_type a1; +typename Functor::first_argument_type a1; public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::result_type result_type; - Functor1Invoke(first_argument_type a1) : a1(a1) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1); - } +typedef typename Functor::first_argument_type first_argument_type; +typedef typename Functor::result_type result_type; +Functor1Invoke( first_argument_type a1 ) : a1( a1 ){ +} +inline result_type operator()( Functor functor ){ + return functor( a1 ); +} }; template class Functor2Invoke { - typename Functor::first_argument_type a1; - typename Functor::second_argument_type a2; +typename Functor::first_argument_type a1; +typename Functor::second_argument_type a2; public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::second_argument_type second_argument_type; - typedef typename Functor::result_type result_type; - Functor2Invoke(first_argument_type a1, second_argument_type a2) - : a1(a1), a2(a2) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1, a2); - } +typedef typename Functor::first_argument_type first_argument_type; +typedef typename Functor::second_argument_type second_argument_type; +typedef typename Functor::result_type result_type; +Functor2Invoke( first_argument_type a1, second_argument_type a2 ) + : a1( a1 ), a2( a2 ){ +} +inline result_type operator()( Functor functor ){ + return functor( a1, a2 ); +} }; template class Functor3Invoke { - typename Functor::first_argument_type a1; - typename Functor::second_argument_type a2; - typename Functor::third_argument_type a3; +typename Functor::first_argument_type a1; +typename Functor::second_argument_type a2; +typename Functor::third_argument_type a3; public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::second_argument_type second_argument_type; - typedef typename Functor::third_argument_type third_argument_type; - typedef typename Functor::result_type result_type; - Functor3Invoke(first_argument_type a1, second_argument_type a2, third_argument_type a3) - : a1(a1), a2(a2), a3(a3) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1, a2, a3); - } +typedef typename Functor::first_argument_type first_argument_type; +typedef typename Functor::second_argument_type second_argument_type; +typedef typename Functor::third_argument_type third_argument_type; +typedef typename Functor::result_type result_type; +Functor3Invoke( first_argument_type a1, second_argument_type a2, third_argument_type a3 ) + : a1( a1 ), a2( a2 ), a3( a3 ){ +} +inline result_type operator()( Functor functor ){ + return functor( a1, a2, a3 ); +} }; template class TypeEqual { public: - typedef False type; +typedef False type; }; template class TypeEqual { public: - typedef True type; +typedef True type; }; diff --git a/libs/generic/object.cpp b/libs/generic/object.cpp index a6ed31c0..bbb56108 100644 --- a/libs/generic/object.cpp +++ b/libs/generic/object.cpp @@ -1,41 +1,39 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "object.h" namespace { - class Blah - { - int i; - public: - Blah() - { - i = 3; - } - }; +class Blah +{ +int i; +public: +Blah(){ + i = 3; +} +}; - void Test() - { - char storage[sizeof(Blah)]; - constructor(*reinterpret_cast(storage)); - } +void Test(){ + char storage[sizeof( Blah )]; + constructor( *reinterpret_cast( storage ) ); +} } \ No newline at end of file diff --git a/libs/generic/object.h b/libs/generic/object.h index ec8e7262..5677a0e3 100644 --- a/libs/generic/object.h +++ b/libs/generic/object.h @@ -1,96 +1,86 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_OBJECT_H) +#if !defined( INCLUDED_GENERIC_OBJECT_H ) #define INCLUDED_GENERIC_OBJECT_H /// \file -/// \brief Convenience functions (syntactic sugar) to wrap explicit constructor (aka in-place 'new') and destructor calls. +/// \brief Convenience functions (syntactic sugar) to wrap explicit constructor (aka in-place 'new') and destructor calls. /// /// Use makeReference() to wrap non-const-reference constructor parameters. -#if _MSC_VER > 1000 && defined(WIN32) +#if _MSC_VER > 1000 && defined( WIN32 ) #pragma warning(disable:4345) // behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized #endif #include template -inline void constructor(Type& object) -{ - new(&object) Type(); +inline void constructor( Type& object ){ + new( &object )Type(); } template -inline void constructor(Type& object, const T1& t1) -{ - new(&object) Type(t1); +inline void constructor( Type& object, const T1& t1 ){ + new( &object )Type( t1 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2) -{ - new(&object) Type(t1, t2); +inline void constructor( Type& object, const T1& t1, const T2& t2 ){ + new( &object )Type( t1, t2 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3) -{ - new(&object) Type(t1, t2, t3); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3 ){ + new( &object )Type( t1, t2, t3 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4) -{ - new(&object) Type(t1, t2, t3, t4); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ + new( &object )Type( t1, t2, t3, t4 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) -{ - new(&object) Type(t1, t2, t3, t4, t5); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ + new( &object )Type( t1, t2, t3, t4, t5 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) -{ - new(&object) Type(t1, t2, t3, t4, t5, t6); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6 ){ + new( &object )Type( t1, t2, t3, t4, t5, t6 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) -{ - new(&object) Type(t1, t2, t3, t4, t5, t6, t7); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7 ){ + new( &object )Type( t1, t2, t3, t4, t5, t6, t7 ); } template -inline void constructor(Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) -{ - new(&object) Type(t1, t2, t3, t4, t5, t6, t7, t8); +inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8 ){ + new( &object )Type( t1, t2, t3, t4, t5, t6, t7, t8 ); } template -inline void destructor(Type& object) -{ - object.~Type(); +inline void destructor( Type& object ){ + object.~Type(); } diff --git a/libs/generic/reference.cpp b/libs/generic/reference.cpp index c09cad82..fd64f288 100644 --- a/libs/generic/reference.cpp +++ b/libs/generic/reference.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "reference.h" diff --git a/libs/generic/reference.h b/libs/generic/reference.h index 62e2c238..df5a05a8 100644 --- a/libs/generic/reference.h +++ b/libs/generic/reference.h @@ -1,71 +1,65 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_REFERENCE_H) +#if !defined( INCLUDED_GENERIC_REFERENCE_H ) #define INCLUDED_GENERIC_REFERENCE_H /// \file -/// \brief Wrappers to allow storing objects in templated containers using 'reference' semantics. +/// \brief Wrappers to allow storing objects in templated containers using 'reference' semantics. /// \brief A reference to a mutable object. /// Has 'reference' semantics, except for \c 'operator==' and \c 'operator.'. /// \param Type The type of the referenced object. template class Reference -{ - Type* m_contained; +{ +Type* m_contained; public: - explicit Reference(Type& contained) : m_contained(&contained) - { - } - operator Type&() const - { - return *m_contained; - } - Type& get() const - { - return *m_contained; - } - Type* get_pointer() const - { - return m_contained; - } +explicit Reference( Type& contained ) : m_contained( &contained ){ +} +operator Type&() const +{ + return *m_contained; +} +Type& get() const { + return *m_contained; +} +Type* get_pointer() const { + return m_contained; +} }; template -bool operator<(const Reference& self, const Reference& other) -{ - return self.get() < other.get(); +bool operator<( const Reference& self, const Reference& other ){ + return self.get() < other.get(); } template -bool operator==(const Reference& self, const Reference& other) -{ - return self.get() == other.get(); +bool operator==( const Reference& self, const Reference& other ){ + return self.get() == other.get(); } /// \brief construct a reference to a mutable object. template -inline Reference makeReference(Type& value) -{ - return Reference(value); +inline Reference makeReference( Type& value ){ + return Reference( value ); } /// \brief A reference to a non-mutable object. @@ -74,41 +68,35 @@ inline Reference makeReference(Type& value) template class ConstReference { - const Type* m_contained; +const Type* m_contained; public: - explicit ConstReference(const Type& contained) : m_contained(&contained) - { - } - operator const Type&() const - { - return *m_contained; - } - const Type& get() const - { - return *m_contained; - } - const Type* get_pointer() const - { - return m_contained; - } +explicit ConstReference( const Type& contained ) : m_contained( &contained ){ +} +operator const Type&() const +{ + return *m_contained; +} +const Type& get() const { + return *m_contained; +} +const Type* get_pointer() const { + return m_contained; +} }; template -bool operator<(const ConstReference& self, const ConstReference& other) -{ - return self.get() < other.get(); +bool operator<( const ConstReference& self, const ConstReference& other ){ + return self.get() < other.get(); } template -bool operator==(const ConstReference& self, const ConstReference& other) -{ - return self.get() == other.get(); +bool operator==( const ConstReference& self, const ConstReference& other ){ + return self.get() == other.get(); } /// \brief construct a reference to a non-mutable object. template -inline ConstReference makeReference(const Type& value) -{ - return ConstReference(value); +inline ConstReference makeReference( const Type& value ){ + return ConstReference( value ); } diff --git a/libs/generic/referencecounted.cpp b/libs/generic/referencecounted.cpp index 757e08d8..0c531bd7 100644 --- a/libs/generic/referencecounted.cpp +++ b/libs/generic/referencecounted.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "referencecounted.h" diff --git a/libs/generic/referencecounted.h b/libs/generic/referencecounted.h index e761cccc..37abd91f 100644 --- a/libs/generic/referencecounted.h +++ b/libs/generic/referencecounted.h @@ -1,29 +1,29 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_REFERENCECOUNTED_H) +#if !defined( INCLUDED_GENERIC_REFERENCECOUNTED_H ) #define INCLUDED_GENERIC_REFERENCECOUNTED_H /// \file -/// \brief 'smart' pointers and references. +/// \brief 'smart' pointers and references. #include @@ -31,97 +31,82 @@ template class IncRefDecRefCounter { public: - void increment(Type& value) - { - value.IncRef(); - } - void decrement(Type& value) - { - value.DecRef(); - } +void increment( Type& value ){ + value.IncRef(); +} +void decrement( Type& value ){ + value.DecRef(); +} }; /// \brief A smart-pointer that uses a counter stored in the object pointed-to. template > class SmartPointer : public Counter { - Type* m_value; +Type* m_value; public: - SmartPointer(const SmartPointer& other) - : m_value(other.m_value) - { - Counter::increment(*m_value); - } - explicit SmartPointer(Type* value) - : m_value(value) - { - Counter::increment(*m_value); - } - ~SmartPointer() - { - Counter::decrement(*m_value); - } - SmartPointer& operator=(const SmartPointer& other) - { - SmartPointer temp(other); - temp.swap(*this); - return *this; - } - SmartPointer& operator=(Type* value) - { - SmartPointer temp(value); - temp.swap(*this); - return *this; - } - void swap(SmartPointer& other) - { - std::swap(m_value, other.m_value); - } - - operator Type*() const - { - return m_value; - } - Type& operator*() const - { - return *m_value; - } - Type* operator->() const - { - return m_value; - } - Type* get() const - { - return m_value; - } +SmartPointer( const SmartPointer& other ) + : m_value( other.m_value ){ + Counter::increment( *m_value ); +} +explicit SmartPointer( Type* value ) + : m_value( value ){ + Counter::increment( *m_value ); +} +~SmartPointer(){ + Counter::decrement( *m_value ); +} +SmartPointer& operator=( const SmartPointer& other ){ + SmartPointer temp( other ); + temp.swap( *this ); + return *this; +} +SmartPointer& operator=( Type* value ){ + SmartPointer temp( value ); + temp.swap( *this ); + return *this; +} +void swap( SmartPointer& other ){ + std::swap( m_value, other.m_value ); +} + +operator Type*() const +{ + return m_value; +} +Type& operator*() const { + return *m_value; +} +Type* operator->() const { + return m_value; +} +Type* get() const { + return m_value; +} }; template -inline bool operator<(const SmartPointer& self, const SmartPointer& other) -{ - return self.get() < other.get(); +inline bool operator<( const SmartPointer& self, const SmartPointer& other ){ + return self.get() < other.get(); } template -inline bool operator==(const SmartPointer& self, const SmartPointer& other) -{ - return self.get() == other.get(); +inline bool operator==( const SmartPointer& self, const SmartPointer& other ){ + return self.get() == other.get(); } template -inline bool operator!=(const SmartPointer& self, const SmartPointer& other) -{ - return !::operator==(self, other); +inline bool operator!=( const SmartPointer& self, const SmartPointer& other ){ + return !::operator==( self, other ); } namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap(). - template - inline void swap(SmartPointer& self, SmartPointer& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap(). +template +inline void swap( SmartPointer& self, SmartPointer& other ){ + self.swap( other ); +} } @@ -129,79 +114,67 @@ namespace std template > class SmartReference : public Counter { - Type* m_value; +Type* m_value; public: - SmartReference(const SmartReference& other) - : m_value(other.m_value) - { - Counter::increment(*m_value); - } - explicit SmartReference(Type& value) - : m_value(&value) - { - Counter::increment(*m_value); - } - ~SmartReference() - { - Counter::decrement(*m_value); - } - SmartReference& operator=(const SmartReference& other) - { - SmartReference temp(other); - temp.swap(*this); - return *this; - } - SmartReference& operator=(Type& value) - { - SmartReference temp(value); - temp.swap(*this); - return *this; - } - void swap(SmartReference& other) - { - std::swap(m_value, other.m_value); - } - - operator Type&() const - { - return *m_value; - } - Type& get() const - { - return *m_value; - } - Type* get_pointer() const - { - return m_value; - } +SmartReference( const SmartReference& other ) + : m_value( other.m_value ){ + Counter::increment( *m_value ); +} +explicit SmartReference( Type& value ) + : m_value( &value ){ + Counter::increment( *m_value ); +} +~SmartReference(){ + Counter::decrement( *m_value ); +} +SmartReference& operator=( const SmartReference& other ){ + SmartReference temp( other ); + temp.swap( *this ); + return *this; +} +SmartReference& operator=( Type& value ){ + SmartReference temp( value ); + temp.swap( *this ); + return *this; +} +void swap( SmartReference& other ){ + std::swap( m_value, other.m_value ); +} + +operator Type&() const +{ + return *m_value; +} +Type& get() const { + return *m_value; +} +Type* get_pointer() const { + return m_value; +} }; template -inline bool operator<(const SmartReference& self, const SmartReference& other) -{ - return self.get() < other.get(); +inline bool operator<( const SmartReference& self, const SmartReference& other ){ + return self.get() < other.get(); } template -inline bool operator==(const SmartReference& self, const SmartReference& other) -{ - return self.get() == other.get(); +inline bool operator==( const SmartReference& self, const SmartReference& other ){ + return self.get() == other.get(); } template -inline bool operator!=(const SmartReference& self, const SmartReference& other) -{ - return !::operator==(self, other); +inline bool operator!=( const SmartReference& self, const SmartReference& other ){ + return !::operator==( self, other ); } namespace std { - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap(). - template - inline void swap(SmartReference& self, SmartReference& other) - { - self.swap(other); - } +/// \brief Swaps the values of \p self and \p other. +/// Overloads std::swap(). +template +inline void swap( SmartReference& self, SmartReference& other ){ + self.swap( other ); +} } #endif diff --git a/libs/generic/static.cpp b/libs/generic/static.cpp index ecd539f3..b32972de 100644 --- a/libs/generic/static.cpp +++ b/libs/generic/static.cpp @@ -1,133 +1,124 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "static.h" -#if defined(_DEBUG) || defined(DOXYGEN) +#if defined( _DEBUG ) || defined( DOXYGEN ) namespace ExampleStatic { - // Static example - // ---- myclass.h - class MyClass - { - public: - int value; - MyClass() : value(3) - { - } - }; - - typedef Static StaticMyClass; - - // ---- main.cpp - class DynamicInitialisation - { - public: - DynamicInitialisation() - { - // StaticMyClass::instance() may be invalid here because construction order is undefined - } - }; - - DynamicInitialisation g_dynamicInitialisation; - - void duringMain() - { - int bar = StaticMyClass::instance().value; - } - // end example +// Static example +// ---- myclass.h +class MyClass +{ +public: +int value; +MyClass() : value( 3 ){ +} +}; + +typedef Static StaticMyClass; + +// ---- main.cpp +class DynamicInitialisation +{ +public: +DynamicInitialisation(){ + // StaticMyClass::instance() may be invalid here because construction order is undefined +} +}; + +DynamicInitialisation g_dynamicInitialisation; + +void duringMain(){ + int bar = StaticMyClass::instance().value; +} +// end example } namespace ExampleLazyStatic { - // LazyStatic example - // ---- myclass.h - class MyClass - { - public: - int value; - MyClass() : value(3) - { - } - // destructor will never be called - }; - - typedef LazyStatic StaticMyClass; - - // ---- main.cpp - class DynamicInitialisation - { - public: - DynamicInitialisation() - { - int bar = StaticMyClass::instance().value; - } - }; - - DynamicInitialisation g_dynamicInitialisation; - - void duringMain() - { - int bar = StaticMyClass::instance().value; - } - // end example +// LazyStatic example +// ---- myclass.h +class MyClass +{ +public: +int value; +MyClass() : value( 3 ){ +} +// destructor will never be called +}; + +typedef LazyStatic StaticMyClass; + +// ---- main.cpp +class DynamicInitialisation +{ +public: +DynamicInitialisation(){ + int bar = StaticMyClass::instance().value; +} +}; + +DynamicInitialisation g_dynamicInitialisation; + +void duringMain(){ + int bar = StaticMyClass::instance().value; +} +// end example } namespace ExampleSmartStatic { - // SmartStatic example - // ---- myclass.h - class MyClass - { - public: - int value; - MyClass() : value(3) - { - } - }; - - typedef CountedStatic StaticMyClass; - - // ---- main.cpp - class DynamicInitialisation - { - public: - DynamicInitialisation() - { - // StaticMyClass::instance() is invalid before the ref is constructed - SmartStatic ref; - int bar = ref.instance().value; - - SmartStatic ref2; // any number of instances are allowed. - } - }; - - DynamicInitialisation g_dynamicInitialisation; - - void duringMain() - { - int bar = SmartStatic().instance().value; // an instance can be a temporary - } - // end example +// SmartStatic example +// ---- myclass.h +class MyClass +{ +public: +int value; +MyClass() : value( 3 ){ +} +}; + +typedef CountedStatic StaticMyClass; + +// ---- main.cpp +class DynamicInitialisation +{ +public: +DynamicInitialisation(){ + // StaticMyClass::instance() is invalid before the ref is constructed + SmartStatic ref; + int bar = ref.instance().value; + + SmartStatic ref2; // any number of instances are allowed. +} +}; + +DynamicInitialisation g_dynamicInitialisation; + +void duringMain(){ + int bar = SmartStatic().instance().value; // an instance can be a temporary +} +// end example } #endif diff --git a/libs/generic/static.h b/libs/generic/static.h index 81691827..ad501fc3 100644 --- a/libs/generic/static.h +++ b/libs/generic/static.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GENERIC_STATIC_H) +#if !defined( INCLUDED_GENERIC_STATIC_H ) #define INCLUDED_GENERIC_STATIC_H /// \file @@ -42,12 +42,11 @@ class Null template class Static { - static Type m_instance; +static Type m_instance; public: - static Type& instance() - { - return m_instance; - } +static Type& instance(){ + return m_instance; +} }; template @@ -66,20 +65,18 @@ Type Static::m_instance; template class LazyStatic { - static Type* m_instance; // this will be initialised to 0 by the CRT, according to the c++ standard +static Type* m_instance; // this will be initialised to 0 by the CRT, according to the c++ standard public: - static Type& instance() - { - if(m_instance == 0) - { - m_instance = new Type; // allocate using 'new' to get the correct alignment - } - return *m_instance; - } +static Type& instance(){ + if ( m_instance == 0 ) { + m_instance = new Type; // allocate using 'new' to get the correct alignment + } + return *m_instance; +} }; template -Type* LazyStatic::m_instance; +Type * LazyStatic::m_instance; /// \brief A singleton which keeps a count of the number of times it is referenced. @@ -92,33 +89,28 @@ Type* LazyStatic::m_instance; template class CountedStatic { - static std::size_t m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard - static Type* m_instance; +static std::size_t m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard +static Type* m_instance; public: - static Type& instance() - { - return *m_instance; - } - static void capture() - { - if(++m_refcount == 1) - { - m_instance = new Type; // allocate using 'new' to get the correct alignment - } - } - static void release() - { - if(--m_refcount == 0) - { - delete m_instance; - } - } +static Type& instance(){ + return *m_instance; +} +static void capture(){ + if ( ++m_refcount == 1 ) { + m_instance = new Type; // allocate using 'new' to get the correct alignment + } +} +static void release(){ + if ( --m_refcount == 0 ) { + delete m_instance; + } +} }; template std::size_t CountedStatic::m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard template -Type* CountedStatic::m_instance; +Type * CountedStatic::m_instance; /// \brief A reference to a CountedStatic. /// Guarantees that CountedStatic will be constructed for the lifetime of this object. @@ -133,18 +125,15 @@ template class SmartStatic { public: - SmartStatic() - { - CountedStatic::capture(); - } - ~SmartStatic() - { - CountedStatic::release(); - } - Type& instance() - { - return CountedStatic::instance(); - } +SmartStatic(){ + CountedStatic::capture(); +} +~SmartStatic(){ + CountedStatic::release(); +} +Type& instance(){ + return CountedStatic::instance(); +} }; diff --git a/libs/generic/vector.cpp b/libs/generic/vector.cpp index 83765dcb..fbafd538 100644 --- a/libs/generic/vector.cpp +++ b/libs/generic/vector.cpp @@ -1,3 +1,2 @@ #include "vector.h" - diff --git a/libs/generic/vector.h b/libs/generic/vector.h index 6e6f74e2..ea1e3bdb 100644 --- a/libs/generic/vector.h +++ b/libs/generic/vector.h @@ -1,5 +1,5 @@ -#if !defined(INCLUDED_VECTOR_H) +#if !defined( INCLUDED_VECTOR_H ) #define INCLUDED_VECTOR_H #include @@ -7,243 +7,196 @@ template class BasicVector2 { - Element m_elements[2]; +Element m_elements[2]; public: - BasicVector2() - { - } - BasicVector2(const Element& x_, const Element& y_) - { - x() = x_; - y() = y_; - } +BasicVector2(){ +} +BasicVector2( const Element& x_, const Element& y_ ){ + x() = x_; + y() = y_; +} - Element& x() - { - return m_elements[0]; - } - const Element& x() const - { - return m_elements[0]; - } - Element& y() - { - return m_elements[1]; - } - const Element& y() const - { - return m_elements[1]; - } +Element& x(){ + return m_elements[0]; +} +const Element& x() const { + return m_elements[0]; +} +Element& y(){ + return m_elements[1]; +} +const Element& y() const { + return m_elements[1]; +} - const Element& operator[](std::size_t i) const - { - return m_elements[i]; - } - Element& operator[](std::size_t i) - { - return m_elements[i]; - } +const Element& operator[]( std::size_t i ) const { + return m_elements[i]; +} +Element& operator[]( std::size_t i ){ + return m_elements[i]; +} - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } +Element* data(){ + return m_elements; +} +const Element* data() const { + return m_elements; +} }; /// \brief A 3-element vector. template class BasicVector3 { - Element m_elements[3]; +Element m_elements[3]; public: - BasicVector3() - { - } - template - BasicVector3(const BasicVector3& other) - { - x() = static_cast(other.x()); - y() = static_cast(other.y()); - z() = static_cast(other.z()); - } - BasicVector3(const Element& x_, const Element& y_, const Element& z_) - { - x() = x_; - y() = y_; - z() = z_; - } +BasicVector3(){ +} +template +BasicVector3( const BasicVector3& other ){ + x() = static_cast( other.x() ); + y() = static_cast( other.y() ); + z() = static_cast( other.z() ); +} +BasicVector3( const Element& x_, const Element& y_, const Element& z_ ){ + x() = x_; + y() = y_; + z() = z_; +} - Element& x() - { - return m_elements[0]; - } - const Element& x() const - { - return m_elements[0]; - } - Element& y() - { - return m_elements[1]; - } - const Element& y() const - { - return m_elements[1]; - } - Element& z() - { - return m_elements[2]; - } - const Element& z() const - { - return m_elements[2]; - } +Element& x(){ + return m_elements[0]; +} +const Element& x() const { + return m_elements[0]; +} +Element& y(){ + return m_elements[1]; +} +const Element& y() const { + return m_elements[1]; +} +Element& z(){ + return m_elements[2]; +} +const Element& z() const { + return m_elements[2]; +} - const Element& operator[](std::size_t i) const - { - return m_elements[i]; - } - Element& operator[](std::size_t i) - { - return m_elements[i]; - } +const Element& operator[]( std::size_t i ) const { + return m_elements[i]; +} +Element& operator[]( std::size_t i ){ + return m_elements[i]; +} - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } +Element* data(){ + return m_elements; +} +const Element* data() const { + return m_elements; +} }; /// \brief A 4-element vector. template class BasicVector4 { - Element m_elements[4]; +Element m_elements[4]; public: - BasicVector4() - { - } - BasicVector4(Element x_, Element y_, Element z_, Element w_) - { - x() = x_; - y() = y_; - z() = z_; - w() = w_; - } - BasicVector4(const BasicVector3& self, Element w_) - { - x() = self.x(); - y() = self.y(); - z() = self.z(); - w() = w_; - } +BasicVector4(){ +} +BasicVector4( Element x_, Element y_, Element z_, Element w_ ){ + x() = x_; + y() = y_; + z() = z_; + w() = w_; +} +BasicVector4( const BasicVector3& self, Element w_ ){ + x() = self.x(); + y() = self.y(); + z() = self.z(); + w() = w_; +} - Element& x() - { - return m_elements[0]; - } - const Element& x() const - { - return m_elements[0]; - } - Element& y() - { - return m_elements[1]; - } - const Element& y() const - { - return m_elements[1]; - } - Element& z() - { - return m_elements[2]; - } - const Element& z() const - { - return m_elements[2]; - } - Element& w() - { - return m_elements[3]; - } - const Element& w() const - { - return m_elements[3]; - } +Element& x(){ + return m_elements[0]; +} +const Element& x() const { + return m_elements[0]; +} +Element& y(){ + return m_elements[1]; +} +const Element& y() const { + return m_elements[1]; +} +Element& z(){ + return m_elements[2]; +} +const Element& z() const { + return m_elements[2]; +} +Element& w(){ + return m_elements[3]; +} +const Element& w() const { + return m_elements[3]; +} - Element index(std::size_t i) const - { - return m_elements[i]; - } - Element& index(std::size_t i) - { - return m_elements[i]; - } - Element operator[](std::size_t i) const - { - return m_elements[i]; - } - Element& operator[](std::size_t i) - { - return m_elements[i]; - } +Element index( std::size_t i ) const { + return m_elements[i]; +} +Element& index( std::size_t i ){ + return m_elements[i]; +} +Element operator[]( std::size_t i ) const { + return m_elements[i]; +} +Element& operator[]( std::size_t i ){ + return m_elements[i]; +} - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } +Element* data(){ + return m_elements; +} +const Element* data() const { + return m_elements; +} }; template -inline BasicVector3 vector3_from_array(const Element* array) -{ - return BasicVector3(array[0], array[1], array[2]); +inline BasicVector3 vector3_from_array( const Element* array ){ + return BasicVector3( array[0], array[1], array[2] ); } template -inline Element* vector3_to_array(BasicVector3& self) -{ - return self.data(); +inline Element* vector3_to_array( BasicVector3& self ){ + return self.data(); } template -inline const Element* vector3_to_array(const BasicVector3& self) -{ - return self.data(); +inline const Element* vector3_to_array( const BasicVector3& self ){ + return self.data(); } template -inline Element* vector4_to_array(BasicVector4& self) -{ - return self.data(); +inline Element* vector4_to_array( BasicVector4& self ){ + return self.data(); } template -inline const Element* vector4_to_array(const BasicVector4& self) -{ - return self.data(); +inline const Element* vector4_to_array( const BasicVector4& self ){ + return self.data(); } template -inline BasicVector3& vector4_to_vector3(BasicVector4& self) -{ - return *reinterpret_cast*>(vector4_to_array(self)); +inline BasicVector3& vector4_to_vector3( BasicVector4& self ){ + return *reinterpret_cast*>( vector4_to_array( self ) ); } template -inline const BasicVector3& vector4_to_vector3(const BasicVector4& self) -{ - return *reinterpret_cast*>(vector4_to_array(self)); +inline const BasicVector3& vector4_to_vector3( const BasicVector4& self ){ + return *reinterpret_cast*>( vector4_to_array( self ) ); } /// \brief A 2-element vector stored in single-precision floating-point. diff --git a/libs/gtkutil/accelerator.cpp b/libs/gtkutil/accelerator.cpp index 214cc36c..bba9ebe3 100644 --- a/libs/gtkutil/accelerator.cpp +++ b/libs/gtkutil/accelerator.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "accelerator.h" @@ -39,106 +39,95 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -const char* global_keys_find(unsigned int key) -{ - const char *s; - if(key == 0) - return ""; - s = gdk_keyval_name(key); - if(!s) - return ""; - return s; +const char* global_keys_find( unsigned int key ){ + const char *s; + if ( key == 0 ) { + return ""; + } + s = gdk_keyval_name( key ); + if ( !s ) { + return ""; + } + return s; } -unsigned int global_keys_find(const char* name) -{ - guint k; - if(!name || !*name) - return 0; - k = gdk_keyval_from_name(name); - if(k == GDK_VoidSymbol) - return 0; - return k; +unsigned int global_keys_find( const char* name ){ + guint k; + if ( !name || !*name ) { + return 0; + } + k = gdk_keyval_from_name( name ); + if ( k == GDK_VoidSymbol ) { + return 0; + } + return k; } -void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream) -{ +void accelerator_write( const Accelerator& accelerator, TextOutputStream& ostream ){ #if 0 - if(accelerator.modifiers & GDK_SHIFT_MASK) - { - ostream << "Shift + "; - } - if(accelerator.modifiers & GDK_MOD1_MASK) - { - ostream << "Alt + "; - } - if(accelerator.modifiers & GDK_CONTROL_MASK) - { - ostream << "Control + "; - } - - const char* keyName = global_keys_find(accelerator.key); - if(!string_empty(keyName)) - { - ostream << keyName; - } - else - { - ostream << static_cast(accelerator.key); - } + if ( accelerator.modifiers & GDK_SHIFT_MASK ) { + ostream << "Shift + "; + } + if ( accelerator.modifiers & GDK_MOD1_MASK ) { + ostream << "Alt + "; + } + if ( accelerator.modifiers & GDK_CONTROL_MASK ) { + ostream << "Control + "; + } + + const char* keyName = global_keys_find( accelerator.key ); + if ( !string_empty( keyName ) ) { + ostream << keyName; + } + else + { + ostream << static_cast( accelerator.key ); + } #endif - ostream << gtk_accelerator_get_label(accelerator.key, accelerator.modifiers); + ostream << gtk_accelerator_get_label( accelerator.key, accelerator.modifiers ); } typedef std::map AcceleratorMap; typedef std::set AcceleratorSet; -bool accelerator_map_insert(AcceleratorMap& acceleratorMap, Accelerator accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - return acceleratorMap.insert(AcceleratorMap::value_type(accelerator, callback)).second; - } - return true; +bool accelerator_map_insert( AcceleratorMap& acceleratorMap, Accelerator accelerator, const Callback& callback ){ + if ( accelerator.key != 0 ) { + return acceleratorMap.insert( AcceleratorMap::value_type( accelerator, callback ) ).second; + } + return true; } -bool accelerator_map_erase(AcceleratorMap& acceleratorMap, Accelerator accelerator) -{ - if(accelerator.key != 0) - { - AcceleratorMap::iterator i = acceleratorMap.find(accelerator); - if(i == acceleratorMap.end()) - { - return false; - } - acceleratorMap.erase(i); - } - return true; -} - -Accelerator accelerator_for_event_key(guint keyval, guint state) -{ - keyval = gdk_keyval_to_upper(keyval); - if(keyval == GDK_ISO_Left_Tab) - keyval = GDK_Tab; - return Accelerator(keyval, (GdkModifierType)(state & gtk_accelerator_get_default_mod_mask())); +bool accelerator_map_erase( AcceleratorMap& acceleratorMap, Accelerator accelerator ){ + if ( accelerator.key != 0 ) { + AcceleratorMap::iterator i = acceleratorMap.find( accelerator ); + if ( i == acceleratorMap.end() ) { + return false; + } + acceleratorMap.erase( i ); + } + return true; } -bool AcceleratorMap_activate(const AcceleratorMap& acceleratorMap, const Accelerator& accelerator) -{ - AcceleratorMap::const_iterator i = acceleratorMap.find(accelerator); - if(i != acceleratorMap.end()) - { - (*i).second(); - return true; - } +Accelerator accelerator_for_event_key( guint keyval, guint state ){ + keyval = gdk_keyval_to_upper( keyval ); + if ( keyval == GDK_ISO_Left_Tab ) { + keyval = GDK_Tab; + } + return Accelerator( keyval, (GdkModifierType)( state & gtk_accelerator_get_default_mod_mask() ) ); +} + +bool AcceleratorMap_activate( const AcceleratorMap& acceleratorMap, const Accelerator& accelerator ){ + AcceleratorMap::const_iterator i = acceleratorMap.find( accelerator ); + if ( i != acceleratorMap.end() ) { + ( *i ).second(); + return true; + } - return false; + return false; } -static gboolean accelerator_key_event(GtkWindow* window, GdkEventKey* event, AcceleratorMap* acceleratorMap) -{ - return AcceleratorMap_activate(*acceleratorMap, accelerator_for_event_key(event->keyval, event->state)); +static gboolean accelerator_key_event( GtkWindow* window, GdkEventKey* event, AcceleratorMap* acceleratorMap ){ + return AcceleratorMap_activate( *acceleratorMap, accelerator_for_event_key( event->keyval, event->state ) ); } @@ -147,217 +136,191 @@ AcceleratorMap g_special_accelerators; namespace MouseButton { - enum - { - Left = 1 << 0, - Right = 1 << 1, - Middle = 1 << 2, - }; +enum +{ + Left = 1 << 0, + Right = 1 << 1, + Middle = 1 << 2, +}; } typedef unsigned int ButtonMask; -void print_buttons(ButtonMask mask) -{ - globalOutputStream() << "button state: "; - if((mask & MouseButton::Left) != 0) - { - globalOutputStream() << "Left "; - } - if((mask & MouseButton::Right) != 0) - { - globalOutputStream() << "Right "; - } - if((mask & MouseButton::Middle) != 0) - { - globalOutputStream() << "Middle "; - } - globalOutputStream() << "\n"; -} - -ButtonMask ButtonMask_for_event_button(guint button) -{ - switch(button) - { - case 1: - return MouseButton::Left; - case 2: - return MouseButton::Middle; - case 3: - return MouseButton::Right; - } - return 0; -} - -bool window_has_accel(GtkWindow* toplevel) -{ - return g_slist_length(gtk_accel_groups_from_object(G_OBJECT(toplevel))) != 0; +void print_buttons( ButtonMask mask ){ + globalOutputStream() << "button state: "; + if ( ( mask & MouseButton::Left ) != 0 ) { + globalOutputStream() << "Left "; + } + if ( ( mask & MouseButton::Right ) != 0 ) { + globalOutputStream() << "Right "; + } + if ( ( mask & MouseButton::Middle ) != 0 ) { + globalOutputStream() << "Middle "; + } + globalOutputStream() << "\n"; +} + +ButtonMask ButtonMask_for_event_button( guint button ){ + switch ( button ) + { + case 1: + return MouseButton::Left; + case 2: + return MouseButton::Middle; + case 3: + return MouseButton::Right; + } + return 0; +} + +bool window_has_accel( GtkWindow* toplevel ){ + return g_slist_length( gtk_accel_groups_from_object( G_OBJECT( toplevel ) ) ) != 0; } namespace { - bool g_accel_enabled = true; +bool g_accel_enabled = true; } -bool global_accel_enabled() -{ - return g_accel_enabled; +bool global_accel_enabled(){ + return g_accel_enabled; } -GClosure* accel_group_add_accelerator(GtkAccelGroup* group, Accelerator accelerator, const Callback& callback); -void accel_group_remove_accelerator(GtkAccelGroup* group, Accelerator accelerator); +GClosure* accel_group_add_accelerator( GtkAccelGroup* group, Accelerator accelerator, const Callback& callback ); +void accel_group_remove_accelerator( GtkAccelGroup* group, Accelerator accelerator ); AcceleratorMap g_queuedAcceleratorsAdd; AcceleratorSet g_queuedAcceleratorsRemove; -void globalQueuedAccelerators_add(Accelerator accelerator, const Callback& callback) -{ - if(!g_queuedAcceleratorsAdd.insert(AcceleratorMap::value_type(accelerator, callback)).second) - { - globalErrorStream() << "globalQueuedAccelerators_add: accelerator already queued: " << accelerator << "\n"; - } +void globalQueuedAccelerators_add( Accelerator accelerator, const Callback& callback ){ + if ( !g_queuedAcceleratorsAdd.insert( AcceleratorMap::value_type( accelerator, callback ) ).second ) { + globalErrorStream() << "globalQueuedAccelerators_add: accelerator already queued: " << accelerator << "\n"; + } } -void globalQueuedAccelerators_remove(Accelerator accelerator) -{ - if(g_queuedAcceleratorsAdd.erase(accelerator) == 0) - { - if(!g_queuedAcceleratorsRemove.insert(accelerator).second) - { - globalErrorStream() << "globalQueuedAccelerators_remove: accelerator already queued: " << accelerator << "\n"; - } - } +void globalQueuedAccelerators_remove( Accelerator accelerator ){ + if ( g_queuedAcceleratorsAdd.erase( accelerator ) == 0 ) { + if ( !g_queuedAcceleratorsRemove.insert( accelerator ).second ) { + globalErrorStream() << "globalQueuedAccelerators_remove: accelerator already queued: " << accelerator << "\n"; + } + } } -void globalQueuedAccelerators_commit() -{ - for(AcceleratorSet::const_iterator i = g_queuedAcceleratorsRemove.begin(); i != g_queuedAcceleratorsRemove.end(); ++i) - { - //globalOutputStream() << "removing: " << (*i).first << "\n"; - accel_group_remove_accelerator(global_accel, *i); - } - g_queuedAcceleratorsRemove.clear(); - for(AcceleratorMap::const_iterator i = g_queuedAcceleratorsAdd.begin(); i != g_queuedAcceleratorsAdd.end(); ++i) - { - //globalOutputStream() << "adding: " << (*i).first << "\n"; - accel_group_add_accelerator(global_accel, (*i).first, (*i).second); - } - g_queuedAcceleratorsAdd.clear(); -} - -void accel_group_test(GtkWindow* toplevel, GtkAccelGroup* accel) -{ - guint n_entries; - gtk_accel_group_query(accel, '4', (GdkModifierType)0, &n_entries); - globalOutputStream() << "grid4: " << n_entries << "\n"; - globalOutputStream() << "toplevel accelgroups: " << g_slist_length(gtk_accel_groups_from_object(G_OBJECT(toplevel))) << "\n"; +void globalQueuedAccelerators_commit(){ + for ( AcceleratorSet::const_iterator i = g_queuedAcceleratorsRemove.begin(); i != g_queuedAcceleratorsRemove.end(); ++i ) + { + //globalOutputStream() << "removing: " << (*i).first << "\n"; + accel_group_remove_accelerator( global_accel, *i ); + } + g_queuedAcceleratorsRemove.clear(); + for ( AcceleratorMap::const_iterator i = g_queuedAcceleratorsAdd.begin(); i != g_queuedAcceleratorsAdd.end(); ++i ) + { + //globalOutputStream() << "adding: " << (*i).first << "\n"; + accel_group_add_accelerator( global_accel, ( *i ).first, ( *i ).second ); + } + g_queuedAcceleratorsAdd.clear(); +} + +void accel_group_test( GtkWindow* toplevel, GtkAccelGroup* accel ){ + guint n_entries; + gtk_accel_group_query( accel, '4', (GdkModifierType)0, &n_entries ); + globalOutputStream() << "grid4: " << n_entries << "\n"; + globalOutputStream() << "toplevel accelgroups: " << g_slist_length( gtk_accel_groups_from_object( G_OBJECT( toplevel ) ) ) << "\n"; } typedef std::set WindowSet; WindowSet g_accel_windows; -bool Buttons_press(ButtonMask& buttons, guint button, guint state) -{ - if(buttons == 0 && bitfield_enable(buttons, ButtonMask_for_event_button(button)) != 0) - { - ASSERT_MESSAGE(g_accel_enabled, "Buttons_press: accelerators not enabled"); - g_accel_enabled = false; - for(WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i) - { - GtkWindow* toplevel = *i; - ASSERT_MESSAGE(window_has_accel(toplevel), "ERROR"); - ASSERT_MESSAGE(GTK_WIDGET_TOPLEVEL(toplevel), "disabling accel for non-toplevel window"); - gtk_window_remove_accel_group(toplevel, global_accel); +bool Buttons_press( ButtonMask& buttons, guint button, guint state ){ + if ( buttons == 0 && bitfield_enable( buttons, ButtonMask_for_event_button( button ) ) != 0 ) { + ASSERT_MESSAGE( g_accel_enabled, "Buttons_press: accelerators not enabled" ); + g_accel_enabled = false; + for ( WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i ) + { + GtkWindow* toplevel = *i; + ASSERT_MESSAGE( window_has_accel( toplevel ), "ERROR" ); + ASSERT_MESSAGE( GTK_WIDGET_TOPLEVEL( toplevel ), "disabling accel for non-toplevel window" ); + gtk_window_remove_accel_group( toplevel, global_accel ); #if 0 - globalOutputStream() << reinterpret_cast(toplevel) << ": disabled global accelerators\n"; + globalOutputStream() << reinterpret_cast( toplevel ) << ": disabled global accelerators\n"; #endif #if 0 - accel_group_test(toplevel, global_accel); + accel_group_test( toplevel, global_accel ); #endif - } - } - buttons = bitfield_enable(buttons, ButtonMask_for_event_button(button)); + } + } + buttons = bitfield_enable( buttons, ButtonMask_for_event_button( button ) ); #if 0 - globalOutputStream() << "Buttons_press: "; - print_buttons(buttons); + globalOutputStream() << "Buttons_press: "; + print_buttons( buttons ); #endif - return false; -} - -bool Buttons_release(ButtonMask& buttons, guint button, guint state) -{ - if(buttons != 0 && bitfield_disable(buttons, ButtonMask_for_event_button(button)) == 0) - { - ASSERT_MESSAGE(!g_accel_enabled, "Buttons_release: accelerators are enabled"); - g_accel_enabled = true; - for(WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i) - { - GtkWindow* toplevel = *i; - ASSERT_MESSAGE(!window_has_accel(toplevel), "ERROR"); - ASSERT_MESSAGE(GTK_WIDGET_TOPLEVEL(toplevel), "enabling accel for non-toplevel window"); - gtk_window_add_accel_group(toplevel, global_accel); + return false; +} + +bool Buttons_release( ButtonMask& buttons, guint button, guint state ){ + if ( buttons != 0 && bitfield_disable( buttons, ButtonMask_for_event_button( button ) ) == 0 ) { + ASSERT_MESSAGE( !g_accel_enabled, "Buttons_release: accelerators are enabled" ); + g_accel_enabled = true; + for ( WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i ) + { + GtkWindow* toplevel = *i; + ASSERT_MESSAGE( !window_has_accel( toplevel ), "ERROR" ); + ASSERT_MESSAGE( GTK_WIDGET_TOPLEVEL( toplevel ), "enabling accel for non-toplevel window" ); + gtk_window_add_accel_group( toplevel, global_accel ); #if 0 - globalOutputStream() << reinterpret_cast(toplevel) << ": enabled global accelerators\n"; + globalOutputStream() << reinterpret_cast( toplevel ) << ": enabled global accelerators\n"; #endif #if 0 - accel_group_test(toplevel, global_accel); + accel_group_test( toplevel, global_accel ); #endif - } - globalQueuedAccelerators_commit(); - } - buttons = bitfield_disable(buttons, ButtonMask_for_event_button(button)); + } + globalQueuedAccelerators_commit(); + } + buttons = bitfield_disable( buttons, ButtonMask_for_event_button( button ) ); #if 0 - globalOutputStream() << "Buttons_release: "; - print_buttons(buttons); + globalOutputStream() << "Buttons_release: "; + print_buttons( buttons ); #endif - return false; + return false; } -bool Buttons_releaseAll(ButtonMask& buttons) -{ - Buttons_release(buttons, MouseButton::Left | MouseButton::Middle | MouseButton::Right, 0); - return false; +bool Buttons_releaseAll( ButtonMask& buttons ){ + Buttons_release( buttons, MouseButton::Left | MouseButton::Middle | MouseButton::Right, 0 ); + return false; } struct PressedButtons { - ButtonMask buttons; + ButtonMask buttons; - PressedButtons() : buttons(0) - { - } + PressedButtons() : buttons( 0 ){ + } }; -gboolean PressedButtons_button_press(GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed) -{ - if(event->type == GDK_BUTTON_PRESS) - { - return Buttons_press(pressed->buttons, event->button, event->state); - } - return FALSE; +gboolean PressedButtons_button_press( GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed ){ + if ( event->type == GDK_BUTTON_PRESS ) { + return Buttons_press( pressed->buttons, event->button, event->state ); + } + return FALSE; } -gboolean PressedButtons_button_release(GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - return Buttons_release(pressed->buttons, event->button, event->state); - } - return FALSE; +gboolean PressedButtons_button_release( GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed ){ + if ( event->type == GDK_BUTTON_RELEASE ) { + return Buttons_release( pressed->buttons, event->button, event->state ); + } + return FALSE; } -gboolean PressedButtons_focus_out(GtkWidget* widget, GdkEventFocus* event, PressedButtons* pressed) -{ - Buttons_releaseAll(pressed->buttons); - return FALSE; +gboolean PressedButtons_focus_out( GtkWidget* widget, GdkEventFocus* event, PressedButtons* pressed ){ + Buttons_releaseAll( pressed->buttons ); + return FALSE; } -void PressedButtons_connect(PressedButtons& pressedButtons, GtkWidget* widget) -{ - g_signal_connect(G_OBJECT(widget), "button_press_event", G_CALLBACK(PressedButtons_button_press), &pressedButtons); - g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(PressedButtons_button_release), &pressedButtons); - g_signal_connect(G_OBJECT(widget), "focus_out_event", G_CALLBACK(PressedButtons_focus_out), &pressedButtons); +void PressedButtons_connect( PressedButtons& pressedButtons, GtkWidget* widget ){ + g_signal_connect( G_OBJECT( widget ), "button_press_event", G_CALLBACK( PressedButtons_button_press ), &pressedButtons ); + g_signal_connect( G_OBJECT( widget ), "button_release_event", G_CALLBACK( PressedButtons_button_release ), &pressedButtons ); + g_signal_connect( G_OBJECT( widget ), "focus_out_event", G_CALLBACK( PressedButtons_focus_out ), &pressedButtons ); } PressedButtons g_pressedButtons; @@ -367,296 +330,247 @@ PressedButtons g_pressedButtons; struct PressedKeys { - typedef std::set Keys; - Keys keys; - std::size_t refcount; + typedef std::set Keys; + Keys keys; + std::size_t refcount; - PressedKeys() : refcount(0) - { - } + PressedKeys() : refcount( 0 ){ + } }; AcceleratorMap g_keydown_accelerators; AcceleratorMap g_keyup_accelerators; -bool Keys_press(PressedKeys::Keys& keys, guint keyval) -{ - if(keys.insert(keyval).second) - { - return AcceleratorMap_activate(g_keydown_accelerators, accelerator_for_event_key(keyval, 0)); - } - return g_keydown_accelerators.find(accelerator_for_event_key(keyval, 0)) != g_keydown_accelerators.end(); +bool Keys_press( PressedKeys::Keys& keys, guint keyval ){ + if ( keys.insert( keyval ).second ) { + return AcceleratorMap_activate( g_keydown_accelerators, accelerator_for_event_key( keyval, 0 ) ); + } + return g_keydown_accelerators.find( accelerator_for_event_key( keyval, 0 ) ) != g_keydown_accelerators.end(); } -bool Keys_release(PressedKeys::Keys& keys, guint keyval) -{ - if(keys.erase(keyval) != 0) - { - return AcceleratorMap_activate(g_keyup_accelerators, accelerator_for_event_key(keyval, 0)); - } - return g_keyup_accelerators.find(accelerator_for_event_key(keyval, 0)) != g_keyup_accelerators.end(); +bool Keys_release( PressedKeys::Keys& keys, guint keyval ){ + if ( keys.erase( keyval ) != 0 ) { + return AcceleratorMap_activate( g_keyup_accelerators, accelerator_for_event_key( keyval, 0 ) ); + } + return g_keyup_accelerators.find( accelerator_for_event_key( keyval, 0 ) ) != g_keyup_accelerators.end(); } -void Keys_releaseAll(PressedKeys::Keys& keys, guint state) -{ - for(PressedKeys::Keys::iterator i = keys.begin(); i != keys.end(); ++i) - { - AcceleratorMap_activate(g_keyup_accelerators, accelerator_for_event_key(*i, state)); - } - keys.clear(); +void Keys_releaseAll( PressedKeys::Keys& keys, guint state ){ + for ( PressedKeys::Keys::iterator i = keys.begin(); i != keys.end(); ++i ) + { + AcceleratorMap_activate( g_keyup_accelerators, accelerator_for_event_key( *i, state ) ); + } + keys.clear(); } -gboolean PressedKeys_key_press(GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys) -{ - //globalOutputStream() << "pressed: " << event->keyval << "\n"; - return event->state == 0 && Keys_press(pressedKeys->keys, event->keyval); +gboolean PressedKeys_key_press( GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys ){ + //globalOutputStream() << "pressed: " << event->keyval << "\n"; + return event->state == 0 && Keys_press( pressedKeys->keys, event->keyval ); } -gboolean PressedKeys_key_release(GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys) -{ - //globalOutputStream() << "released: " << event->keyval << "\n"; - return Keys_release(pressedKeys->keys, event->keyval); +gboolean PressedKeys_key_release( GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys ){ + //globalOutputStream() << "released: " << event->keyval << "\n"; + return Keys_release( pressedKeys->keys, event->keyval ); } -gboolean PressedKeys_focus_in(GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys) -{ - ++pressedKeys->refcount; - return FALSE; +gboolean PressedKeys_focus_in( GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys ){ + ++pressedKeys->refcount; + return FALSE; } -gboolean PressedKeys_focus_out(GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys) -{ - if(--pressedKeys->refcount == 0) - { - Keys_releaseAll(pressedKeys->keys, 0); - } - return FALSE; +gboolean PressedKeys_focus_out( GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys ){ + if ( --pressedKeys->refcount == 0 ) { + Keys_releaseAll( pressedKeys->keys, 0 ); + } + return FALSE; } PressedKeys g_pressedKeys; -void GlobalPressedKeys_releaseAll() -{ - Keys_releaseAll(g_pressedKeys.keys, 0); +void GlobalPressedKeys_releaseAll(){ + Keys_releaseAll( g_pressedKeys.keys, 0 ); } -void GlobalPressedKeys_connect(GtkWindow* window) -{ - unsigned int key_press_handler = g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(PressedKeys_key_press), &g_pressedKeys); - unsigned int key_release_handler = g_signal_connect(G_OBJECT(window), "key_release_event", G_CALLBACK(PressedKeys_key_release), &g_pressedKeys); - g_object_set_data(G_OBJECT(window), "key_press_handler", gint_to_pointer(key_press_handler)); - g_object_set_data(G_OBJECT(window), "key_release_handler", gint_to_pointer(key_release_handler)); - unsigned int focus_in_handler = g_signal_connect(G_OBJECT(window), "focus_in_event", G_CALLBACK(PressedKeys_focus_in), &g_pressedKeys); - unsigned int focus_out_handler = g_signal_connect(G_OBJECT(window), "focus_out_event", G_CALLBACK(PressedKeys_focus_out), &g_pressedKeys); - g_object_set_data(G_OBJECT(window), "focus_in_handler", gint_to_pointer(focus_in_handler)); - g_object_set_data(G_OBJECT(window), "focus_out_handler", gint_to_pointer(focus_out_handler)); +void GlobalPressedKeys_connect( GtkWindow* window ){ + unsigned int key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( PressedKeys_key_press ), &g_pressedKeys ); + unsigned int key_release_handler = g_signal_connect( G_OBJECT( window ), "key_release_event", G_CALLBACK( PressedKeys_key_release ), &g_pressedKeys ); + g_object_set_data( G_OBJECT( window ), "key_press_handler", gint_to_pointer( key_press_handler ) ); + g_object_set_data( G_OBJECT( window ), "key_release_handler", gint_to_pointer( key_release_handler ) ); + unsigned int focus_in_handler = g_signal_connect( G_OBJECT( window ), "focus_in_event", G_CALLBACK( PressedKeys_focus_in ), &g_pressedKeys ); + unsigned int focus_out_handler = g_signal_connect( G_OBJECT( window ), "focus_out_event", G_CALLBACK( PressedKeys_focus_out ), &g_pressedKeys ); + g_object_set_data( G_OBJECT( window ), "focus_in_handler", gint_to_pointer( focus_in_handler ) ); + g_object_set_data( G_OBJECT( window ), "focus_out_handler", gint_to_pointer( focus_out_handler ) ); } -void GlobalPressedKeys_disconnect(GtkWindow* window) -{ - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "key_press_handler"))); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "key_release_handler"))); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "focus_in_handler"))); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "focus_out_handler"))); +void GlobalPressedKeys_disconnect( GtkWindow* window ){ + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_press_handler" ) ) ); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_release_handler" ) ) ); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "focus_in_handler" ) ) ); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "focus_out_handler" ) ) ); } -void special_accelerators_add(Accelerator accelerator, const Callback& callback) -{ - //globalOutputStream() << "special_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_special_accelerators, accelerator, callback)) - { - globalErrorStream() << "special_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } +void special_accelerators_add( Accelerator accelerator, const Callback& callback ){ + //globalOutputStream() << "special_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_insert( g_special_accelerators, accelerator, callback ) ) { + globalErrorStream() << "special_accelerators_add: already exists: " << makeQuoted( accelerator ) << "\n"; + } } -void special_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "special_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_special_accelerators, accelerator)) - { - globalErrorStream() << "special_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } +void special_accelerators_remove( Accelerator accelerator ){ + //globalOutputStream() << "special_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_erase( g_special_accelerators, accelerator ) ) { + globalErrorStream() << "special_accelerators_remove: not found: " << makeQuoted( accelerator ) << "\n"; + } } -void keydown_accelerators_add(Accelerator accelerator, const Callback& callback) -{ - //globalOutputStream() << "keydown_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_keydown_accelerators, accelerator, callback)) - { - globalErrorStream() << "keydown_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } +void keydown_accelerators_add( Accelerator accelerator, const Callback& callback ){ + //globalOutputStream() << "keydown_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_insert( g_keydown_accelerators, accelerator, callback ) ) { + globalErrorStream() << "keydown_accelerators_add: already exists: " << makeQuoted( accelerator ) << "\n"; + } } -void keydown_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "keydown_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_keydown_accelerators, accelerator)) - { - globalErrorStream() << "keydown_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } +void keydown_accelerators_remove( Accelerator accelerator ){ + //globalOutputStream() << "keydown_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_erase( g_keydown_accelerators, accelerator ) ) { + globalErrorStream() << "keydown_accelerators_remove: not found: " << makeQuoted( accelerator ) << "\n"; + } } -void keyup_accelerators_add(Accelerator accelerator, const Callback& callback) -{ - //globalOutputStream() << "keyup_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_keyup_accelerators, accelerator, callback)) - { - globalErrorStream() << "keyup_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } +void keyup_accelerators_add( Accelerator accelerator, const Callback& callback ){ + //globalOutputStream() << "keyup_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_insert( g_keyup_accelerators, accelerator, callback ) ) { + globalErrorStream() << "keyup_accelerators_add: already exists: " << makeQuoted( accelerator ) << "\n"; + } } -void keyup_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "keyup_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_keyup_accelerators, accelerator)) - { - globalErrorStream() << "keyup_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } +void keyup_accelerators_remove( Accelerator accelerator ){ + //globalOutputStream() << "keyup_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if ( !accelerator_map_erase( g_keyup_accelerators, accelerator ) ) { + globalErrorStream() << "keyup_accelerators_remove: not found: " << makeQuoted( accelerator ) << "\n"; + } } -gboolean accel_closure_callback(GtkAccelGroup* group, GtkWidget* widget, guint key, GdkModifierType modifiers, gpointer data) -{ - (*reinterpret_cast(data))(); - return TRUE; +gboolean accel_closure_callback( GtkAccelGroup* group, GtkWidget* widget, guint key, GdkModifierType modifiers, gpointer data ){ + ( *reinterpret_cast( data ) )( ); + return TRUE; } -GClosure* accel_group_add_accelerator(GtkAccelGroup* group, Accelerator accelerator, const Callback& callback) -{ - if(accelerator.key != 0 && gtk_accelerator_valid(accelerator.key, accelerator.modifiers)) - { - //globalOutputStream() << "global_accel_connect: " << makeQuoted(accelerator) << "\n"; - GClosure* closure = create_cclosure(G_CALLBACK(accel_closure_callback), callback); - gtk_accel_group_connect(group, accelerator.key, accelerator.modifiers, GTK_ACCEL_VISIBLE, closure); - return closure; - } - else - { - special_accelerators_add(accelerator, callback); - return 0; - } -} - -void accel_group_remove_accelerator(GtkAccelGroup* group, Accelerator accelerator) -{ - if(accelerator.key != 0 && gtk_accelerator_valid(accelerator.key, accelerator.modifiers)) - { - //globalOutputStream() << "global_accel_disconnect: " << makeQuoted(accelerator) << "\n"; - gtk_accel_group_disconnect_key(group, accelerator.key, accelerator.modifiers); - } - else - { - special_accelerators_remove(accelerator); - } +GClosure* accel_group_add_accelerator( GtkAccelGroup* group, Accelerator accelerator, const Callback& callback ){ + if ( accelerator.key != 0 && gtk_accelerator_valid( accelerator.key, accelerator.modifiers ) ) { + //globalOutputStream() << "global_accel_connect: " << makeQuoted(accelerator) << "\n"; + GClosure* closure = create_cclosure( G_CALLBACK( accel_closure_callback ), callback ); + gtk_accel_group_connect( group, accelerator.key, accelerator.modifiers, GTK_ACCEL_VISIBLE, closure ); + return closure; + } + else + { + special_accelerators_add( accelerator, callback ); + return 0; + } +} + +void accel_group_remove_accelerator( GtkAccelGroup* group, Accelerator accelerator ){ + if ( accelerator.key != 0 && gtk_accelerator_valid( accelerator.key, accelerator.modifiers ) ) { + //globalOutputStream() << "global_accel_disconnect: " << makeQuoted(accelerator) << "\n"; + gtk_accel_group_disconnect_key( group, accelerator.key, accelerator.modifiers ); + } + else + { + special_accelerators_remove( accelerator ); + } } GtkAccelGroup* global_accel = 0; -void global_accel_init() -{ - global_accel = gtk_accel_group_new(); +void global_accel_init(){ + global_accel = gtk_accel_group_new(); } -void global_accel_destroy() -{ - g_object_unref(global_accel); +void global_accel_destroy(){ + g_object_unref( global_accel ); } -GClosure* global_accel_group_add_accelerator(Accelerator accelerator, const Callback& callback) -{ - if(!global_accel_enabled()) - { - // workaround: cannot add to GtkAccelGroup while it is disabled - //globalOutputStream() << "queued for add: " << accelerator << "\n"; - globalQueuedAccelerators_add(accelerator, callback); - return 0; - } - return accel_group_add_accelerator(global_accel, accelerator, callback); -} -void global_accel_group_remove_accelerator(Accelerator accelerator) -{ - if(!global_accel_enabled()) - { - //globalOutputStream() << "queued for remove: " << accelerator << "\n"; - globalQueuedAccelerators_remove(accelerator); - return; - } - accel_group_remove_accelerator(global_accel, accelerator); +GClosure* global_accel_group_add_accelerator( Accelerator accelerator, const Callback& callback ){ + if ( !global_accel_enabled() ) { + // workaround: cannot add to GtkAccelGroup while it is disabled + //globalOutputStream() << "queued for add: " << accelerator << "\n"; + globalQueuedAccelerators_add( accelerator, callback ); + return 0; + } + return accel_group_add_accelerator( global_accel, accelerator, callback ); +} +void global_accel_group_remove_accelerator( Accelerator accelerator ){ + if ( !global_accel_enabled() ) { + //globalOutputStream() << "queued for remove: " << accelerator << "\n"; + globalQueuedAccelerators_remove( accelerator ); + return; + } + accel_group_remove_accelerator( global_accel, accelerator ); } /// \brief Propagates key events to the focus-widget, overriding global accelerators. -static gboolean override_global_accelerators(GtkWindow* window, GdkEventKey* event, gpointer data) -{ - gboolean b = gtk_window_propagate_key_event(window, event); - return b; +static gboolean override_global_accelerators( GtkWindow* window, GdkEventKey* event, gpointer data ){ + gboolean b = gtk_window_propagate_key_event( window, event ); + return b; } -void global_accel_connect_window(GtkWindow* window) -{ +void global_accel_connect_window( GtkWindow* window ){ #if 1 - unsigned int override_handler = g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(override_global_accelerators), 0); - g_object_set_data(G_OBJECT(window), "override_handler", gint_to_pointer(override_handler)); + unsigned int override_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( override_global_accelerators ), 0 ); + g_object_set_data( G_OBJECT( window ), "override_handler", gint_to_pointer( override_handler ) ); - unsigned int special_key_press_handler = g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(accelerator_key_event), &g_special_accelerators); - g_object_set_data(G_OBJECT(window), "special_key_press_handler", gint_to_pointer(special_key_press_handler)); + unsigned int special_key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( accelerator_key_event ), &g_special_accelerators ); + g_object_set_data( G_OBJECT( window ), "special_key_press_handler", gint_to_pointer( special_key_press_handler ) ); - GlobalPressedKeys_connect(window); + GlobalPressedKeys_connect( window ); #else - unsigned int key_press_handler = g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(accelerator_key_event), &g_keydown_accelerators); - unsigned int key_release_handler = g_signal_connect(G_OBJECT(window), "key_release_event", G_CALLBACK(accelerator_key_event), &g_keyup_accelerators); - g_object_set_data(G_OBJECT(window), "key_press_handler", gint_to_pointer(key_press_handler)); - g_object_set_data(G_OBJECT(window), "key_release_handler", gint_to_pointer(key_release_handler)); + unsigned int key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( accelerator_key_event ), &g_keydown_accelerators ); + unsigned int key_release_handler = g_signal_connect( G_OBJECT( window ), "key_release_event", G_CALLBACK( accelerator_key_event ), &g_keyup_accelerators ); + g_object_set_data( G_OBJECT( window ), "key_press_handler", gint_to_pointer( key_press_handler ) ); + g_object_set_data( G_OBJECT( window ), "key_release_handler", gint_to_pointer( key_release_handler ) ); #endif - g_accel_windows.insert(window); - gtk_window_add_accel_group(window, global_accel); + g_accel_windows.insert( window ); + gtk_window_add_accel_group( window, global_accel ); } -void global_accel_disconnect_window(GtkWindow* window) -{ +void global_accel_disconnect_window( GtkWindow* window ){ #if 1 - GlobalPressedKeys_disconnect(window); + GlobalPressedKeys_disconnect( window ); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "override_handler"))); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "special_key_press_handler"))); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "override_handler" ) ) ); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "special_key_press_handler" ) ) ); #else - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "key_press_handler"))); - g_signal_handler_disconnect(G_OBJECT(window), gpointer_to_int(g_object_get_data(G_OBJECT(window), "key_release_handler"))); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_press_handler" ) ) ); + g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_release_handler" ) ) ); #endif - gtk_window_remove_accel_group(window, global_accel); - std::size_t count = g_accel_windows.erase(window); - ASSERT_MESSAGE(count == 1, "failed to remove accel group\n"); + gtk_window_remove_accel_group( window, global_accel ); + std::size_t count = g_accel_windows.erase( window ); + ASSERT_MESSAGE( count == 1, "failed to remove accel group\n" ); } -GClosure* global_accel_group_find(Accelerator accelerator) -{ - guint numEntries = 0; - GtkAccelGroupEntry* entry = gtk_accel_group_query(global_accel, accelerator.key, accelerator.modifiers, &numEntries); - if(numEntries != 0) - { - if(numEntries != 1) - { - char* name = gtk_accelerator_name(accelerator.key, accelerator.modifiers); - globalErrorStream() << "accelerator already in-use: " << name << "\n"; - g_free(name); - } - return entry->closure; - } - return 0; -} - -void global_accel_group_connect(const Accelerator& accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - global_accel_group_add_accelerator(accelerator, callback); - } +GClosure* global_accel_group_find( Accelerator accelerator ){ + guint numEntries = 0; + GtkAccelGroupEntry* entry = gtk_accel_group_query( global_accel, accelerator.key, accelerator.modifiers, &numEntries ); + if ( numEntries != 0 ) { + if ( numEntries != 1 ) { + char* name = gtk_accelerator_name( accelerator.key, accelerator.modifiers ); + globalErrorStream() << "accelerator already in-use: " << name << "\n"; + g_free( name ); + } + return entry->closure; + } + return 0; } -void global_accel_group_disconnect(const Accelerator& accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - global_accel_group_remove_accelerator(accelerator); - } +void global_accel_group_connect( const Accelerator& accelerator, const Callback& callback ){ + if ( accelerator.key != 0 ) { + global_accel_group_add_accelerator( accelerator, callback ); + } } - +void global_accel_group_disconnect( const Accelerator& accelerator, const Callback& callback ){ + if ( accelerator.key != 0 ) { + global_accel_group_remove_accelerator( accelerator ); + } +} diff --git a/libs/gtkutil/accelerator.h b/libs/gtkutil/accelerator.h index 4e441b21..d1cd344e 100644 --- a/libs/gtkutil/accelerator.h +++ b/libs/gtkutil/accelerator.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_ACCELERATOR_H) +#if !defined( INCLUDED_GTKUTIL_ACCELERATOR_H ) #define INCLUDED_GTKUTIL_ACCELERATOR_H #include @@ -29,75 +29,67 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "generic/callback.h" // ignore numlock -#define ALLOWED_MODIFIERS (~(GDK_MOD2_MASK | GDK_LOCK_MASK | GDK_MOD3_MASK | GDK_MOD4_MASK | GDK_MOD5_MASK)) +#define ALLOWED_MODIFIERS ( ~( GDK_MOD2_MASK | GDK_LOCK_MASK | GDK_MOD3_MASK | GDK_MOD4_MASK | GDK_MOD5_MASK ) ) struct Accelerator { - Accelerator(guint _key) - : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType)0) - { - } - Accelerator(guint _key, GdkModifierType _modifiers) - : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType) (_modifiers & ALLOWED_MODIFIERS)) - { - } - Accelerator(const Accelerator &src) - : key(gdk_keyval_to_upper(src.key)), modifiers((GdkModifierType) (src.modifiers & ALLOWED_MODIFIERS)) - { - } - bool operator<(const Accelerator& other) const - { - guint k1 = key; - guint k2 = other.key; - int mod1 = modifiers & ALLOWED_MODIFIERS; - int mod2 = other.modifiers & ALLOWED_MODIFIERS; - return k1 < k2 || (!(k2 < k1) && mod1 < mod2); - } - bool operator==(const Accelerator& other) const - { - guint k1 = key; - guint k2 = other.key; - int mod1 = modifiers & ALLOWED_MODIFIERS; - int mod2 = other.modifiers & ALLOWED_MODIFIERS; - return k1 == k2 && mod1 == mod2; - } - Accelerator &operator=(const Accelerator& other) - { - key = other.key; - modifiers = (GdkModifierType) (other.modifiers & ALLOWED_MODIFIERS); - return *this; - } - guint key; - GdkModifierType modifiers; + Accelerator( guint _key ) + : key( gdk_keyval_to_upper( _key ) ), modifiers( ( GdkModifierType ) 0 ){ + } + Accelerator( guint _key, GdkModifierType _modifiers ) + : key( gdk_keyval_to_upper( _key ) ), modifiers( ( GdkModifierType )( _modifiers & ALLOWED_MODIFIERS ) ){ + } + Accelerator( const Accelerator &src ) + : key( gdk_keyval_to_upper( src.key ) ), modifiers( ( GdkModifierType )( src.modifiers & ALLOWED_MODIFIERS ) ){ + } + bool operator<( const Accelerator& other ) const { + guint k1 = key; + guint k2 = other.key; + int mod1 = modifiers & ALLOWED_MODIFIERS; + int mod2 = other.modifiers & ALLOWED_MODIFIERS; + return k1 < k2 || ( !( k2 < k1 ) && mod1 < mod2 ); + } + bool operator==( const Accelerator& other ) const { + guint k1 = key; + guint k2 = other.key; + int mod1 = modifiers & ALLOWED_MODIFIERS; + int mod2 = other.modifiers & ALLOWED_MODIFIERS; + return k1 == k2 && mod1 == mod2; + } + Accelerator &operator=( const Accelerator& other ){ + key = other.key; + modifiers = (GdkModifierType) ( other.modifiers & ALLOWED_MODIFIERS ); + return *this; + } + guint key; + GdkModifierType modifiers; }; -inline Accelerator accelerator_null() -{ - return Accelerator(0, (GdkModifierType)0); +inline Accelerator accelerator_null(){ + return Accelerator( 0, (GdkModifierType)0 ); } -const char* global_keys_find(unsigned int key); -unsigned int global_keys_find(const char* name); +const char* global_keys_find( unsigned int key ); +unsigned int global_keys_find( const char* name ); class TextOutputStream; -void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream); +void accelerator_write( const Accelerator& accelerator, TextOutputStream& ostream ); template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Accelerator& accelerator) -{ - accelerator_write(accelerator, ostream); - return ostream; +TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Accelerator& accelerator ){ + accelerator_write( accelerator, ostream ); + return ostream; } -void keydown_accelerators_add(Accelerator accelerator, const Callback& callback); -void keydown_accelerators_remove(Accelerator accelerator); -void keyup_accelerators_add(Accelerator accelerator, const Callback& callback); -void keyup_accelerators_remove(Accelerator accelerator); +void keydown_accelerators_add( Accelerator accelerator, const Callback& callback ); +void keydown_accelerators_remove( Accelerator accelerator ); +void keyup_accelerators_add( Accelerator accelerator, const Callback& callback ); +void keyup_accelerators_remove( Accelerator accelerator ); typedef struct _GtkWidget GtkWidget; typedef struct _GtkWindow GtkWindow; -void global_accel_connect_window(GtkWindow* window); -void global_accel_disconnect_window(GtkWindow* window); +void global_accel_connect_window( GtkWindow* window ); +void global_accel_disconnect_window( GtkWindow* window ); void GlobalPressedKeys_releaseAll(); @@ -106,48 +98,45 @@ extern GtkAccelGroup* global_accel; void global_accel_init(); void global_accel_destroy(); -GClosure* global_accel_group_find(Accelerator accelerator); +GClosure* global_accel_group_find( Accelerator accelerator ); -void global_accel_group_connect(const Accelerator& accelerator, const Callback& callback); -void global_accel_group_disconnect(const Accelerator& accelerator, const Callback& callback); +void global_accel_group_connect( const Accelerator& accelerator, const Callback& callback ); +void global_accel_group_disconnect( const Accelerator& accelerator, const Callback& callback ); class Command { public: - Callback m_callback; - const Accelerator& m_accelerator; - Command(const Callback& callback, const Accelerator& accelerator) : m_callback(callback), m_accelerator(accelerator) - { - } +Callback m_callback; +const Accelerator& m_accelerator; +Command( const Callback& callback, const Accelerator& accelerator ) : m_callback( callback ), m_accelerator( accelerator ){ +} }; class Toggle { public: - Command m_command; - BoolExportCallback m_exportCallback; - Toggle(const Callback& callback, const Accelerator& accelerator, const BoolExportCallback& exportCallback) : m_command(callback, accelerator), m_exportCallback(exportCallback) - { - } +Command m_command; +BoolExportCallback m_exportCallback; +Toggle( const Callback& callback, const Accelerator& accelerator, const BoolExportCallback& exportCallback ) : m_command( callback, accelerator ), m_exportCallback( exportCallback ){ +} }; class KeyEvent { public: - const Accelerator& m_accelerator; - Callback m_keyDown; - Callback m_keyUp; - KeyEvent(const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp) : m_accelerator(accelerator), m_keyDown(keyDown), m_keyUp(keyUp) - { - } +const Accelerator& m_accelerator; +Callback m_keyDown; +Callback m_keyUp; +KeyEvent( const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp ) : m_accelerator( accelerator ), m_keyDown( keyDown ), m_keyUp( keyUp ){ +} }; struct PressedButtons; typedef struct _GtkWidget GtkWidget; -void PressedButtons_connect(PressedButtons& pressedButtons, GtkWidget* widget); +void PressedButtons_connect( PressedButtons& pressedButtons, GtkWidget* widget ); extern PressedButtons g_pressedButtons; diff --git a/libs/gtkutil/button.cpp b/libs/gtkutil/button.cpp index 0356ba39..fc1e58d7 100644 --- a/libs/gtkutil/button.cpp +++ b/libs/gtkutil/button.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "button.h" @@ -30,108 +30,96 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "image.h" #include "pointer.h" -void clicked_closure_callback(GtkWidget* widget, gpointer data) -{ - (*reinterpret_cast(data))(); +void clicked_closure_callback( GtkWidget* widget, gpointer data ){ + ( *reinterpret_cast( data ) )( ); } -void button_connect_callback(GtkButton* button, const Callback& callback) -{ +void button_connect_callback( GtkButton* button, const Callback& callback ){ #if 1 - g_signal_connect_swapped(G_OBJECT(button), "clicked", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); + g_signal_connect_swapped( G_OBJECT( button ), "clicked", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); #else - g_signal_connect_closure(G_OBJECT(button), "clicked", create_cclosure(G_CALLBACK(clicked_closure_callback), callback), FALSE); + g_signal_connect_closure( G_OBJECT( button ), "clicked", create_cclosure( G_CALLBACK( clicked_closure_callback ), callback ), FALSE ); #endif } - -guint toggle_button_connect_callback(GtkToggleButton* button, const Callback& callback) -{ + +guint toggle_button_connect_callback( GtkToggleButton* button, const Callback& callback ){ #if 1 - guint handler = g_signal_connect_swapped(G_OBJECT(button), "toggled", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); + guint handler = g_signal_connect_swapped( G_OBJECT( button ), "toggled", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); #else - guint handler = g_signal_connect_closure(G_OBJECT(button), "toggled", create_cclosure(G_CALLBACK(clicked_closure_callback), callback), TRUE); + guint handler = g_signal_connect_closure( G_OBJECT( button ), "toggled", create_cclosure( G_CALLBACK( clicked_closure_callback ), callback ), TRUE ); #endif - g_object_set_data(G_OBJECT(button), "handler", gint_to_pointer(handler)); - return handler; + g_object_set_data( G_OBJECT( button ), "handler", gint_to_pointer( handler ) ); + return handler; } - -void button_set_icon(GtkButton* button, const char* icon) -{ - GtkImage* image = new_local_image(icon); - gtk_widget_show(GTK_WIDGET(image)); - gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image)); + +void button_set_icon( GtkButton* button, const char* icon ){ + GtkImage* image = new_local_image( icon ); + gtk_widget_show( GTK_WIDGET( image ) ); + gtk_container_add( GTK_CONTAINER( button ), GTK_WIDGET( image ) ); } -void toggle_button_set_active_no_signal(GtkToggleButton* button, gboolean active) -{ - //globalOutputStream() << "set active: " << active << "\n"; - guint handler_id = gpointer_to_int(g_object_get_data(G_OBJECT(button), "handler")); - //guint signal_id = g_signal_lookup("toggled", G_OBJECT_TYPE (button)); - //globalOutputStream() << "signal_id: " << signal_id << "\n"; - //guint found = g_signal_handler_find(G_OBJECT(button), G_SIGNAL_MATCH_ID, signal_id, 0, 0, 0, 0); - //globalOutputStream() << " handler found: " << found << "\n"; - g_signal_handler_block(G_OBJECT(button), handler_id); - gtk_toggle_button_set_active(button, active); - g_signal_handler_unblock(G_OBJECT(button), handler_id); +void toggle_button_set_active_no_signal( GtkToggleButton* button, gboolean active ){ + //globalOutputStream() << "set active: " << active << "\n"; + guint handler_id = gpointer_to_int( g_object_get_data( G_OBJECT( button ), "handler" ) ); + //guint signal_id = g_signal_lookup("toggled", G_OBJECT_TYPE (button)); + //globalOutputStream() << "signal_id: " << signal_id << "\n"; + //guint found = g_signal_handler_find(G_OBJECT(button), G_SIGNAL_MATCH_ID, signal_id, 0, 0, 0, 0); + //globalOutputStream() << " handler found: " << found << "\n"; + g_signal_handler_block( G_OBJECT( button ), handler_id ); + gtk_toggle_button_set_active( button, active ); + g_signal_handler_unblock( G_OBJECT( button ), handler_id ); } -void radio_button_print_state(GtkRadioButton* button) -{ - globalOutputStream() << "toggle button: "; - for(GSList* radio = gtk_radio_button_group(button); radio != 0; radio = g_slist_next(radio)) - { - globalOutputStream() << gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (radio->data)); - } - globalOutputStream() << "\n"; +void radio_button_print_state( GtkRadioButton* button ){ + globalOutputStream() << "toggle button: "; + for ( GSList* radio = gtk_radio_button_group( button ); radio != 0; radio = g_slist_next( radio ) ) + { + globalOutputStream() << gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio->data ) ); + } + globalOutputStream() << "\n"; } -GtkToggleButton* radio_button_get_nth(GtkRadioButton* radio, int index) -{ - GSList *group = gtk_radio_button_group(radio); - return GTK_TOGGLE_BUTTON(g_slist_nth_data(group, g_slist_length(group) - index - 1)); +GtkToggleButton* radio_button_get_nth( GtkRadioButton* radio, int index ){ + GSList *group = gtk_radio_button_group( radio ); + return GTK_TOGGLE_BUTTON( g_slist_nth_data( group, g_slist_length( group ) - index - 1 ) ); } -void radio_button_set_active(GtkRadioButton* radio, int index) -{ - //radio_button_print_state(radio); - gtk_toggle_button_set_active(radio_button_get_nth(radio, index), TRUE); - //radio_button_print_state(radio); +void radio_button_set_active( GtkRadioButton* radio, int index ){ + //radio_button_print_state(radio); + gtk_toggle_button_set_active( radio_button_get_nth( radio, index ), TRUE ); + //radio_button_print_state(radio); } -void radio_button_set_active_no_signal(GtkRadioButton* radio, int index) -{ - { - for(GSList* l = gtk_radio_button_get_group(radio); l != 0; l = g_slist_next(l)) - { - g_signal_handler_block(G_OBJECT(l->data), gpointer_to_int(g_object_get_data(G_OBJECT(l->data), "handler"))); - } - } - radio_button_set_active(radio, index); - { - for(GSList* l = gtk_radio_button_get_group(radio); l != 0; l = g_slist_next(l)) - { - g_signal_handler_unblock(G_OBJECT(l->data), gpointer_to_int(g_object_get_data(G_OBJECT(l->data), "handler"))); - } - } +void radio_button_set_active_no_signal( GtkRadioButton* radio, int index ){ + { + for ( GSList* l = gtk_radio_button_get_group( radio ); l != 0; l = g_slist_next( l ) ) + { + g_signal_handler_block( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); + } + } + radio_button_set_active( radio, index ); + { + for ( GSList* l = gtk_radio_button_get_group( radio ); l != 0; l = g_slist_next( l ) ) + { + g_signal_handler_unblock( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); + } + } } -int radio_button_get_active(GtkRadioButton* radio) -{ - //radio_button_print_state(radio); - GSList *group = gtk_radio_button_group(radio); - int index = g_slist_length(group) - 1; - for (; group != 0; group = g_slist_next(group)) - { - if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(group->data))) - { - break; - } - else - { - index--; - } - } - return index; +int radio_button_get_active( GtkRadioButton* radio ){ + //radio_button_print_state(radio); + GSList *group = gtk_radio_button_group( radio ); + int index = g_slist_length( group ) - 1; + for (; group != 0; group = g_slist_next( group ) ) + { + if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( group->data ) ) ) { + break; + } + else + { + index--; + } + } + return index; } - diff --git a/libs/gtkutil/button.h b/libs/gtkutil/button.h index 69ddac4b..15a9f2e8 100644 --- a/libs/gtkutil/button.h +++ b/libs/gtkutil/button.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_BUTTON_H) +#if !defined( INCLUDED_GTKUTIL_BUTTON_H ) #define INCLUDED_GTKUTIL_BUTTON_H #include "generic/callbackfwd.h" @@ -31,14 +31,14 @@ typedef int gint; typedef gint gboolean; typedef unsigned int guint; -void button_connect_callback(GtkButton* button, const Callback& callback); -guint toggle_button_connect_callback(GtkToggleButton* button, const Callback& callback); +void button_connect_callback( GtkButton* button, const Callback& callback ); +guint toggle_button_connect_callback( GtkToggleButton* button, const Callback& callback ); -void button_set_icon(GtkButton* button, const char* icon); -void toggle_button_set_active_no_signal(GtkToggleButton* item, gboolean active); +void button_set_icon( GtkButton* button, const char* icon ); +void toggle_button_set_active_no_signal( GtkToggleButton* item, gboolean active ); -void radio_button_set_active(GtkRadioButton* radio, int index); -void radio_button_set_active_no_signal(GtkRadioButton* radio, int index); -int radio_button_get_active(GtkRadioButton* radio); +void radio_button_set_active( GtkRadioButton* radio, int index ); +void radio_button_set_active_no_signal( GtkRadioButton* radio, int index ); +int radio_button_get_active( GtkRadioButton* radio ); #endif diff --git a/libs/gtkutil/clipboard.cpp b/libs/gtkutil/clipboard.cpp index f7b9466a..c8073aba 100644 --- a/libs/gtkutil/clipboard.cpp +++ b/libs/gtkutil/clipboard.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "clipboard.h" @@ -28,66 +28,57 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// \file /// \brief Platform-independent GTK clipboard support. /// \todo Using GDK_SELECTION_CLIPBOARD fails on win32, so we use the win32 API directly for now. -#if defined(WIN32) +#if defined( WIN32 ) const char* c_clipboard_format = "RadiantClippings"; #include -void clipboard_copy(ClipboardCopyFunc copy) -{ - BufferOutputStream ostream; - copy(ostream); - - bool bClipped = false; - UINT nClipboard = ::RegisterClipboardFormat(c_clipboard_format); - if (nClipboard > 0) - { - if (::OpenClipboard(0)) - { - EmptyClipboard(); - std::size_t length = ostream.size(); - HANDLE h = ::GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, length + sizeof(std::size_t)); - if (h != 0) - { - char *buffer = reinterpret_cast(::GlobalLock(h)); - *reinterpret_cast(buffer) = length; - buffer += sizeof(std::size_t); - memcpy(buffer, ostream.data(), length); - ::GlobalUnlock(h); - ::SetClipboardData(nClipboard, h); - ::CloseClipboard(); - bClipped = true; - } - } - } - - if (!bClipped) - { - globalOutputStream() << "Unable to register Windows clipboard formats, copy/paste between editors will not be possible\n"; - } +void clipboard_copy( ClipboardCopyFunc copy ){ + BufferOutputStream ostream; + copy( ostream ); + + bool bClipped = false; + UINT nClipboard = ::RegisterClipboardFormat( c_clipboard_format ); + if ( nClipboard > 0 ) { + if ( ::OpenClipboard( 0 ) ) { + EmptyClipboard(); + std::size_t length = ostream.size(); + HANDLE h = ::GlobalAlloc( GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, length + sizeof( std::size_t ) ); + if ( h != 0 ) { + char *buffer = reinterpret_cast( ::GlobalLock( h ) ); + *reinterpret_cast( buffer ) = length; + buffer += sizeof( std::size_t ); + memcpy( buffer, ostream.data(), length ); + ::GlobalUnlock( h ); + ::SetClipboardData( nClipboard, h ); + ::CloseClipboard(); + bClipped = true; + } + } + } + + if ( !bClipped ) { + globalOutputStream() << "Unable to register Windows clipboard formats, copy/paste between editors will not be possible\n"; + } } -void clipboard_paste(ClipboardPasteFunc paste) -{ - UINT nClipboard = ::RegisterClipboardFormat(c_clipboard_format); - if (nClipboard > 0 && ::OpenClipboard(0)) - { - if(IsClipboardFormatAvailable(nClipboard)) - { - HANDLE h = ::GetClipboardData(nClipboard); - if(h) - { - const char *buffer = reinterpret_cast(::GlobalLock(h)); - std::size_t length = *reinterpret_cast(buffer); - buffer += sizeof(std::size_t); - BufferInputStream istream(buffer, length); - paste(istream); - ::GlobalUnlock(h); - } - } - ::CloseClipboard(); - } +void clipboard_paste( ClipboardPasteFunc paste ){ + UINT nClipboard = ::RegisterClipboardFormat( c_clipboard_format ); + if ( nClipboard > 0 && ::OpenClipboard( 0 ) ) { + if ( IsClipboardFormatAvailable( nClipboard ) ) { + HANDLE h = ::GetClipboardData( nClipboard ); + if ( h ) { + const char *buffer = reinterpret_cast( ::GlobalLock( h ) ); + std::size_t length = *reinterpret_cast( buffer ); + buffer += sizeof( std::size_t ); + BufferInputStream istream( buffer, length ); + paste( istream ); + ::GlobalUnlock( h ); + } + } + ::CloseClipboard(); + } } #else @@ -96,66 +87,58 @@ void clipboard_paste(ClipboardPasteFunc paste) enum { - RADIANT_CLIPPINGS = 23, + RADIANT_CLIPPINGS = 23, }; static const GtkTargetEntry clipboard_targets[] = { - { "RADIANT_CLIPPINGS", 0, RADIANT_CLIPPINGS, }, + { "RADIANT_CLIPPINGS", 0, RADIANT_CLIPPINGS, }, }; -static void clipboard_get (GtkClipboard *clipboard, GtkSelectionData *selection_data, guint info, gpointer data) -{ - std::size_t len = *reinterpret_cast(data); - const char* buffer = (len != 0) ? reinterpret_cast(data) + sizeof(std::size_t) : 0; +static void clipboard_get( GtkClipboard *clipboard, GtkSelectionData *selection_data, guint info, gpointer data ){ + std::size_t len = *reinterpret_cast( data ); + const char* buffer = ( len != 0 ) ? reinterpret_cast( data ) + sizeof( std::size_t ) : 0; - GdkAtom type = GDK_NONE; - if(info == clipboard_targets[0].info) - { - type = gdk_atom_intern(clipboard_targets[0].target, FALSE); - } + GdkAtom type = GDK_NONE; + if ( info == clipboard_targets[0].info ) { + type = gdk_atom_intern( clipboard_targets[0].target, FALSE ); + } - gtk_selection_data_set (selection_data, type, 8, reinterpret_cast(buffer), static_cast(len)); + gtk_selection_data_set( selection_data, type, 8, reinterpret_cast( buffer ), static_cast( len ) ); } -static void clipboard_clear (GtkClipboard *clipboard, gpointer data) -{ - delete [] reinterpret_cast(data); +static void clipboard_clear( GtkClipboard *clipboard, gpointer data ){ + delete [] reinterpret_cast( data ); } -static void clipboard_received (GtkClipboard *clipboard, GtkSelectionData *data, gpointer user_data) -{ - if (data->length < 0) - { - globalErrorStream() << "Error retrieving selection\n"; - } - else if(strcmp(gdk_atom_name(data->type), clipboard_targets[0].target) == 0) - { - BufferInputStream istream(reinterpret_cast(data->data), data->length); - (*reinterpret_cast(user_data))(istream); - } +static void clipboard_received( GtkClipboard *clipboard, GtkSelectionData *data, gpointer user_data ){ + if ( data->length < 0 ) { + globalErrorStream() << "Error retrieving selection\n"; + } + else if ( strcmp( gdk_atom_name( data->type ), clipboard_targets[0].target ) == 0 ) { + BufferInputStream istream( reinterpret_cast( data->data ), data->length ); + ( *reinterpret_cast( user_data ) )( istream ); + } } -void clipboard_copy(ClipboardCopyFunc copy) -{ - GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); +void clipboard_copy( ClipboardCopyFunc copy ){ + GtkClipboard* clipboard = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD ); - BufferOutputStream ostream; - copy(ostream); - std::size_t length = ostream.size(); - char* data = new char[length + sizeof(std::size_t)]; - *reinterpret_cast(data) = length; - memcpy(data + sizeof(std::size_t), ostream.data(), length); + BufferOutputStream ostream; + copy( ostream ); + std::size_t length = ostream.size(); + char* data = new char[length + sizeof( std::size_t )]; + *reinterpret_cast( data ) = length; + memcpy( data + sizeof( std::size_t ), ostream.data(), length ); - gtk_clipboard_set_with_data (clipboard, clipboard_targets, 1, clipboard_get, clipboard_clear, data); + gtk_clipboard_set_with_data( clipboard, clipboard_targets, 1, clipboard_get, clipboard_clear, data ); } ClipboardPasteFunc g_clipboardPasteFunc = 0; -void clipboard_paste(ClipboardPasteFunc paste) -{ - GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); - - g_clipboardPasteFunc = paste; - gtk_clipboard_request_contents (clipboard, gdk_atom_intern(clipboard_targets[0].target, FALSE), clipboard_received, &g_clipboardPasteFunc); +void clipboard_paste( ClipboardPasteFunc paste ){ + GtkClipboard* clipboard = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD ); + + g_clipboardPasteFunc = paste; + gtk_clipboard_request_contents( clipboard, gdk_atom_intern( clipboard_targets[0].target, FALSE ), clipboard_received, &g_clipboardPasteFunc ); } diff --git a/libs/gtkutil/clipboard.h b/libs/gtkutil/clipboard.h index 1589a66a..69b64d70 100644 --- a/libs/gtkutil/clipboard.h +++ b/libs/gtkutil/clipboard.h @@ -1,33 +1,33 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_CLIPBOARD_H) +#if !defined( INCLUDED_GTKUTIL_CLIPBOARD_H ) #define INCLUDED_GTKUTIL_CLIPBOARD_H class TextOutputStream; -typedef void(*ClipboardCopyFunc)(TextOutputStream&); -void clipboard_copy(ClipboardCopyFunc copy); +typedef void ( *ClipboardCopyFunc )( TextOutputStream& ); +void clipboard_copy( ClipboardCopyFunc copy ); class TextInputStream; -typedef void(*ClipboardPasteFunc)(TextInputStream&); -void clipboard_paste(ClipboardPasteFunc paste); +typedef void ( *ClipboardPasteFunc )( TextInputStream& ); +void clipboard_paste( ClipboardPasteFunc paste ); #endif diff --git a/libs/gtkutil/closure.cpp b/libs/gtkutil/closure.cpp index 4926d994..09e2fab7 100644 --- a/libs/gtkutil/closure.cpp +++ b/libs/gtkutil/closure.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "closure.h" - diff --git a/libs/gtkutil/closure.h b/libs/gtkutil/closure.h index 9a74b95e..9696464a 100644 --- a/libs/gtkutil/closure.h +++ b/libs/gtkutil/closure.h @@ -1,77 +1,70 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_CLOSURE_H) +#if !defined( INCLUDED_GTKUTIL_CLOSURE_H ) #define INCLUDED_GTKUTIL_CLOSURE_H #include #include "generic/callback.h" -inline void closure_destroy(gpointer data, GClosure* closure) -{ - delete reinterpret_cast(data); +inline void closure_destroy( gpointer data, GClosure* closure ){ + delete reinterpret_cast( data ); } -inline GClosure* create_cclosure(GCallback func, const Callback& callback) -{ - return g_cclosure_new(func, new Callback(callback), closure_destroy); +inline GClosure* create_cclosure( GCallback func, const Callback& callback ){ + return g_cclosure_new( func, new Callback( callback ), closure_destroy ); } -inline GValue GValue_default() -{ - GValue value; - value.g_type = 0; - return value; +inline GValue GValue_default(){ + GValue value; + value.g_type = 0; + return value; } -inline gint object_get_int_property(GObject* object, const char* property) -{ - GValue gvalue = GValue_default(); - g_value_init(&gvalue, G_TYPE_INT); - g_object_get_property(object, property, &gvalue); - return g_value_get_int(&gvalue); +inline gint object_get_int_property( GObject* object, const char* property ){ + GValue gvalue = GValue_default(); + g_value_init( &gvalue, G_TYPE_INT ); + g_object_get_property( object, property, &gvalue ); + return g_value_get_int( &gvalue ); } -inline void object_set_int_property(GObject* object, const char* property, gint value) -{ - GValue gvalue = GValue_default(); - g_value_init(&gvalue, G_TYPE_INT); - g_value_set_int(&gvalue, value); - g_object_set_property(object, property, &gvalue); +inline void object_set_int_property( GObject* object, const char* property, gint value ){ + GValue gvalue = GValue_default(); + g_value_init( &gvalue, G_TYPE_INT ); + g_value_set_int( &gvalue, value ); + g_object_set_property( object, property, &gvalue ); } -inline gboolean object_get_boolean_property(GObject* object, const char* property) -{ - GValue gvalue = GValue_default(); - g_value_init(&gvalue, G_TYPE_BOOLEAN); - g_object_get_property(object, property, &gvalue); - return g_value_get_boolean(&gvalue); +inline gboolean object_get_boolean_property( GObject* object, const char* property ){ + GValue gvalue = GValue_default(); + g_value_init( &gvalue, G_TYPE_BOOLEAN ); + g_object_get_property( object, property, &gvalue ); + return g_value_get_boolean( &gvalue ); } -inline void object_set_boolean_property(GObject* object, const char* property, gboolean value) -{ - GValue gvalue = GValue_default(); - g_value_init(&gvalue, G_TYPE_BOOLEAN); - g_value_set_boolean(&gvalue, value); - g_object_set_property(object, property, &gvalue); +inline void object_set_boolean_property( GObject* object, const char* property, gboolean value ){ + GValue gvalue = GValue_default(); + g_value_init( &gvalue, G_TYPE_BOOLEAN ); + g_value_set_boolean( &gvalue, value ); + g_object_set_property( object, property, &gvalue ); } #endif diff --git a/libs/gtkutil/container.cpp b/libs/gtkutil/container.cpp index 627e0c88..8790307e 100644 --- a/libs/gtkutil/container.cpp +++ b/libs/gtkutil/container.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "container.h" - diff --git a/libs/gtkutil/container.h b/libs/gtkutil/container.h index c41478ba..b6b6afa4 100644 --- a/libs/gtkutil/container.h +++ b/libs/gtkutil/container.h @@ -1,43 +1,40 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_CONTAINER_H) +#if !defined( INCLUDED_GTKUTIL_CONTAINER_H ) #define INCLUDED_GTKUTIL_CONTAINER_H #include -inline GtkWidget* container_add_widget(GtkContainer* container, GtkWidget* widget) -{ - gtk_container_add(container, widget); - return widget; +inline GtkWidget* container_add_widget( GtkContainer* container, GtkWidget* widget ){ + gtk_container_add( container, widget ); + return widget; } -inline void container_remove(GtkWidget* item, gpointer data) -{ - gtk_container_remove(GTK_CONTAINER(data), item); +inline void container_remove( GtkWidget* item, gpointer data ){ + gtk_container_remove( GTK_CONTAINER( data ), item ); } -inline void container_remove_all(GtkContainer* container) -{ - gtk_container_foreach(container, container_remove, container); +inline void container_remove_all( GtkContainer* container ){ + gtk_container_foreach( container, container_remove, container ); } #endif diff --git a/libs/gtkutil/cursor.cpp b/libs/gtkutil/cursor.cpp index 2c4225a2..6005bf1f 100644 --- a/libs/gtkutil/cursor.cpp +++ b/libs/gtkutil/cursor.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "cursor.h" @@ -28,70 +28,63 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include -GdkCursor* create_blank_cursor() -{ - GdkPixmap *pixmap; - GdkBitmap *mask; - char buffer [(32 * 32)/8]; - memset (buffer, 0, (32 * 32)/8); - GdkColor white = {0, 0xffff, 0xffff, 0xffff}; - GdkColor black = {0, 0x0000, 0x0000, 0x0000}; - pixmap = gdk_bitmap_create_from_data(0, buffer, 32, 32); - mask = gdk_bitmap_create_from_data(0, buffer, 32, 32); - GdkCursor *cursor = gdk_cursor_new_from_pixmap(pixmap, mask, &white, &black, 1, 1); - gdk_drawable_unref(pixmap); - gdk_drawable_unref(mask); - - return cursor; +GdkCursor* create_blank_cursor(){ + GdkPixmap *pixmap; + GdkBitmap *mask; + char buffer [( 32 * 32 ) / 8]; + memset( buffer, 0, ( 32 * 32 ) / 8 ); + GdkColor white = {0, 0xffff, 0xffff, 0xffff}; + GdkColor black = {0, 0x0000, 0x0000, 0x0000}; + pixmap = gdk_bitmap_create_from_data( 0, buffer, 32, 32 ); + mask = gdk_bitmap_create_from_data( 0, buffer, 32, 32 ); + GdkCursor *cursor = gdk_cursor_new_from_pixmap( pixmap, mask, &white, &black, 1, 1 ); + gdk_drawable_unref( pixmap ); + gdk_drawable_unref( mask ); + + return cursor; } -void blank_cursor(GtkWidget* widget) -{ - GdkCursor* cursor = create_blank_cursor(); - gdk_window_set_cursor (widget->window, cursor); - gdk_cursor_unref(cursor); +void blank_cursor( GtkWidget* widget ){ + GdkCursor* cursor = create_blank_cursor(); + gdk_window_set_cursor( widget->window, cursor ); + gdk_cursor_unref( cursor ); } -void default_cursor(GtkWidget* widget) -{ - gdk_window_set_cursor(widget->window, 0); +void default_cursor( GtkWidget* widget ){ + gdk_window_set_cursor( widget->window, 0 ); } -#if defined(WIN32) +#if defined( WIN32 ) #include -void Sys_GetCursorPos(GtkWindow* window, int *x, int *y) -{ - POINT pos; - GetCursorPos(&pos); - ScreenToClient((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); - *x = pos.x; - *y = pos.y; +void Sys_GetCursorPos( GtkWindow* window, int *x, int *y ){ + POINT pos; + GetCursorPos( &pos ); + ScreenToClient( (HWND)GDK_WINDOW_HWND( GTK_WIDGET( window )->window ), &pos ); + *x = pos.x; + *y = pos.y; } -void Sys_SetCursorPos(GtkWindow* window, int x, int y) -{ - POINT pos; - pos.x = x; - pos.y = y; - ClientToScreen((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); - SetCursorPos(pos.x, pos.y); +void Sys_SetCursorPos( GtkWindow* window, int x, int y ){ + POINT pos; + pos.x = x; + pos.y = y; + ClientToScreen( (HWND)GDK_WINDOW_HWND( GTK_WIDGET( window )->window ), &pos ); + SetCursorPos( pos.x, pos.y ); } #else #include -void Sys_GetCursorPos(GtkWindow* window, int *x, int *y) -{ - gdk_display_get_pointer(gdk_display_get_default(), 0, x, y, 0); +void Sys_GetCursorPos( GtkWindow* window, int *x, int *y ){ + gdk_display_get_pointer( gdk_display_get_default(), 0, x, y, 0 ); } -void Sys_SetCursorPos(GtkWindow* window, int x, int y) -{ - XWarpPointer(GDK_DISPLAY(), None, GDK_ROOT_WINDOW(), 0, 0, 0, 0, x, y); +void Sys_SetCursorPos( GtkWindow* window, int x, int y ){ + XWarpPointer( GDK_DISPLAY(), None, GDK_ROOT_WINDOW(), 0, 0, 0, 0, x, y ); } #endif diff --git a/libs/gtkutil/cursor.h b/libs/gtkutil/cursor.h index eadae085..e1584fd0 100644 --- a/libs/gtkutil/cursor.h +++ b/libs/gtkutil/cursor.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_CURSOR_H) +#if !defined( INCLUDED_GTKUTIL_CURSOR_H ) #define INCLUDED_GTKUTIL_CURSOR_H #include @@ -34,160 +34,144 @@ typedef struct _GtkWidget GtkWidget; typedef struct _GtkWindow GtkWindow; GdkCursor* create_blank_cursor(); -void blank_cursor(GtkWidget* widget); -void default_cursor(GtkWidget* widget); -void Sys_GetCursorPos(GtkWindow* window, int *x, int *y); -void Sys_SetCursorPos(GtkWindow* window, int x, int y); +void blank_cursor( GtkWidget* widget ); +void default_cursor( GtkWidget* widget ); +void Sys_GetCursorPos( GtkWindow* window, int *x, int *y ); +void Sys_SetCursorPos( GtkWindow* window, int x, int y ); class DeferredMotion { - guint m_handler; - typedef void(*MotionFunction)(gdouble x, gdouble y, guint state, void* data); - MotionFunction m_function; - void* m_data; - gdouble m_x; - gdouble m_y; - guint m_state; - - static gboolean deferred(DeferredMotion* self) - { - self->m_handler = 0; - self->m_function(self->m_x, self->m_y, self->m_state, self->m_data); - return FALSE; - } +guint m_handler; +typedef void ( *MotionFunction )( gdouble x, gdouble y, guint state, void* data ); +MotionFunction m_function; +void* m_data; +gdouble m_x; +gdouble m_y; +guint m_state; + +static gboolean deferred( DeferredMotion* self ){ + self->m_handler = 0; + self->m_function( self->m_x, self->m_y, self->m_state, self->m_data ); + return FALSE; +} public: - DeferredMotion(MotionFunction function, void* data) : m_handler(0), m_function(function), m_data(data) - { - } - void motion(gdouble x, gdouble y, guint state) - { - m_x = x; - m_y = y; - m_state = state; - if(m_handler == 0) - { - m_handler = g_idle_add((GSourceFunc)deferred, this); - } - } - static gboolean gtk_motion(GtkWidget *widget, GdkEventMotion *event, DeferredMotion* self) - { - self->motion(event->x, event->y, event->state); - return FALSE; - } +DeferredMotion( MotionFunction function, void* data ) : m_handler( 0 ), m_function( function ), m_data( data ){ +} +void motion( gdouble x, gdouble y, guint state ){ + m_x = x; + m_y = y; + m_state = state; + if ( m_handler == 0 ) { + m_handler = g_idle_add( (GSourceFunc)deferred, this ); + } +} +static gboolean gtk_motion( GtkWidget *widget, GdkEventMotion *event, DeferredMotion* self ){ + self->motion( event->x, event->y, event->state ); + return FALSE; +} }; class DeferredMotionDelta { - int m_delta_x; - int m_delta_y; - guint m_motion_handler; - typedef void (*MotionDeltaFunction)(int x, int y, void* data); - MotionDeltaFunction m_function; - void* m_data; - - static gboolean deferred_motion(gpointer data) - { - reinterpret_cast(data)->m_function( - reinterpret_cast(data)->m_delta_x, - reinterpret_cast(data)->m_delta_y, - reinterpret_cast(data)->m_data - ); - reinterpret_cast(data)->m_motion_handler = 0; - reinterpret_cast(data)->m_delta_x = 0; - reinterpret_cast(data)->m_delta_y = 0; - return FALSE; - } +int m_delta_x; +int m_delta_y; +guint m_motion_handler; +typedef void ( *MotionDeltaFunction )( int x, int y, void* data ); +MotionDeltaFunction m_function; +void* m_data; + +static gboolean deferred_motion( gpointer data ){ + reinterpret_cast( data )->m_function( + reinterpret_cast( data )->m_delta_x, + reinterpret_cast( data )->m_delta_y, + reinterpret_cast( data )->m_data + ); + reinterpret_cast( data )->m_motion_handler = 0; + reinterpret_cast( data )->m_delta_x = 0; + reinterpret_cast( data )->m_delta_y = 0; + return FALSE; +} public: - DeferredMotionDelta(MotionDeltaFunction function, void* data) : m_delta_x(0), m_delta_y(0), m_motion_handler(0), m_function(function), m_data(data) - { - } - void flush() - { - if(m_motion_handler != 0) - { - g_source_remove(m_motion_handler); - deferred_motion(this); - } - } - void motion_delta(int x, int y, unsigned int state) - { - m_delta_x += x; - m_delta_y += y; - if(m_motion_handler == 0) - { - m_motion_handler = g_idle_add(deferred_motion, this); - } - } +DeferredMotionDelta( MotionDeltaFunction function, void* data ) : m_delta_x( 0 ), m_delta_y( 0 ), m_motion_handler( 0 ), m_function( function ), m_data( data ){ +} +void flush(){ + if ( m_motion_handler != 0 ) { + g_source_remove( m_motion_handler ); + deferred_motion( this ); + } +} +void motion_delta( int x, int y, unsigned int state ){ + m_delta_x += x; + m_delta_y += y; + if ( m_motion_handler == 0 ) { + m_motion_handler = g_idle_add( deferred_motion, this ); + } +} }; class FreezePointer { - unsigned int handle_motion; - int recorded_x, recorded_y; - typedef void (*MotionDeltaFunction)(int x, int y, unsigned int state, void* data); - MotionDeltaFunction m_function; - void* m_data; +unsigned int handle_motion; +int recorded_x, recorded_y; +typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); +MotionDeltaFunction m_function; +void* m_data; public: - FreezePointer() : handle_motion(0), m_function(0), m_data(0) - { - } - static gboolean motion_delta(GtkWidget *widget, GdkEventMotion *event, FreezePointer* self) - { - int current_x, current_y; - Sys_GetCursorPos(GTK_WINDOW(widget), ¤t_x, ¤t_y); - int dx = current_x - self->recorded_x; - int dy = current_y - self->recorded_y; - if(dx != 0 || dy != 0) - { - //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; - Sys_SetCursorPos(GTK_WINDOW(widget), self->recorded_x, self->recorded_y); - self->m_function(dx, dy, event->state, self->m_data); - } - return FALSE; - } - - void freeze_pointer(GtkWindow* window, MotionDeltaFunction function, void* data) - { - ASSERT_MESSAGE(m_function == 0, "can't freeze pointer"); - - const GdkEventMask mask = static_cast(GDK_POINTER_MOTION_MASK - | GDK_POINTER_MOTION_HINT_MASK - | GDK_BUTTON_MOTION_MASK - | GDK_BUTTON1_MOTION_MASK - | GDK_BUTTON2_MOTION_MASK - | GDK_BUTTON3_MOTION_MASK - | GDK_BUTTON_PRESS_MASK - | GDK_BUTTON_RELEASE_MASK - | GDK_VISIBILITY_NOTIFY_MASK); - - GdkCursor* cursor = create_blank_cursor(); - //GdkGrabStatus status = - gdk_pointer_grab(GTK_WIDGET(window)->window, TRUE, mask, 0, cursor, GDK_CURRENT_TIME); - gdk_cursor_unref(cursor); - - Sys_GetCursorPos(window, &recorded_x, &recorded_y); - - Sys_SetCursorPos(window, recorded_x, recorded_y); - - m_function = function; - m_data = data; - - handle_motion = g_signal_connect(G_OBJECT(window), "motion_notify_event", G_CALLBACK(motion_delta), this); - } - - void unfreeze_pointer(GtkWindow* window) - { - g_signal_handler_disconnect(G_OBJECT(window), handle_motion); - - m_function = 0; - m_data = 0; - - Sys_SetCursorPos(window, recorded_x, recorded_y); - - gdk_pointer_ungrab(GDK_CURRENT_TIME); - } +FreezePointer() : handle_motion( 0 ), m_function( 0 ), m_data( 0 ){ +} +static gboolean motion_delta( GtkWidget *widget, GdkEventMotion *event, FreezePointer* self ){ + int current_x, current_y; + Sys_GetCursorPos( GTK_WINDOW( widget ), ¤t_x, ¤t_y ); + int dx = current_x - self->recorded_x; + int dy = current_y - self->recorded_y; + if ( dx != 0 || dy != 0 ) { + //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; + Sys_SetCursorPos( GTK_WINDOW( widget ), self->recorded_x, self->recorded_y ); + self->m_function( dx, dy, event->state, self->m_data ); + } + return FALSE; +} + +void freeze_pointer( GtkWindow* window, MotionDeltaFunction function, void* data ){ + ASSERT_MESSAGE( m_function == 0, "can't freeze pointer" ); + + const GdkEventMask mask = static_cast( GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK + | GDK_BUTTON_MOTION_MASK + | GDK_BUTTON1_MOTION_MASK + | GDK_BUTTON2_MOTION_MASK + | GDK_BUTTON3_MOTION_MASK + | GDK_BUTTON_PRESS_MASK + | GDK_BUTTON_RELEASE_MASK + | GDK_VISIBILITY_NOTIFY_MASK ); + + GdkCursor* cursor = create_blank_cursor(); + //GdkGrabStatus status = + gdk_pointer_grab( GTK_WIDGET( window )->window, TRUE, mask, 0, cursor, GDK_CURRENT_TIME ); + gdk_cursor_unref( cursor ); + + Sys_GetCursorPos( window, &recorded_x, &recorded_y ); + + Sys_SetCursorPos( window, recorded_x, recorded_y ); + + m_function = function; + m_data = data; + + handle_motion = g_signal_connect( G_OBJECT( window ), "motion_notify_event", G_CALLBACK( motion_delta ), this ); +} + +void unfreeze_pointer( GtkWindow* window ){ + g_signal_handler_disconnect( G_OBJECT( window ), handle_motion ); + + m_function = 0; + m_data = 0; + + Sys_SetCursorPos( window, recorded_x, recorded_y ); + + gdk_pointer_ungrab( GDK_CURRENT_TIME ); +} }; #endif diff --git a/libs/gtkutil/dialog.cpp b/libs/gtkutil/dialog.cpp index 0f95e9ae..59f5c5d9 100644 --- a/libs/gtkutil/dialog.cpp +++ b/libs/gtkutil/dialog.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "dialog.h" @@ -35,269 +35,242 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "button.h" #include "window.h" -GtkVBox* create_dialog_vbox(int spacing, int border) -{ - GtkVBox* vbox = GTK_VBOX(gtk_vbox_new(FALSE, spacing)); - gtk_widget_show(GTK_WIDGET(vbox)); - gtk_container_set_border_width(GTK_CONTAINER(vbox), border); - return vbox; +GtkVBox* create_dialog_vbox( int spacing, int border ){ + GtkVBox* vbox = GTK_VBOX( gtk_vbox_new( FALSE, spacing ) ); + gtk_widget_show( GTK_WIDGET( vbox ) ); + gtk_container_set_border_width( GTK_CONTAINER( vbox ), border ); + return vbox; } -GtkHBox* create_dialog_hbox(int spacing, int border) -{ - GtkHBox* hbox = GTK_HBOX(gtk_hbox_new(FALSE, spacing)); - gtk_widget_show(GTK_WIDGET(hbox)); - gtk_container_set_border_width(GTK_CONTAINER(hbox), border); - return hbox; +GtkHBox* create_dialog_hbox( int spacing, int border ){ + GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( FALSE, spacing ) ); + gtk_widget_show( GTK_WIDGET( hbox ) ); + gtk_container_set_border_width( GTK_CONTAINER( hbox ), border ); + return hbox; } -GtkFrame* create_dialog_frame(const char* label, GtkShadowType shadow) -{ - GtkFrame* frame = GTK_FRAME(gtk_frame_new(label)); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_frame_set_shadow_type(frame, shadow); - return frame; +GtkFrame* create_dialog_frame( const char* label, GtkShadowType shadow ){ + GtkFrame* frame = GTK_FRAME( gtk_frame_new( label ) ); + gtk_widget_show( GTK_WIDGET( frame ) ); + gtk_frame_set_shadow_type( frame, shadow ); + return frame; } -GtkTable* create_dialog_table(unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border) -{ - GtkTable* table = GTK_TABLE(gtk_table_new(rows, columns, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_table_set_row_spacings(table, row_spacing); - gtk_table_set_col_spacings(table, col_spacing); - gtk_container_set_border_width(GTK_CONTAINER(table), border); - return table; +GtkTable* create_dialog_table( unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border ){ + GtkTable* table = GTK_TABLE( gtk_table_new( rows, columns, FALSE ) ); + gtk_widget_show( GTK_WIDGET( table ) ); + gtk_table_set_row_spacings( table, row_spacing ); + gtk_table_set_col_spacings( table, col_spacing ); + gtk_container_set_border_width( GTK_CONTAINER( table ), border ); + return table; } -GtkButton* create_dialog_button(const char* label, GCallback func, gpointer data) -{ - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label(label)); - gtk_widget_set_size_request(GTK_WIDGET(button), 64, -1); - gtk_widget_show(GTK_WIDGET(button)); - g_signal_connect(G_OBJECT(button), "clicked", func, data); - return button; +GtkButton* create_dialog_button( const char* label, GCallback func, gpointer data ){ + GtkButton* button = GTK_BUTTON( gtk_button_new_with_label( label ) ); + gtk_widget_set_size_request( GTK_WIDGET( button ), 64, -1 ); + gtk_widget_show( GTK_WIDGET( button ) ); + g_signal_connect( G_OBJECT( button ), "clicked", func, data ); + return button; } -GtkWindow* create_dialog_window(GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w, int default_h) -{ - GtkWindow* window = create_floating_window(title, parent); - gtk_window_set_default_size(window, default_w, default_h); - gtk_window_set_position(window, GTK_WIN_POS_CENTER_ON_PARENT); - g_signal_connect(G_OBJECT(window), "delete_event", func, data); +GtkWindow* create_dialog_window( GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w, int default_h ){ + GtkWindow* window = create_floating_window( title, parent ); + gtk_window_set_default_size( window, default_w, default_h ); + gtk_window_set_position( window, GTK_WIN_POS_CENTER_ON_PARENT ); + g_signal_connect( G_OBJECT( window ), "delete_event", func, data ); - return window; + return window; } -gboolean modal_dialog_button_clicked(GtkWidget *widget, ModalDialogButton* button) -{ - button->m_dialog.loop = false; - button->m_dialog.ret = button->m_value; - return TRUE; +gboolean modal_dialog_button_clicked( GtkWidget *widget, ModalDialogButton* button ){ + button->m_dialog.loop = false; + button->m_dialog.ret = button->m_value; + return TRUE; } -gboolean modal_dialog_delete(GtkWidget *widget, GdkEvent* event, ModalDialog* dialog) -{ - dialog->loop = 0; - dialog->ret = eIDCANCEL; - return TRUE; +gboolean modal_dialog_delete( GtkWidget *widget, GdkEvent* event, ModalDialog* dialog ){ + dialog->loop = 0; + dialog->ret = eIDCANCEL; + return TRUE; } -EMessageBoxReturn modal_dialog_show(GtkWindow* window, ModalDialog& dialog) -{ - gtk_grab_add(GTK_WIDGET(window)); - gtk_widget_show(GTK_WIDGET(window)); +EMessageBoxReturn modal_dialog_show( GtkWindow* window, ModalDialog& dialog ){ + gtk_grab_add( GTK_WIDGET( window ) ); + gtk_widget_show( GTK_WIDGET( window ) ); - dialog.loop = true; - while(dialog.loop) - { - gtk_main_iteration(); - } + dialog.loop = true; + while ( dialog.loop ) + { + gtk_main_iteration(); + } - gtk_widget_hide(GTK_WIDGET(window)); - gtk_grab_remove(GTK_WIDGET(window)); + gtk_widget_hide( GTK_WIDGET( window ) ); + gtk_grab_remove( GTK_WIDGET( window ) ); - return dialog.ret; + return dialog.ret; } -GtkButton* create_modal_dialog_button(const char* label, ModalDialogButton& button) -{ - return create_dialog_button(label, G_CALLBACK(modal_dialog_button_clicked), &button); +GtkButton* create_modal_dialog_button( const char* label, ModalDialogButton& button ){ + return create_dialog_button( label, G_CALLBACK( modal_dialog_button_clicked ), &button ); } -GtkWindow* create_modal_dialog_window(GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w, int default_h) -{ - return create_dialog_window(parent, title, G_CALLBACK(modal_dialog_delete), &dialog, default_w, default_h); +GtkWindow* create_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w, int default_h ){ + return create_dialog_window( parent, title, G_CALLBACK( modal_dialog_delete ), &dialog, default_w, default_h ); } -GtkWindow* create_fixedsize_modal_dialog_window(GtkWindow* parent, const char* title, ModalDialog& dialog, int width, int height) -{ - GtkWindow* window = create_modal_dialog_window(parent, title, dialog, width, height); +GtkWindow* create_fixedsize_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int width, int height ){ + GtkWindow* window = create_modal_dialog_window( parent, title, dialog, width, height ); - gtk_window_set_resizable(window, FALSE); - gtk_window_set_modal(window, TRUE); - gtk_window_set_position(window, GTK_WIN_POS_CENTER); + gtk_window_set_resizable( window, FALSE ); + gtk_window_set_modal( window, TRUE ); + gtk_window_set_position( window, GTK_WIN_POS_CENTER ); - window_remove_minmax(window); + window_remove_minmax( window ); - //gtk_widget_set_size_request(GTK_WIDGET(window), width, height); - //gtk_window_set_default_size(window, width, height); - //gtk_window_resize(window, width, height); - //GdkGeometry geometry = { width, height, -1, -1, width, height, -1, -1, -1, -1, GDK_GRAVITY_STATIC, }; - //gtk_window_set_geometry_hints(window, GTK_WIDGET(window), &geometry, (GdkWindowHints)(GDK_HINT_POS|GDK_HINT_MIN_SIZE|GDK_HINT_BASE_SIZE)); + //gtk_widget_set_size_request(GTK_WIDGET(window), width, height); + //gtk_window_set_default_size(window, width, height); + //gtk_window_resize(window, width, height); + //GdkGeometry geometry = { width, height, -1, -1, width, height, -1, -1, -1, -1, GDK_GRAVITY_STATIC, }; + //gtk_window_set_geometry_hints(window, GTK_WIDGET(window), &geometry, (GdkWindowHints)(GDK_HINT_POS|GDK_HINT_MIN_SIZE|GDK_HINT_BASE_SIZE)); - return window; + return window; } -gboolean dialog_button_ok(GtkWidget *widget, ModalDialog* data) -{ - data->loop = false; - data->ret = eIDOK; - return TRUE; +gboolean dialog_button_ok( GtkWidget *widget, ModalDialog* data ){ + data->loop = false; + data->ret = eIDOK; + return TRUE; } -gboolean dialog_button_cancel(GtkWidget *widget, ModalDialog* data) -{ - data->loop = false; - data->ret = eIDCANCEL; - return TRUE; +gboolean dialog_button_cancel( GtkWidget *widget, ModalDialog* data ){ + data->loop = false; + data->ret = eIDCANCEL; + return TRUE; } -gboolean dialog_button_yes(GtkWidget *widget, ModalDialog* data) -{ - data->loop = false; - data->ret = eIDYES; - return TRUE; +gboolean dialog_button_yes( GtkWidget *widget, ModalDialog* data ){ + data->loop = false; + data->ret = eIDYES; + return TRUE; } -gboolean dialog_button_no(GtkWidget *widget, ModalDialog* data) -{ - data->loop = false; - data->ret = eIDNO; - return TRUE; +gboolean dialog_button_no( GtkWidget *widget, ModalDialog* data ){ + data->loop = false; + data->ret = eIDNO; + return TRUE; } -gboolean dialog_delete_callback(GtkWidget *widget, GdkEventAny* event, ModalDialog* data) -{ - gtk_widget_hide(widget); - data->loop = false; - return TRUE; +gboolean dialog_delete_callback( GtkWidget *widget, GdkEventAny* event, ModalDialog* data ){ + gtk_widget_hide( widget ); + data->loop = false; + return TRUE; } -GtkWindow* create_simple_modal_dialog_window(const char* title, ModalDialog& dialog, GtkWidget* contents) -{ - GtkWindow* window = create_fixedsize_modal_dialog_window(0, title, dialog); +GtkWindow* create_simple_modal_dialog_window( const char* title, ModalDialog& dialog, GtkWidget* contents ){ + GtkWindow* window = create_fixedsize_modal_dialog_window( 0, title, dialog ); - GtkVBox* vbox1 = create_dialog_vbox(8, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox1)); + GtkVBox* vbox1 = create_dialog_vbox( 8, 4 ); + gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox1 ) ); - gtk_container_add(GTK_CONTAINER(vbox1), contents); + gtk_container_add( GTK_CONTAINER( vbox1 ), contents ); - GtkAlignment* alignment = GTK_ALIGNMENT(gtk_alignment_new(0.5, 0.0, 0.0, 0.0)); - gtk_widget_show(GTK_WIDGET(alignment)); - gtk_box_pack_start(GTK_BOX(vbox1), GTK_WIDGET(alignment), FALSE, FALSE, 0); + GtkAlignment* alignment = GTK_ALIGNMENT( gtk_alignment_new( 0.5, 0.0, 0.0, 0.0 ) ); + gtk_widget_show( GTK_WIDGET( alignment ) ); + gtk_box_pack_start( GTK_BOX( vbox1 ), GTK_WIDGET( alignment ), FALSE, FALSE, 0 ); - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &dialog); - gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(button)); + GtkButton* button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &dialog ); + gtk_container_add( GTK_CONTAINER( alignment ), GTK_WIDGET( button ) ); - return window; + return window; } -RadioHBox RadioHBox_new(StringArrayRange names) -{ - GtkHBox* hbox = GTK_HBOX(gtk_hbox_new(TRUE, 4)); - gtk_widget_show(GTK_WIDGET(hbox)); +RadioHBox RadioHBox_new( StringArrayRange names ){ + GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( TRUE, 4 ) ); + gtk_widget_show( GTK_WIDGET( hbox ) ); - GSList* group = 0; - GtkRadioButton* radio = 0; - for(StringArrayRange::Iterator i = names.first; i != names.last; ++i) - { - radio = GTK_RADIO_BUTTON(gtk_radio_button_new_with_label(group, *i)); - gtk_widget_show(GTK_WIDGET(radio)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(radio), FALSE, FALSE, 0); + GSList* group = 0; + GtkRadioButton* radio = 0; + for ( StringArrayRange::Iterator i = names.first; i != names.last; ++i ) + { + radio = GTK_RADIO_BUTTON( gtk_radio_button_new_with_label( group, *i ) ); + gtk_widget_show( GTK_WIDGET( radio ) ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( radio ), FALSE, FALSE, 0 ); - group = gtk_radio_button_get_group(radio); - } + group = gtk_radio_button_get_group( radio ); + } - return RadioHBox(hbox, radio); + return RadioHBox( hbox, radio ); } -PathEntry PathEntry_new() -{ - GtkFrame* frame = GTK_FRAME(gtk_frame_new(NULL)); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_frame_set_shadow_type(frame, GTK_SHADOW_IN); +PathEntry PathEntry_new(){ + GtkFrame* frame = GTK_FRAME( gtk_frame_new( NULL ) ); + gtk_widget_show( GTK_WIDGET( frame ) ); + gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN ); - // path entry - GtkHBox* hbox = GTK_HBOX(gtk_hbox_new(FALSE, 0)); - gtk_widget_show(GTK_WIDGET(hbox)); + // path entry + GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( FALSE, 0 ) ); + gtk_widget_show( GTK_WIDGET( hbox ) ); - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_entry_set_has_frame(entry, FALSE); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(entry), TRUE, TRUE, 0); + GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); + gtk_entry_set_has_frame( entry, FALSE ); + gtk_widget_show( GTK_WIDGET( entry ) ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - // browse button - GtkButton* button = GTK_BUTTON(gtk_button_new()); - button_set_icon(button, "ellipsis.bmp"); - gtk_widget_show(GTK_WIDGET(button)); - gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + // browse button + GtkButton* button = GTK_BUTTON( gtk_button_new() ); + button_set_icon( button, "ellipsis.bmp" ); + gtk_widget_show( GTK_WIDGET( button ) ); + gtk_box_pack_end( GTK_BOX( hbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 ); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(hbox)); + gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( hbox ) ); - return PathEntry(frame, entry, button); + return PathEntry( frame, entry, button ); } -void PathEntry_setPath(PathEntry& self, const char* path) -{ - gtk_entry_set_text(self.m_entry, path); +void PathEntry_setPath( PathEntry& self, const char* path ){ + gtk_entry_set_text( self.m_entry, path ); } typedef ReferenceCaller1 PathEntrySetPathCaller; -void BrowsedPathEntry_clicked(GtkWidget* widget, BrowsedPathEntry* self) -{ - self->m_browse(PathEntrySetPathCaller(self->m_entry)); +void BrowsedPathEntry_clicked( GtkWidget* widget, BrowsedPathEntry* self ){ + self->m_browse( PathEntrySetPathCaller( self->m_entry ) ); } -BrowsedPathEntry::BrowsedPathEntry(const BrowseCallback& browse) : - m_entry(PathEntry_new()), - m_browse(browse) -{ - g_signal_connect(G_OBJECT(m_entry.m_button), "clicked", G_CALLBACK(BrowsedPathEntry_clicked), this); +BrowsedPathEntry::BrowsedPathEntry( const BrowseCallback& browse ) : + m_entry( PathEntry_new() ), + m_browse( browse ){ + g_signal_connect( G_OBJECT( m_entry.m_button ), "clicked", G_CALLBACK( BrowsedPathEntry_clicked ), this ); } -GtkLabel* DialogLabel_new(const char* name) -{ - GtkLabel* label = GTK_LABEL(gtk_label_new(name)); - gtk_widget_show(GTK_WIDGET(label)); - gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); - gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); +GtkLabel* DialogLabel_new( const char* name ){ + GtkLabel* label = GTK_LABEL( gtk_label_new( name ) ); + gtk_widget_show( GTK_WIDGET( label ) ); + gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); + gtk_label_set_justify( label, GTK_JUSTIFY_LEFT ); - return label; + return label; } -GtkTable* DialogRow_new(const char* name, GtkWidget* widget) -{ - GtkTable* table = GTK_TABLE(gtk_table_new(1, 3, TRUE)); - gtk_widget_show(GTK_WIDGET(table)); +GtkTable* DialogRow_new( const char* name, GtkWidget* widget ){ + GtkTable* table = GTK_TABLE( gtk_table_new( 1, 3, TRUE ) ); + gtk_widget_show( GTK_WIDGET( table ) ); - gtk_table_set_col_spacings(table, 4); - gtk_table_set_row_spacings(table, 0); + gtk_table_set_col_spacings( table, 4 ); + gtk_table_set_row_spacings( table, 0 ); - gtk_table_attach(table, GTK_WIDGET(DialogLabel_new(name)), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); + gtk_table_attach( table, GTK_WIDGET( DialogLabel_new( name ) ), 0, 1, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); - gtk_table_attach(table, widget, 1, 3, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); + gtk_table_attach( table, widget, 1, 3, 0, 1, + (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), + (GtkAttachOptions) ( 0 ), 0, 0 ); - return table; + return table; } -void DialogVBox_packRow(GtkVBox* vbox, GtkWidget* row) -{ - gtk_box_pack_start(GTK_BOX(vbox), row, FALSE, FALSE, 0); +void DialogVBox_packRow( GtkVBox* vbox, GtkWidget* row ){ + gtk_box_pack_start( GTK_BOX( vbox ), row, FALSE, FALSE, 0 ); } - diff --git a/libs/gtkutil/dialog.h b/libs/gtkutil/dialog.h index 150404a2..5a87731e 100644 --- a/libs/gtkutil/dialog.h +++ b/libs/gtkutil/dialog.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_DIALOG_H) +#if !defined( INCLUDED_GTKUTIL_DIALOG_H ) #define INCLUDED_GTKUTIL_DIALOG_H #include "generic/callback.h" @@ -43,25 +43,23 @@ typedef struct _GtkTable GtkTable; struct ModalDialog { - ModalDialog() - : loop(true), ret(eIDCANCEL) - { - } - bool loop; - EMessageBoxReturn ret; + ModalDialog() + : loop( true ), ret( eIDCANCEL ){ + } + bool loop; + EMessageBoxReturn ret; }; struct ModalDialogButton { - ModalDialogButton(ModalDialog& dialog, EMessageBoxReturn value) - : m_dialog(dialog), m_value(value) - { - } - ModalDialog& m_dialog; - EMessageBoxReturn m_value; + ModalDialogButton( ModalDialog& dialog, EMessageBoxReturn value ) + : m_dialog( dialog ), m_value( value ){ + } + ModalDialog& m_dialog; + EMessageBoxReturn m_value; }; -typedef void (*GCallback)(void); +typedef void ( *GCallback )( void ); typedef void* gpointer; typedef struct _GtkWindow GtkWindow; typedef struct _GtkTable GtkTable; @@ -70,56 +68,54 @@ typedef struct _GtkVBox GtkVBox; typedef struct _GtkHBox GtkHBox; typedef struct _GtkFrame GtkFrame; -GtkWindow* create_fixedsize_modal_window(GtkWindow* parent, const char* title, int width, int height); +GtkWindow* create_fixedsize_modal_window( GtkWindow* parent, const char* title, int width, int height ); -GtkWindow* create_dialog_window(GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w = -1, int default_h = -1); -GtkTable* create_dialog_table(unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border = 0); -GtkButton* create_dialog_button(const char* label, GCallback func, gpointer data); -GtkVBox* create_dialog_vbox(int spacing, int border = 0); -GtkHBox* create_dialog_hbox(int spacing, int border = 0); -GtkFrame* create_dialog_frame(const char* label, GtkShadowType shadow = GTK_SHADOW_ETCHED_IN); +GtkWindow* create_dialog_window( GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w = -1, int default_h = -1 ); +GtkTable* create_dialog_table( unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border = 0 ); +GtkButton* create_dialog_button( const char* label, GCallback func, gpointer data ); +GtkVBox* create_dialog_vbox( int spacing, int border = 0 ); +GtkHBox* create_dialog_hbox( int spacing, int border = 0 ); +GtkFrame* create_dialog_frame( const char* label, GtkShadowType shadow = GTK_SHADOW_ETCHED_IN ); -GtkButton* create_modal_dialog_button(const char* label, ModalDialogButton& button); -GtkWindow* create_modal_dialog_window(GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w = -1, int default_h = -1); -GtkWindow* create_fixedsize_modal_dialog_window(GtkWindow* parent, const char* title, ModalDialog& dialog, int width = -1, int height = -1); -EMessageBoxReturn modal_dialog_show(GtkWindow* window, ModalDialog& dialog); +GtkButton* create_modal_dialog_button( const char* label, ModalDialogButton& button ); +GtkWindow* create_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w = -1, int default_h = -1 ); +GtkWindow* create_fixedsize_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int width = -1, int height = -1 ); +EMessageBoxReturn modal_dialog_show( GtkWindow* window, ModalDialog& dialog ); -gboolean dialog_button_ok(GtkWidget *widget, ModalDialog* data); -gboolean dialog_button_cancel(GtkWidget *widget, ModalDialog* data); -gboolean dialog_button_yes(GtkWidget *widget, ModalDialog* data); -gboolean dialog_button_no(GtkWidget *widget, ModalDialog* data); -gboolean dialog_delete_callback(GtkWidget *widget, GdkEventAny* event, ModalDialog* data); +gboolean dialog_button_ok( GtkWidget *widget, ModalDialog* data ); +gboolean dialog_button_cancel( GtkWidget *widget, ModalDialog* data ); +gboolean dialog_button_yes( GtkWidget *widget, ModalDialog* data ); +gboolean dialog_button_no( GtkWidget *widget, ModalDialog* data ); +gboolean dialog_delete_callback( GtkWidget *widget, GdkEventAny* event, ModalDialog* data ); -GtkWindow* create_simple_modal_dialog_window(const char* title, ModalDialog& dialog, GtkWidget* contents); +GtkWindow* create_simple_modal_dialog_window( const char* title, ModalDialog& dialog, GtkWidget* contents ); class RadioHBox { public: - GtkHBox* m_hbox; - GtkRadioButton* m_radio; - RadioHBox(GtkHBox* hbox, GtkRadioButton* radio) : - m_hbox(hbox), - m_radio(radio) - { - } +GtkHBox* m_hbox; +GtkRadioButton* m_radio; +RadioHBox( GtkHBox* hbox, GtkRadioButton* radio ) : + m_hbox( hbox ), + m_radio( radio ){ +} }; -RadioHBox RadioHBox_new(StringArrayRange names); +RadioHBox RadioHBox_new( StringArrayRange names ); class PathEntry { public: - GtkFrame* m_frame; - GtkEntry* m_entry; - GtkButton* m_button; - PathEntry(GtkFrame* frame, GtkEntry* entry, GtkButton* button) : - m_frame(frame), - m_entry(entry), - m_button(button) - { - } +GtkFrame* m_frame; +GtkEntry* m_entry; +GtkButton* m_button; +PathEntry( GtkFrame* frame, GtkEntry* entry, GtkButton* button ) : + m_frame( frame ), + m_entry( entry ), + m_button( button ){ +} }; PathEntry PathEntry_new(); @@ -127,19 +123,19 @@ PathEntry PathEntry_new(); class BrowsedPathEntry { public: - typedef Callback1 SetPathCallback; - typedef Callback1 BrowseCallback; +typedef Callback1 SetPathCallback; +typedef Callback1 BrowseCallback; - PathEntry m_entry; - BrowseCallback m_browse; +PathEntry m_entry; +BrowseCallback m_browse; - BrowsedPathEntry(const BrowseCallback& browse); +BrowsedPathEntry( const BrowseCallback& browse ); }; -GtkLabel* DialogLabel_new(const char* name); -GtkTable* DialogRow_new(const char* name, GtkWidget* widget); +GtkLabel* DialogLabel_new( const char* name ); +GtkTable* DialogRow_new( const char* name, GtkWidget* widget ); typedef struct _GtkVBox GtkVBox; -void DialogVBox_packRow(GtkVBox* vbox, GtkWidget* row); +void DialogVBox_packRow( GtkVBox* vbox, GtkWidget* row ); #endif diff --git a/libs/gtkutil/entry.cpp b/libs/gtkutil/entry.cpp index 9c3c1553..2640da0f 100644 --- a/libs/gtkutil/entry.cpp +++ b/libs/gtkutil/entry.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "entry.h" - diff --git a/libs/gtkutil/entry.h b/libs/gtkutil/entry.h index 82957d29..814be152 100644 --- a/libs/gtkutil/entry.h +++ b/libs/gtkutil/entry.h @@ -1,63 +1,57 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_ENTRY_H) +#if !defined( INCLUDED_GTKUTIL_ENTRY_H ) #define INCLUDED_GTKUTIL_ENTRY_H #include #include #include -inline void entry_set_string(GtkEntry* entry, const char* string) -{ - gtk_entry_set_text(entry, string); +inline void entry_set_string( GtkEntry* entry, const char* string ){ + gtk_entry_set_text( entry, string ); } -inline void entry_set_int(GtkEntry* entry, int i) -{ - char buf[32]; - sprintf(buf, "%d", i); - entry_set_string(entry, buf); +inline void entry_set_int( GtkEntry* entry, int i ){ + char buf[32]; + sprintf( buf, "%d", i ); + entry_set_string( entry, buf ); } -inline void entry_set_float(GtkEntry* entry, float f) -{ - char buf[32]; - sprintf(buf, "%g", f); - entry_set_string(entry, buf); +inline void entry_set_float( GtkEntry* entry, float f ){ + char buf[32]; + sprintf( buf, "%g", f ); + entry_set_string( entry, buf ); } -inline const char* entry_get_string(GtkEntry* entry) -{ - return gtk_entry_get_text(entry); +inline const char* entry_get_string( GtkEntry* entry ){ + return gtk_entry_get_text( entry ); } -inline int entry_get_int(GtkEntry* entry) -{ - return atoi(entry_get_string(entry)); +inline int entry_get_int( GtkEntry* entry ){ + return atoi( entry_get_string( entry ) ); } -inline double entry_get_float(GtkEntry* entry) -{ - return atof(entry_get_string(entry)); +inline double entry_get_float( GtkEntry* entry ){ + return atof( entry_get_string( entry ) ); } #endif diff --git a/libs/gtkutil/filechooser.cpp b/libs/gtkutil/filechooser.cpp index 2246b57b..d65d310c 100644 --- a/libs/gtkutil/filechooser.cpp +++ b/libs/gtkutil/filechooser.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "filechooser.h" @@ -42,264 +42,242 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA struct filetype_pair_t { - filetype_pair_t() - : m_moduleName("") - { - } - filetype_pair_t(const char* moduleName, filetype_t type) - : m_moduleName(moduleName), m_type(type) - { - } - const char* m_moduleName; - filetype_t m_type; + filetype_pair_t() + : m_moduleName( "" ){ + } + filetype_pair_t( const char* moduleName, filetype_t type ) + : m_moduleName( moduleName ), m_type( type ){ + } + const char* m_moduleName; + filetype_t m_type; }; class FileTypeList : public IFileTypeList { - struct filetype_copy_t - { - filetype_copy_t(const filetype_pair_t& other) - : m_moduleName(other.m_moduleName), m_name(other.m_type.name), m_pattern(other.m_type.pattern) - { - } - CopiedString m_moduleName; - CopiedString m_name; - CopiedString m_pattern; - }; - - typedef std::list Types; - Types m_types; +struct filetype_copy_t +{ + filetype_copy_t( const filetype_pair_t& other ) + : m_moduleName( other.m_moduleName ), m_name( other.m_type.name ), m_pattern( other.m_type.pattern ){ + } + CopiedString m_moduleName; + CopiedString m_name; + CopiedString m_pattern; +}; + +typedef std::list Types; +Types m_types; public: - typedef Types::const_iterator const_iterator; - const_iterator begin() const - { - return m_types.begin(); - } - const_iterator end() const - { - return m_types.end(); - } - - std::size_t size() const - { - return m_types.size(); - } - - void addType(const char* moduleName, filetype_t type) - { - m_types.push_back(filetype_pair_t(moduleName, type)); - } +typedef Types::const_iterator const_iterator; +const_iterator begin() const { + return m_types.begin(); +} +const_iterator end() const { + return m_types.end(); +} + +std::size_t size() const { + return m_types.size(); +} + +void addType( const char* moduleName, filetype_t type ){ + m_types.push_back( filetype_pair_t( moduleName, type ) ); +} }; class GTKMasks { - const FileTypeList& m_types; +const FileTypeList& m_types; public: - std::vector m_filters; - std::vector m_masks; - - GTKMasks(const FileTypeList& types) : m_types(types) - { - m_masks.reserve(m_types.size()); - for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i) - { - std::size_t len = strlen((*i).m_name.c_str()) + strlen((*i).m_pattern.c_str()) + 3; - StringOutputStream buffer(len + 1); // length + null char - - buffer << (*i).m_name.c_str() << " <" << (*i).m_pattern.c_str() << ">"; - - m_masks.push_back(buffer.c_str()); - } - - m_filters.reserve(m_types.size()); - for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i) - { - m_filters.push_back((*i).m_pattern); - } - } - - filetype_pair_t GetTypeForGTKMask(const char *mask) const - { - std::vector::const_iterator j = m_masks.begin(); - for(FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j) - { - if(string_equal((*j).c_str(), mask)) - { - return filetype_pair_t((*i).m_moduleName.c_str(), filetype_t((*i).m_name.c_str(), (*i).m_pattern.c_str())); - } - } - return filetype_pair_t(); - } +std::vector m_filters; +std::vector m_masks; + +GTKMasks( const FileTypeList& types ) : m_types( types ){ + m_masks.reserve( m_types.size() ); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) + { + std::size_t len = strlen( ( *i ).m_name.c_str() ) + strlen( ( *i ).m_pattern.c_str() ) + 3; + StringOutputStream buffer( len + 1 ); // length + null char + + buffer << ( *i ).m_name.c_str() << " <" << ( *i ).m_pattern.c_str() << ">"; + + m_masks.push_back( buffer.c_str() ); + } + + m_filters.reserve( m_types.size() ); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) + { + m_filters.push_back( ( *i ).m_pattern ); + } +} + +filetype_pair_t GetTypeForGTKMask( const char *mask ) const { + std::vector::const_iterator j = m_masks.begin(); + for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j ) + { + if ( string_equal( ( *j ).c_str(), mask ) ) { + return filetype_pair_t( ( *i ).m_moduleName.c_str(), filetype_t( ( *i ).m_name.c_str(), ( *i ).m_pattern.c_str() ) ); + } + } + return filetype_pair_t(); +} }; static char g_file_dialog_file[1024]; -const char* file_dialog_show(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save) -{ - filetype_t type; - - if(pattern == 0) - { - pattern = "*"; - } - - FileTypeList typelist; - GlobalFiletypes().getTypeList(pattern, &typelist, want_load, want_import, want_save); - - GTKMasks masks(typelist); - - if (title == 0) - title = open ? "Open File" : "Save File"; - - GtkWidget* dialog; - if (open) - { - dialog = gtk_file_chooser_dialog_new(title, - GTK_WINDOW(parent), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - } - else - { - dialog = gtk_file_chooser_dialog_new(title, - GTK_WINDOW(parent), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL); - gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), "unnamed"); - } - - gtk_window_set_modal(GTK_WINDOW(dialog), TRUE); - gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT); - - // we expect an actual path below, if the path is 0 we might crash - if (path != 0 && !string_empty(path)) - { - ASSERT_MESSAGE(path_is_absolute(path), "file_dialog_show: path not absolute: " << makeQuoted(path)); - - Array new_path(strlen(path)+1); - - // copy path, replacing dir separators as appropriate - Array::iterator w = new_path.begin(); - for(const char* r = path; *r != '\0'; ++r) - { - *w++ = (*r == '/') ? G_DIR_SEPARATOR : *r; - } - // remove separator from end of path if required - if(*(w-1) == G_DIR_SEPARATOR) - { - --w; - } - // terminate string - *w = '\0'; - - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), new_path.data()); - } - - // we should add all important paths as shortcut folder... - // gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(dialog), "/tmp/", NULL); - - - for(std::size_t i = 0; i < masks.m_filters.size(); ++i) - { - GtkFileFilter* filter = gtk_file_filter_new(); - gtk_file_filter_add_pattern(filter, masks.m_filters[i].c_str()); - gtk_file_filter_set_name(filter, masks.m_masks[i].c_str()); - gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); - } - - if(gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) - { - strcpy(g_file_dialog_file, gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog))); - - if(!string_equal(pattern, "*")) - { - GtkFileFilter* filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog)); - if(filter != 0) // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files' - { - type = masks.GetTypeForGTKMask(gtk_file_filter_get_name(filter)).m_type; - // last ext separator - const char* extension = path_get_extension(g_file_dialog_file); - // no extension - if(string_empty(extension)) - { - strcat(g_file_dialog_file, type.pattern+1); - } - else - { - strcpy(g_file_dialog_file + (extension - g_file_dialog_file), type.pattern+2); - } - } - } - - // convert back to unix format - for(char* w = g_file_dialog_file; *w!='\0'; w++) - { - if(*w=='\\') - { - *w = '/'; - } - } - } - else - { - g_file_dialog_file[0] = '\0'; - } - - gtk_widget_destroy(dialog); - - // don't return an empty filename - if(g_file_dialog_file[0] == '\0') return NULL; - - return g_file_dialog_file; +const char* file_dialog_show( GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save ){ + filetype_t type; + + if ( pattern == 0 ) { + pattern = "*"; + } + + FileTypeList typelist; + GlobalFiletypes().getTypeList( pattern, &typelist, want_load, want_import, want_save ); + + GTKMasks masks( typelist ); + + if ( title == 0 ) { + title = open ? "Open File" : "Save File"; + } + + GtkWidget* dialog; + if ( open ) { + dialog = gtk_file_chooser_dialog_new( title, + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_OPEN, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, + NULL ); + } + else + { + dialog = gtk_file_chooser_dialog_new( title, + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_SAVE, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, + NULL ); + gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER( dialog ), "unnamed" ); + } + + gtk_window_set_modal( GTK_WINDOW( dialog ), TRUE ); + gtk_window_set_position( GTK_WINDOW( dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); + + // we expect an actual path below, if the path is 0 we might crash + if ( path != 0 && !string_empty( path ) ) { + ASSERT_MESSAGE( path_is_absolute( path ), "file_dialog_show: path not absolute: " << makeQuoted( path ) ); + + Array new_path( strlen( path ) + 1 ); + + // copy path, replacing dir separators as appropriate + Array::iterator w = new_path.begin(); + for ( const char* r = path; *r != '\0'; ++r ) + { + *w++ = ( *r == '/' ) ? G_DIR_SEPARATOR : *r; + } + // remove separator from end of path if required + if ( *( w - 1 ) == G_DIR_SEPARATOR ) { + --w; + } + // terminate string + *w = '\0'; + + gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER( dialog ), new_path.data() ); + } + + // we should add all important paths as shortcut folder... + // gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(dialog), "/tmp/", NULL); + + + for ( std::size_t i = 0; i < masks.m_filters.size(); ++i ) + { + GtkFileFilter* filter = gtk_file_filter_new(); + gtk_file_filter_add_pattern( filter, masks.m_filters[i].c_str() ); + gtk_file_filter_set_name( filter, masks.m_masks[i].c_str() ); + gtk_file_chooser_add_filter( GTK_FILE_CHOOSER( dialog ), filter ); + } + + if ( gtk_dialog_run( GTK_DIALOG( dialog ) ) == GTK_RESPONSE_ACCEPT ) { + strcpy( g_file_dialog_file, gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) ) ); + + if ( !string_equal( pattern, "*" ) ) { + GtkFileFilter* filter = gtk_file_chooser_get_filter( GTK_FILE_CHOOSER( dialog ) ); + if ( filter != 0 ) { // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files' + type = masks.GetTypeForGTKMask( gtk_file_filter_get_name( filter ) ).m_type; + // last ext separator + const char* extension = path_get_extension( g_file_dialog_file ); + // no extension + if ( string_empty( extension ) ) { + strcat( g_file_dialog_file, type.pattern + 1 ); + } + else + { + strcpy( g_file_dialog_file + ( extension - g_file_dialog_file ), type.pattern + 2 ); + } + } + } + + // convert back to unix format + for ( char* w = g_file_dialog_file; *w != '\0'; w++ ) + { + if ( *w == '\\' ) { + *w = '/'; + } + } + } + else + { + g_file_dialog_file[0] = '\0'; + } + + gtk_widget_destroy( dialog ); + + // don't return an empty filename + if ( g_file_dialog_file[0] == '\0' ) { + return NULL; + } + + return g_file_dialog_file; } -char* dir_dialog(GtkWidget* parent, const char* title, const char* path) -{ - GtkWidget* dialog = gtk_file_chooser_dialog_new(title, - GTK_WINDOW(parent), - GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - - gtk_window_set_modal(GTK_WINDOW(dialog), TRUE); - gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT); - - if(!string_empty(path)) - { - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), path); - } - - char* filename = 0; - if(gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) - { - filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - } - - gtk_widget_destroy(dialog); - - return filename; +char* dir_dialog( GtkWidget* parent, const char* title, const char* path ){ + GtkWidget* dialog = gtk_file_chooser_dialog_new( title, + GTK_WINDOW( parent ), + GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, + NULL ); + + gtk_window_set_modal( GTK_WINDOW( dialog ), TRUE ); + gtk_window_set_position( GTK_WINDOW( dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); + + if ( !string_empty( path ) ) { + gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER( dialog ), path ); + } + + char* filename = 0; + if ( gtk_dialog_run( GTK_DIALOG( dialog ) ) == GTK_RESPONSE_ACCEPT ) { + filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) ); + } + + gtk_widget_destroy( dialog ); + + return filename; } -const char* file_dialog(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save) -{ - for(;;) - { - const char* file = file_dialog_show(parent, open, title, path, pattern, want_load, want_import, want_save); - - if(open - || file == 0 - || !file_exists(file) - || gtk_MessageBox(parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION) == eIDYES) - { - return file; - } - } +const char* file_dialog( GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save ){ + for (;; ) + { + const char* file = file_dialog_show( parent, open, title, path, pattern, want_load, want_import, want_save ); + + if ( open + || file == 0 + || !file_exists( file ) + || gtk_MessageBox( parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION ) == eIDYES ) { + return file; + } + } } diff --git a/libs/gtkutil/filechooser.h b/libs/gtkutil/filechooser.h index 3789321e..f4610bea 100644 --- a/libs/gtkutil/filechooser.h +++ b/libs/gtkutil/filechooser.h @@ -1,38 +1,38 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_FILECHOOSER_H) +#if !defined( INCLUDED_GTKUTIL_FILECHOOSER_H ) #define INCLUDED_GTKUTIL_FILECHOOSER_H /// \file /// GTK+ file-chooser dialogs. typedef struct _GtkWidget GtkWidget; -const char* file_dialog(GtkWidget *parent, bool open, const char* title, const char* path = 0, const char* pattern = 0, bool want_load = false, bool want_import = false, bool want_save = false); +const char* file_dialog( GtkWidget *parent, bool open, const char* title, const char* path = 0, const char* pattern = 0, bool want_load = false, bool want_import = false, bool want_save = false ); /// \brief Prompts the user to browse for a directory. /// The prompt window will be transient to \p parent. /// The directory will initially default to \p path, which must be an absolute path. /// The returned string is allocated with \c g_malloc and must be freed with \c g_free. -char* dir_dialog(GtkWidget *parent, const char* title = "Choose Directory", const char* path = ""); +char* dir_dialog( GtkWidget *parent, const char* title = "Choose Directory", const char* path = "" ); #endif diff --git a/libs/gtkutil/frame.cpp b/libs/gtkutil/frame.cpp index 026de650..8914fb70 100644 --- a/libs/gtkutil/frame.cpp +++ b/libs/gtkutil/frame.cpp @@ -1,35 +1,33 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "frame.h" #include -GtkFrame* create_framed_widget(GtkWidget* widget) -{ - GtkFrame* frame = GTK_FRAME(gtk_frame_new(0)); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_frame_set_shadow_type(frame, GTK_SHADOW_IN); - gtk_container_add (GTK_CONTAINER(frame), widget); - gtk_widget_show(GTK_WIDGET(widget)); - return frame; +GtkFrame* create_framed_widget( GtkWidget* widget ){ + GtkFrame* frame = GTK_FRAME( gtk_frame_new( 0 ) ); + gtk_widget_show( GTK_WIDGET( frame ) ); + gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN ); + gtk_container_add( GTK_CONTAINER( frame ), widget ); + gtk_widget_show( GTK_WIDGET( widget ) ); + return frame; } - diff --git a/libs/gtkutil/frame.h b/libs/gtkutil/frame.h index 12305db2..ebeccc28 100644 --- a/libs/gtkutil/frame.h +++ b/libs/gtkutil/frame.h @@ -1,29 +1,29 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_FRAME_H) +#if !defined( INCLUDED_GTKUTIL_FRAME_H ) #define INCLUDED_GTKUTIL_FRAME_H typedef struct _GtkWidget GtkWidget; typedef struct _GtkFrame GtkFrame; -GtkFrame* create_framed_widget(GtkWidget* widget); +GtkFrame* create_framed_widget( GtkWidget* widget ); #endif diff --git a/libs/gtkutil/glfont.cpp b/libs/gtkutil/glfont.cpp index a3eac91d..09211a05 100644 --- a/libs/gtkutil/glfont.cpp +++ b/libs/gtkutil/glfont.cpp @@ -1,59 +1,53 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "glfont.h" #include "igl.h" // generic string printing with call lists -class GLFontCallList: public GLFont +class GLFontCallList : public GLFont { - GLuint m_displayList; - int m_pixelHeight; - int m_pixelAscent; - int m_pixelDescent; - public: - GLFontCallList(GLuint displayList, int asc, int desc, int pixelHeight) : m_displayList(displayList), m_pixelHeight(pixelHeight), m_pixelAscent(asc), m_pixelDescent(desc) - { - } - virtual ~GLFontCallList() - { - glDeleteLists(m_displayList, 256); - } - void printString(const char *s) - { - GlobalOpenGL().m_glListBase(m_displayList); - GlobalOpenGL().m_glCallLists(GLsizei(strlen(s)), GL_UNSIGNED_BYTE, reinterpret_cast(s)); - } - virtual int getPixelAscent() const - { - return m_pixelAscent; - } - virtual int getPixelDescent() const - { - return m_pixelDescent; - } - virtual int getPixelHeight() const - { - return m_pixelHeight; - } +GLuint m_displayList; +int m_pixelHeight; +int m_pixelAscent; +int m_pixelDescent; +public: +GLFontCallList( GLuint displayList, int asc, int desc, int pixelHeight ) : m_displayList( displayList ), m_pixelHeight( pixelHeight ), m_pixelAscent( asc ), m_pixelDescent( desc ){ +} +virtual ~GLFontCallList(){ + glDeleteLists( m_displayList, 256 ); +} +void printString( const char *s ){ + GlobalOpenGL().m_glListBase( m_displayList ); + GlobalOpenGL().m_glCallLists( GLsizei( strlen( s ) ), GL_UNSIGNED_BYTE, reinterpret_cast( s ) ); +} +virtual int getPixelAscent() const { + return m_pixelAscent; +} +virtual int getPixelDescent() const { + return m_pixelDescent; +} +virtual int getPixelHeight() const { + return m_pixelHeight; +} }; #ifdef _WIN32 @@ -73,111 +67,107 @@ class GLFontCallList: public GLFont #include #include -GLFont *glfont_create(const char* font_string) -{ - GLuint font_list_base; - XFontStruct *fontInfo; - Display *dpy = GDK_DISPLAY (); - unsigned int i, first, last, firstrow, lastrow; - int maxchars; - int firstbitmap; - - fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-8-*-*-*-*-*-*-*"); - if (fontInfo == NULL) - { - // try to load other fonts - fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*"); - - // any font will do ! - if (fontInfo == NULL) - fontInfo = XLoadQueryFont(dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); - - if (fontInfo == NULL) - ERROR_MESSAGE("couldn't create font"); - } - - first = (int)fontInfo->min_char_or_byte2; - last = (int)fontInfo->max_char_or_byte2; - firstrow = (int)fontInfo->min_byte1; - lastrow = (int)fontInfo->max_byte1; - /* - * How many chars in the charset - */ - maxchars = 256 * lastrow + last; - font_list_base = glGenLists(maxchars+1); - if (font_list_base == 0) - { - ERROR_MESSAGE( "couldn't create font" ); - } - - /* - * Get offset to first char in the charset - */ - firstbitmap = 256 * firstrow + first; - /* - * for each row of chars, call glXUseXFont to build the bitmaps. - */ - - for(i=firstrow; i<=lastrow; i++) - { - glXUseXFont(fontInfo->fid, firstbitmap, last-first+1, font_list_base+firstbitmap); - firstbitmap += 256; - } +GLFont *glfont_create( const char* font_string ){ + GLuint font_list_base; + XFontStruct *fontInfo; + Display *dpy = GDK_DISPLAY(); + unsigned int i, first, last, firstrow, lastrow; + int maxchars; + int firstbitmap; + + fontInfo = XLoadQueryFont( dpy, "-*-fixed-*-*-*-*-8-*-*-*-*-*-*-*" ); + if ( fontInfo == NULL ) { + // try to load other fonts + fontInfo = XLoadQueryFont( dpy, "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*" ); + + // any font will do ! + if ( fontInfo == NULL ) { + fontInfo = XLoadQueryFont( dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" ); + } + + if ( fontInfo == NULL ) { + ERROR_MESSAGE( "couldn't create font" ); + } + } + + first = (int)fontInfo->min_char_or_byte2; + last = (int)fontInfo->max_char_or_byte2; + firstrow = (int)fontInfo->min_byte1; + lastrow = (int)fontInfo->max_byte1; + /* + * How many chars in the charset + */ + maxchars = 256 * lastrow + last; + font_list_base = glGenLists( maxchars + 1 ); + if ( font_list_base == 0 ) { + ERROR_MESSAGE( "couldn't create font" ); + } + + /* + * Get offset to first char in the charset + */ + firstbitmap = 256 * firstrow + first; + /* + * for each row of chars, call glXUseXFont to build the bitmaps. + */ + + for ( i = firstrow; i <= lastrow; i++ ) + { + glXUseXFont( fontInfo->fid, firstbitmap, last - first + 1, font_list_base + firstbitmap ); + firstbitmap += 256; + } /* *height = fontInfo->ascent + fontInfo->descent; - *width = fontInfo->max_bounds.width; */ - return new GLFontCallList(font_list_base, fontInfo->ascent, fontInfo->descent, fontInfo->ascent + fontInfo->descent); + *width = fontInfo->max_bounds.width; */ + return new GLFontCallList( font_list_base, fontInfo->ascent, fontInfo->descent, fontInfo->ascent + fontInfo->descent ); } #elif 0 #include -GLFont *glfont_create(const char* font_string) -{ - GLuint font_list_base = glGenLists (256); - gint font_height = 0, font_ascent = 0, font_descent = 0; +GLFont *glfont_create( const char* font_string ){ + GLuint font_list_base = glGenLists( 256 ); + gint font_height = 0, font_ascent = 0, font_descent = 0; - PangoFontDescription* font_desc = pango_font_description_from_string (font_string); + PangoFontDescription* font_desc = pango_font_description_from_string( font_string ); - PangoFont* font = gdk_gl_font_use_pango_font (font_desc, 0, 256, font_list_base); + PangoFont* font = gdk_gl_font_use_pango_font( font_desc, 0, 256, font_list_base ); - if(font == 0) - { - pango_font_description_free (font_desc); - font_desc = pango_font_description_from_string ("fixed 8"); - font = gdk_gl_font_use_pango_font (font_desc, 0, 256, font_list_base); - } + if ( font == 0 ) { + pango_font_description_free( font_desc ); + font_desc = pango_font_description_from_string( "fixed 8" ); + font = gdk_gl_font_use_pango_font( font_desc, 0, 256, font_list_base ); + } - if(font == 0) - { - pango_font_description_free (font_desc); - font_desc = pango_font_description_from_string ("courier new 8"); - font = gdk_gl_font_use_pango_font (font_desc, 0, 256, font_list_base); - } + if ( font == 0 ) { + pango_font_description_free( font_desc ); + font_desc = pango_font_description_from_string( "courier new 8" ); + font = gdk_gl_font_use_pango_font( font_desc, 0, 256, font_list_base ); + } - if(font != 0) - { - PangoFontMetrics* font_metrics = pango_font_get_metrics (font, 0); + if ( font != 0 ) { + PangoFontMetrics* font_metrics = pango_font_get_metrics( font, 0 ); - font_ascent = pango_font_metrics_get_ascent (font_metrics); - font_descent = pango_font_metrics_get_descent (font_metrics); - font_height = font_ascent + font_descent; + font_ascent = pango_font_metrics_get_ascent( font_metrics ); + font_descent = pango_font_metrics_get_descent( font_metrics ); + font_height = font_ascent + font_descent; - font_ascent = PANGO_PIXELS (font_ascent); - font_descent = PANGO_PIXELS (font_descent); - font_height = PANGO_PIXELS (font_height); + font_ascent = PANGO_PIXELS( font_ascent ); + font_descent = PANGO_PIXELS( font_descent ); + font_height = PANGO_PIXELS( font_height ); - pango_font_metrics_unref (font_metrics); - } + pango_font_metrics_unref( font_metrics ); + } - pango_font_description_free (font_desc); + pango_font_description_free( font_desc ); - // fix for pango/gtkglext metrix bug - if(font_height > 256) - font_height = 16; + // fix for pango/gtkglext metrix bug + if ( font_height > 256 ) { + font_height = 16; + } - return new GLFontCallList(font_list_base, font_ascent, font_descent, font_height); + return new GLFontCallList( font_list_base, font_ascent, font_descent, font_height ); } #else @@ -186,169 +176,164 @@ GLFont *glfont_create(const char* font_string) #include #include -class GLFontInternal: public GLFont +class GLFontInternal : public GLFont { - const char *font_string; - int font_height; - int font_ascent; - int font_descent; - int y_offset_bitmap_render_pango_units; - PangoContext *ft2_context; - PangoFontMap *fontmap; - - public: - GLFontInternal(const char *_font_string): font_string(_font_string) - { - PangoFontDescription *font_desc; - PangoLayout *layout; - PangoRectangle log_rect; - int font_ascent_pango_units; - int font_descent_pango_units; - -#if !PANGO_VERSION_CHECK(1,22,0) - ft2_context = pango_ft2_get_context(72, 72); +const char *font_string; +int font_height; +int font_ascent; +int font_descent; +int y_offset_bitmap_render_pango_units; +PangoContext *ft2_context; +PangoFontMap *fontmap; + +public: +GLFontInternal( const char *_font_string ) : font_string( _font_string ){ + PangoFontDescription *font_desc; + PangoLayout *layout; + PangoRectangle log_rect; + int font_ascent_pango_units; + int font_descent_pango_units; + +#if !PANGO_VERSION_CHECK( 1,22,0 ) + ft2_context = pango_ft2_get_context( 72, 72 ); #else - fontmap = pango_ft2_font_map_new(); - pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP(fontmap), 72, 72); - ft2_context = pango_font_map_create_context(fontmap); + fontmap = pango_ft2_font_map_new(); + pango_ft2_font_map_set_resolution( PANGO_FT2_FONT_MAP( fontmap ), 72, 72 ); + ft2_context = pango_font_map_create_context( fontmap ); #endif - font_desc = pango_font_description_from_string(font_string); - //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); - pango_context_set_font_description(ft2_context, font_desc); - pango_font_description_free(font_desc); - // TODO fallback to fixed 8, courier new 8 + font_desc = pango_font_description_from_string( font_string ); + //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); + pango_context_set_font_description( ft2_context, font_desc ); + pango_font_description_free( font_desc ); + // TODO fallback to fixed 8, courier new 8 - layout = pango_layout_new(ft2_context); + layout = pango_layout_new( ft2_context ); #ifdef FONT_SIZE_WORKAROUND - pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. - pango_layout_set_text(layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1); // -1 null-terminated string. + pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. + pango_layout_set_text( layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1 ); // -1 null-terminated string. #endif -#if !PANGO_VERSION_CHECK(1,22,0) - PangoLayoutIter *iter; - iter = pango_layout_get_iter(layout); - font_ascent_pango_units = pango_layout_iter_get_baseline(iter); - pango_layout_iter_free(iter); +#if !PANGO_VERSION_CHECK( 1,22,0 ) + PangoLayoutIter *iter; + iter = pango_layout_get_iter( layout ); + font_ascent_pango_units = pango_layout_iter_get_baseline( iter ); + pango_layout_iter_free( iter ); #else - font_ascent_pango_units = pango_layout_get_baseline(layout); + font_ascent_pango_units = pango_layout_get_baseline( layout ); #endif - pango_layout_get_extents(layout, NULL, &log_rect); - g_object_unref(G_OBJECT(layout)); - font_descent_pango_units = log_rect.height - font_ascent_pango_units; + pango_layout_get_extents( layout, NULL, &log_rect ); + g_object_unref( G_OBJECT( layout ) ); + font_descent_pango_units = log_rect.height - font_ascent_pango_units; - font_ascent = PANGO_PIXELS_CEIL(font_ascent_pango_units); - font_descent = PANGO_PIXELS_CEIL(font_descent_pango_units); - font_height = font_ascent + font_descent; - y_offset_bitmap_render_pango_units = (font_ascent * PANGO_SCALE) - font_ascent_pango_units; - } + font_ascent = PANGO_PIXELS_CEIL( font_ascent_pango_units ); + font_descent = PANGO_PIXELS_CEIL( font_descent_pango_units ); + font_height = font_ascent + font_descent; + y_offset_bitmap_render_pango_units = ( font_ascent * PANGO_SCALE ) - font_ascent_pango_units; +} - virtual ~GLFontInternal() - { - g_object_unref(G_OBJECT(ft2_context)); - g_object_unref(G_OBJECT(fontmap)); - } +virtual ~GLFontInternal(){ + g_object_unref( G_OBJECT( ft2_context ) ); + g_object_unref( G_OBJECT( fontmap ) ); +} - // Renders the input text at the current location with the current color. - // The X position of the current location is used to place the left edge of the text image, - // where the text image bounds are defined as the logical extents of the line of text. - // The Y position of the current location is used to place the bottom of the text image. - // You should offset the Y position by the amount returned by gtk_glwidget_font_descent() - // if you want to place the baseline of the text image at the current Y position. - // Note: A problem with this function is that if the lower left corner of the text falls - // just a hair outside of the viewport (meaning the current raster position is invalid), - // then no text will be rendered. The solution to this is a very hacky one. You can search - // Google for "glDrawPixels clipping". - virtual void printString(const char *s) - { - // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. - - PangoLayout *layout; - PangoRectangle log_rect; - FT_Bitmap bitmap; - unsigned char *begin_bitmap_buffer; - GLfloat color[4]; - GLint previous_unpack_alignment; - GLboolean previous_blend_enabled; - GLint previous_blend_func_src; - GLint previous_blend_func_dst; - GLfloat previous_red_bias; - GLfloat previous_green_bias; - GLfloat previous_blue_bias; - GLfloat previous_alpha_scale; - - layout = pango_layout_new(ft2_context); - pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. - pango_layout_set_text(layout, s, -1); // -1 null-terminated string. - pango_layout_get_extents(layout, NULL, &log_rect); - - if (log_rect.width > 0 && log_rect.height > 0) { - bitmap.rows = font_ascent + font_descent; - bitmap.width = PANGO_PIXELS_CEIL(log_rect.width); - bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. - begin_bitmap_buffer = (unsigned char *) g_malloc(bitmap.rows * bitmap.width); - memset(begin_bitmap_buffer, 0, bitmap.rows * bitmap.width); - bitmap.buffer = begin_bitmap_buffer + (bitmap.rows - 1) * bitmap.width; // See pitch above. - bitmap.num_grays = 0xff; - bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; - pango_ft2_render_layout_subpixel(&bitmap, layout, -log_rect.x, - y_offset_bitmap_render_pango_units); - GlobalOpenGL().m_glGetFloatv(GL_CURRENT_COLOR, color); - - // Save state. I didn't see any OpenGL push/pop operations for these. - // Question: Is saving/restoring this state necessary? Being safe. - GlobalOpenGL().m_glGetIntegerv(GL_UNPACK_ALIGNMENT, &previous_unpack_alignment); - previous_blend_enabled = GlobalOpenGL().m_glIsEnabled(GL_BLEND); - GlobalOpenGL().m_glGetIntegerv(GL_BLEND_SRC, &previous_blend_func_src); - GlobalOpenGL().m_glGetIntegerv(GL_BLEND_DST, &previous_blend_func_dst); - GlobalOpenGL().m_glGetFloatv(GL_RED_BIAS, &previous_red_bias); - GlobalOpenGL().m_glGetFloatv(GL_GREEN_BIAS, &previous_green_bias); - GlobalOpenGL().m_glGetFloatv(GL_BLUE_BIAS, &previous_blue_bias); - GlobalOpenGL().m_glGetFloatv(GL_ALPHA_SCALE, &previous_alpha_scale); - - GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - GlobalOpenGL().m_glEnable(GL_BLEND); - GlobalOpenGL().m_glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, color[0]); - GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, color[1]); - GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, color[2]); - GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, color[3]); - - GlobalOpenGL().m_glDrawPixels(bitmap.width, bitmap.rows, - GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer); - g_free(begin_bitmap_buffer); - - // Restore state in reverse order of how we set it. - GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, previous_alpha_scale); - GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, previous_blue_bias); - GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, previous_green_bias); - GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, previous_red_bias); - GlobalOpenGL().m_glBlendFunc(previous_blend_func_src, previous_blend_func_dst); - if (!previous_blend_enabled) { GlobalOpenGL().m_glDisable(GL_BLEND); } - GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, previous_unpack_alignment); +// Renders the input text at the current location with the current color. +// The X position of the current location is used to place the left edge of the text image, +// where the text image bounds are defined as the logical extents of the line of text. +// The Y position of the current location is used to place the bottom of the text image. +// You should offset the Y position by the amount returned by gtk_glwidget_font_descent() +// if you want to place the baseline of the text image at the current Y position. +// Note: A problem with this function is that if the lower left corner of the text falls +// just a hair outside of the viewport (meaning the current raster position is invalid), +// then no text will be rendered. The solution to this is a very hacky one. You can search +// Google for "glDrawPixels clipping". +virtual void printString( const char *s ){ + // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. + + PangoLayout *layout; + PangoRectangle log_rect; + FT_Bitmap bitmap; + unsigned char *begin_bitmap_buffer; + GLfloat color[4]; + GLint previous_unpack_alignment; + GLboolean previous_blend_enabled; + GLint previous_blend_func_src; + GLint previous_blend_func_dst; + GLfloat previous_red_bias; + GLfloat previous_green_bias; + GLfloat previous_blue_bias; + GLfloat previous_alpha_scale; + + layout = pango_layout_new( ft2_context ); + pango_layout_set_width( layout, -1 ); // -1 no wrapping. All text on one line. + pango_layout_set_text( layout, s, -1 ); // -1 null-terminated string. + pango_layout_get_extents( layout, NULL, &log_rect ); + + if ( log_rect.width > 0 && log_rect.height > 0 ) { + bitmap.rows = font_ascent + font_descent; + bitmap.width = PANGO_PIXELS_CEIL( log_rect.width ); + bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. + begin_bitmap_buffer = (unsigned char *) g_malloc( bitmap.rows * bitmap.width ); + memset( begin_bitmap_buffer, 0, bitmap.rows * bitmap.width ); + bitmap.buffer = begin_bitmap_buffer + ( bitmap.rows - 1 ) * bitmap.width; // See pitch above. + bitmap.num_grays = 0xff; + bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; + pango_ft2_render_layout_subpixel( &bitmap, layout, -log_rect.x, + y_offset_bitmap_render_pango_units ); + GlobalOpenGL().m_glGetFloatv( GL_CURRENT_COLOR, color ); + + // Save state. I didn't see any OpenGL push/pop operations for these. + // Question: Is saving/restoring this state necessary? Being safe. + GlobalOpenGL().m_glGetIntegerv( GL_UNPACK_ALIGNMENT, &previous_unpack_alignment ); + previous_blend_enabled = GlobalOpenGL().m_glIsEnabled( GL_BLEND ); + GlobalOpenGL().m_glGetIntegerv( GL_BLEND_SRC, &previous_blend_func_src ); + GlobalOpenGL().m_glGetIntegerv( GL_BLEND_DST, &previous_blend_func_dst ); + GlobalOpenGL().m_glGetFloatv( GL_RED_BIAS, &previous_red_bias ); + GlobalOpenGL().m_glGetFloatv( GL_GREEN_BIAS, &previous_green_bias ); + GlobalOpenGL().m_glGetFloatv( GL_BLUE_BIAS, &previous_blue_bias ); + GlobalOpenGL().m_glGetFloatv( GL_ALPHA_SCALE, &previous_alpha_scale ); + + GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); + GlobalOpenGL().m_glEnable( GL_BLEND ); + GlobalOpenGL().m_glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, color[0] ); + GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, color[1] ); + GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, color[2] ); + GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, color[3] ); + + GlobalOpenGL().m_glDrawPixels( bitmap.width, bitmap.rows, + GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer ); + g_free( begin_bitmap_buffer ); + + // Restore state in reverse order of how we set it. + GlobalOpenGL().m_glPixelTransferf( GL_ALPHA_SCALE, previous_alpha_scale ); + GlobalOpenGL().m_glPixelTransferf( GL_BLUE_BIAS, previous_blue_bias ); + GlobalOpenGL().m_glPixelTransferf( GL_GREEN_BIAS, previous_green_bias ); + GlobalOpenGL().m_glPixelTransferf( GL_RED_BIAS, previous_red_bias ); + GlobalOpenGL().m_glBlendFunc( previous_blend_func_src, previous_blend_func_dst ); + if ( !previous_blend_enabled ) { + GlobalOpenGL().m_glDisable( GL_BLEND ); } - - g_object_unref(G_OBJECT(layout)); + GlobalOpenGL().m_glPixelStorei( GL_UNPACK_ALIGNMENT, previous_unpack_alignment ); } - virtual int getPixelAscent() const - { - return font_ascent; - } - virtual int getPixelDescent() const - { - return font_descent; - } - virtual int getPixelHeight() const - { - return font_height; - } + g_object_unref( G_OBJECT( layout ) ); +} + +virtual int getPixelAscent() const { + return font_ascent; +} +virtual int getPixelDescent() const { + return font_descent; +} +virtual int getPixelHeight() const { + return font_height; +} }; -GLFont *glfont_create(const char* font_string) -{ - return new GLFontInternal(font_string); +GLFont *glfont_create( const char* font_string ){ + return new GLFontInternal( font_string ); } #endif diff --git a/libs/gtkutil/glfont.h b/libs/gtkutil/glfont.h index 0d1e0000..06bfd4cd 100644 --- a/libs/gtkutil/glfont.h +++ b/libs/gtkutil/glfont.h @@ -1,42 +1,41 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_GLFONT_H) +#if !defined( INCLUDED_GTKUTIL_GLFONT_H ) #define INCLUDED_GTKUTIL_GLFONT_H typedef unsigned int GLuint; class GLFont { - public: - virtual int getPixelHeight() const = 0; - virtual int getPixelAscent() const = 0; - virtual int getPixelDescent() const = 0; - virtual void printString(const char *s) = 0; - virtual ~GLFont() - { - } +public: +virtual int getPixelHeight() const = 0; +virtual int getPixelAscent() const = 0; +virtual int getPixelDescent() const = 0; +virtual void printString( const char *s ) = 0; +virtual ~GLFont(){ +} }; -GLFont *glfont_create(const char* font_string); +GLFont *glfont_create( const char* font_string ); // release with delete #endif diff --git a/libs/gtkutil/glwidget.cpp b/libs/gtkutil/glwidget.cpp index cda5366a..746b8f0f 100644 --- a/libs/gtkutil/glwidget.cpp +++ b/libs/gtkutil/glwidget.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // OpenGL widget based on GtkGLExt @@ -32,243 +32,226 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "pointer.h" -void (*GLWidget_sharedContextCreated)() = 0; -void (*GLWidget_sharedContextDestroyed)() = 0; +void ( *GLWidget_sharedContextCreated )() = 0; +void ( *GLWidget_sharedContextDestroyed )() = 0; typedef int* attribs_t; struct config_t { - const char* name; - attribs_t attribs; + const char* name; + attribs_t attribs; }; typedef const config_t* configs_iterator; int config_rgba32[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 24, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 16, + GDK_GL_ATTRIB_LIST_NONE, }; const config_t configs[] = { - { - "colour-buffer = 32bpp, depth-buffer = none", - config_rgba32, - }, - { - "colour-buffer = 16bpp, depth-buffer = none", - config_rgba, - } + { + "colour-buffer = 32bpp, depth-buffer = none", + config_rgba32, + }, + { + "colour-buffer = 16bpp, depth-buffer = none", + config_rgba, + } }; -GdkGLConfig* glconfig_new() -{ - GdkGLConfig* glconfig = 0; - - for(configs_iterator i = configs, end = configs + 2; i != end; ++i) - { - glconfig = gdk_gl_config_new((*i).attribs); - if(glconfig != 0) - { - globalOutputStream() << "OpenGL window configuration: " << (*i).name << "\n"; - return glconfig; - } - } - - globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = none\n"; - return gdk_gl_config_new_by_mode((GdkGLConfigMode)(GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE)); +GdkGLConfig* glconfig_new(){ + GdkGLConfig* glconfig = 0; + + for ( configs_iterator i = configs, end = configs + 2; i != end; ++i ) + { + glconfig = gdk_gl_config_new( ( *i ).attribs ); + if ( glconfig != 0 ) { + globalOutputStream() << "OpenGL window configuration: " << ( *i ).name << "\n"; + return glconfig; + } + } + + globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = none\n"; + return gdk_gl_config_new_by_mode( (GdkGLConfigMode)( GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE ) ); } int config_rgba32_depth32[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 32, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 24, + GDK_GL_DEPTH_SIZE, 32, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba32_depth24[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 24, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 24, + GDK_GL_DEPTH_SIZE, 24, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba32_depth16[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 24, + GDK_GL_DEPTH_SIZE, 16, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba32_depth[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 1, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 24, + GDK_GL_DEPTH_SIZE, 1, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba_depth16[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_DEPTH_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 16, + GDK_GL_DEPTH_SIZE, 16, + GDK_GL_ATTRIB_LIST_NONE, }; int config_rgba_depth[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_DEPTH_SIZE, 1, - GDK_GL_ATTRIB_LIST_NONE, + GDK_GL_RGBA, + GDK_GL_DOUBLEBUFFER, + GDK_GL_BUFFER_SIZE, 16, + GDK_GL_DEPTH_SIZE, 1, + GDK_GL_ATTRIB_LIST_NONE, }; -const config_t configs_with_depth[] = +const config_t configs_with_depth[] = { - { - "colour-buffer = 32bpp, depth-buffer = 32bpp", - config_rgba32_depth32, - }, - { - "colour-buffer = 32bpp, depth-buffer = 24bpp", - config_rgba32_depth24, - }, - { - "colour-buffer = 32bpp, depth-buffer = 16bpp", - config_rgba32_depth16, - }, - { - "colour-buffer = 32bpp, depth-buffer = auto", - config_rgba32_depth, - }, - { - "colour-buffer = 16bpp, depth-buffer = 16bpp", - config_rgba_depth16, - }, - { - "colour-buffer = auto, depth-buffer = auto", - config_rgba_depth, - }, + { + "colour-buffer = 32bpp, depth-buffer = 32bpp", + config_rgba32_depth32, + }, + { + "colour-buffer = 32bpp, depth-buffer = 24bpp", + config_rgba32_depth24, + }, + { + "colour-buffer = 32bpp, depth-buffer = 16bpp", + config_rgba32_depth16, + }, + { + "colour-buffer = 32bpp, depth-buffer = auto", + config_rgba32_depth, + }, + { + "colour-buffer = 16bpp, depth-buffer = 16bpp", + config_rgba_depth16, + }, + { + "colour-buffer = auto, depth-buffer = auto", + config_rgba_depth, + }, }; -GdkGLConfig* glconfig_new_with_depth() -{ - GdkGLConfig* glconfig = 0; - - for(configs_iterator i = configs_with_depth, end = configs_with_depth + 6; i != end; ++i) - { - glconfig = gdk_gl_config_new((*i).attribs); - if(glconfig != 0) - { - globalOutputStream() << "OpenGL window configuration: " << (*i).name << "\n"; - return glconfig; - } - } - - globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = auto (fallback)\n"; - return gdk_gl_config_new_by_mode((GdkGLConfigMode)(GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE | GDK_GL_MODE_DEPTH)); +GdkGLConfig* glconfig_new_with_depth(){ + GdkGLConfig* glconfig = 0; + + for ( configs_iterator i = configs_with_depth, end = configs_with_depth + 6; i != end; ++i ) + { + glconfig = gdk_gl_config_new( ( *i ).attribs ); + if ( glconfig != 0 ) { + globalOutputStream() << "OpenGL window configuration: " << ( *i ).name << "\n"; + return glconfig; + } + } + + globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = auto (fallback)\n"; + return gdk_gl_config_new_by_mode( (GdkGLConfigMode)( GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE | GDK_GL_MODE_DEPTH ) ); } unsigned int g_context_count = 0; namespace { - GtkWidget* g_shared = 0; +GtkWidget* g_shared = 0; } -gint glwidget_context_created(GtkWidget* widget, gpointer data) -{ - if(++g_context_count == 1) - { - g_shared = widget; - gtk_widget_ref(g_shared); +gint glwidget_context_created( GtkWidget* widget, gpointer data ){ + if ( ++g_context_count == 1 ) { + g_shared = widget; + gtk_widget_ref( g_shared ); - glwidget_make_current(g_shared); - GlobalOpenGL().contextValid = true; + glwidget_make_current( g_shared ); + GlobalOpenGL().contextValid = true; - GLWidget_sharedContextCreated(); - } - return FALSE; + GLWidget_sharedContextCreated(); + } + return FALSE; } -gint glwidget_context_destroyed(GtkWidget* widget, gpointer data) -{ - if(--g_context_count == 0) - { - GlobalOpenGL().contextValid = false; +gint glwidget_context_destroyed( GtkWidget* widget, gpointer data ){ + if ( --g_context_count == 0 ) { + GlobalOpenGL().contextValid = false; - GLWidget_sharedContextDestroyed(); + GLWidget_sharedContextDestroyed(); - gtk_widget_unref(g_shared); - g_shared = 0; - } - return FALSE; + gtk_widget_unref( g_shared ); + g_shared = 0; + } + return FALSE; } -gboolean glwidget_enable_gl(GtkWidget* widget, GtkWidget* widget2, gpointer data) -{ - if(widget2 == 0 && !gtk_widget_is_gl_capable(widget)) - { - GdkGLConfig* glconfig = (g_object_get_data(G_OBJECT(widget), "zbuffer")) ? glconfig_new_with_depth() : glconfig_new(); - ASSERT_MESSAGE(glconfig != 0, "failed to create OpenGL config"); - - gtk_widget_set_gl_capability(widget, glconfig, g_shared != 0 ? gtk_widget_get_gl_context(g_shared) : 0, TRUE, GDK_GL_RGBA_TYPE); - - gtk_widget_realize(widget); - if(g_shared == 0) - { - g_shared = widget; - } - - // free glconfig? - } - return FALSE; +gboolean glwidget_enable_gl( GtkWidget* widget, GtkWidget* widget2, gpointer data ){ + if ( widget2 == 0 && !gtk_widget_is_gl_capable( widget ) ) { + GdkGLConfig* glconfig = ( g_object_get_data( G_OBJECT( widget ), "zbuffer" ) ) ? glconfig_new_with_depth() : glconfig_new(); + ASSERT_MESSAGE( glconfig != 0, "failed to create OpenGL config" ); + + gtk_widget_set_gl_capability( widget, glconfig, g_shared != 0 ? gtk_widget_get_gl_context( g_shared ) : 0, TRUE, GDK_GL_RGBA_TYPE ); + + gtk_widget_realize( widget ); + if ( g_shared == 0 ) { + g_shared = widget; + } + + // free glconfig? + } + return FALSE; } -GtkWidget* glwidget_new(gboolean zbuffer) -{ - GtkWidget* widget = gtk_drawing_area_new(); +GtkWidget* glwidget_new( gboolean zbuffer ){ + GtkWidget* widget = gtk_drawing_area_new(); - g_object_set_data(G_OBJECT(widget), "zbuffer", gint_to_pointer(zbuffer)); + g_object_set_data( G_OBJECT( widget ), "zbuffer", gint_to_pointer( zbuffer ) ); - g_signal_connect(G_OBJECT(widget), "hierarchy-changed", G_CALLBACK(glwidget_enable_gl), 0); + g_signal_connect( G_OBJECT( widget ), "hierarchy-changed", G_CALLBACK( glwidget_enable_gl ), 0 ); - g_signal_connect(G_OBJECT(widget), "realize", G_CALLBACK(glwidget_context_created), 0); - g_signal_connect(G_OBJECT(widget), "unrealize", G_CALLBACK(glwidget_context_destroyed), 0); + g_signal_connect( G_OBJECT( widget ), "realize", G_CALLBACK( glwidget_context_created ), 0 ); + g_signal_connect( G_OBJECT( widget ), "unrealize", G_CALLBACK( glwidget_context_destroyed ), 0 ); - return widget; + return widget; } -void glwidget_destroy_context (GtkWidget *widget) -{ +void glwidget_destroy_context( GtkWidget *widget ){ } -void glwidget_create_context (GtkWidget *widget) -{ +void glwidget_create_context( GtkWidget *widget ){ } -void glwidget_swap_buffers (GtkWidget *widget) -{ - GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget); - gdk_gl_drawable_swap_buffers (gldrawable); +void glwidget_swap_buffers( GtkWidget *widget ){ + GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable( widget ); + gdk_gl_drawable_swap_buffers( gldrawable ); } -gboolean glwidget_make_current (GtkWidget *widget) -{ - GdkGLContext *glcontext = gtk_widget_get_gl_context (widget); - GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget); - return gdk_gl_drawable_gl_begin (gldrawable, glcontext); +gboolean glwidget_make_current( GtkWidget *widget ){ + GdkGLContext *glcontext = gtk_widget_get_gl_context( widget ); + GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable( widget ); + return gdk_gl_drawable_gl_begin( gldrawable, glcontext ); } - diff --git a/libs/gtkutil/glwidget.h b/libs/gtkutil/glwidget.h index 235b0908..43e26dc7 100644 --- a/libs/gtkutil/glwidget.h +++ b/libs/gtkutil/glwidget.h @@ -1,39 +1,39 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_GLWIDGET_H) +#if !defined( INCLUDED_GTKUTIL_GLWIDGET_H ) #define INCLUDED_GTKUTIL_GLWIDGET_H typedef struct _GtkWidget GtkWidget; -typedef int gint; -typedef gint gboolean; +typedef int gint; +typedef gint gboolean; -GtkWidget* glwidget_new(gboolean zbuffer); -void glwidget_swap_buffers(GtkWidget* widget); -gboolean glwidget_make_current(GtkWidget* widget); -void glwidget_destroy_context(GtkWidget* widget); -void glwidget_create_context(GtkWidget* widget); +GtkWidget* glwidget_new( gboolean zbuffer ); +void glwidget_swap_buffers( GtkWidget* widget ); +gboolean glwidget_make_current( GtkWidget* widget ); +void glwidget_destroy_context( GtkWidget* widget ); +void glwidget_create_context( GtkWidget* widget ); -extern void (*GLWidget_sharedContextCreated)(); -extern void (*GLWidget_sharedContextDestroyed)(); +extern void ( *GLWidget_sharedContextCreated )(); +extern void ( *GLWidget_sharedContextDestroyed )(); #endif diff --git a/libs/gtkutil/idledraw.cpp b/libs/gtkutil/idledraw.cpp index 47d432ca..b50d41f2 100644 --- a/libs/gtkutil/idledraw.cpp +++ b/libs/gtkutil/idledraw.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "idledraw.h" - diff --git a/libs/gtkutil/idledraw.h b/libs/gtkutil/idledraw.h index 48081237..e74edd8c 100644 --- a/libs/gtkutil/idledraw.h +++ b/libs/gtkutil/idledraw.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_IDLEDRAW_H) +#if !defined( INCLUDED_GTKUTIL_IDLEDRAW_H ) #define INCLUDED_GTKUTIL_IDLEDRAW_H #include @@ -28,41 +28,33 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class IdleDraw { - Callback m_draw; - unsigned int m_handler; - static gboolean draw(gpointer data) - { - reinterpret_cast(data)->m_draw(); - reinterpret_cast(data)->m_handler = 0; - return FALSE; - } +Callback m_draw; +unsigned int m_handler; +static gboolean draw( gpointer data ){ + reinterpret_cast( data )->m_draw(); + reinterpret_cast( data )->m_handler = 0; + return FALSE; +} public: - IdleDraw(const Callback& draw) : m_draw(draw), m_handler(0) - { - } - ~IdleDraw() - { - if(m_handler != 0) - { - g_source_remove(m_handler); - } - } - void queueDraw() - { - if(m_handler == 0) - { - m_handler = g_idle_add(&draw, this); - } - } - typedef MemberCaller QueueDrawCaller; - - void flush() - { - if(m_handler != 0) - { - draw(this); - } - } +IdleDraw( const Callback& draw ) : m_draw( draw ), m_handler( 0 ){ +} +~IdleDraw(){ + if ( m_handler != 0 ) { + g_source_remove( m_handler ); + } +} +void queueDraw(){ + if ( m_handler == 0 ) { + m_handler = g_idle_add( &draw, this ); + } +} +typedef MemberCaller QueueDrawCaller; + +void flush(){ + if ( m_handler != 0 ) { + draw( this ); + } +} }; diff --git a/libs/gtkutil/image.cpp b/libs/gtkutil/image.cpp index 66e61d1e..4605d3f5 100644 --- a/libs/gtkutil/image.cpp +++ b/libs/gtkutil/image.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "image.h" @@ -31,66 +31,56 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA namespace { - CopiedString g_bitmapsPath; +CopiedString g_bitmapsPath; } -void BitmapsPath_set(const char* path) -{ - g_bitmapsPath = path; +void BitmapsPath_set( const char* path ){ + g_bitmapsPath = path; } -GdkPixbuf* pixbuf_new_from_file_with_mask(const char* filename) -{ - GdkPixbuf* rgb = gdk_pixbuf_new_from_file(filename, 0); - if(rgb == 0) - { - return 0; - } - else - { - GdkPixbuf* rgba = gdk_pixbuf_add_alpha(rgb, TRUE, 255, 0, 255); - gdk_pixbuf_unref(rgb); - return rgba; - } +GdkPixbuf* pixbuf_new_from_file_with_mask( const char* filename ){ + GdkPixbuf* rgb = gdk_pixbuf_new_from_file( filename, 0 ); + if ( rgb == 0 ) { + return 0; + } + else + { + GdkPixbuf* rgba = gdk_pixbuf_add_alpha( rgb, TRUE, 255, 0, 255 ); + gdk_pixbuf_unref( rgb ); + return rgba; + } } -GtkImage* image_new_from_file_with_mask(const char* filename) -{ - GdkPixbuf* rgba = pixbuf_new_from_file_with_mask(filename); - if(rgba == 0) - { - return 0; - } - else - { - GtkImage* image = GTK_IMAGE(gtk_image_new_from_pixbuf(rgba)); - gdk_pixbuf_unref(rgba); - return image; - } +GtkImage* image_new_from_file_with_mask( const char* filename ){ + GdkPixbuf* rgba = pixbuf_new_from_file_with_mask( filename ); + if ( rgba == 0 ) { + return 0; + } + else + { + GtkImage* image = GTK_IMAGE( gtk_image_new_from_pixbuf( rgba ) ); + gdk_pixbuf_unref( rgba ); + return image; + } } -GtkImage* image_new_missing() -{ - return GTK_IMAGE(gtk_image_new_from_stock(GTK_STOCK_MISSING_IMAGE, GTK_ICON_SIZE_SMALL_TOOLBAR)); -} +GtkImage* image_new_missing(){ + return GTK_IMAGE( gtk_image_new_from_stock( GTK_STOCK_MISSING_IMAGE, GTK_ICON_SIZE_SMALL_TOOLBAR ) ); +} -GtkImage* new_image(const char* filename) -{ - { - GtkImage* image = image_new_from_file_with_mask(filename); - if(image != 0) - { - return image; - } - } - - return image_new_missing(); -} - -GtkImage* new_local_image(const char* filename) -{ - StringOutputStream fullPath(256); - fullPath << g_bitmapsPath.c_str() << filename; - return new_image(fullPath.c_str()); +GtkImage* new_image( const char* filename ){ + { + GtkImage* image = image_new_from_file_with_mask( filename ); + if ( image != 0 ) { + return image; + } + } + + return image_new_missing(); } +GtkImage* new_local_image( const char* filename ){ + StringOutputStream fullPath( 256 ); + fullPath << g_bitmapsPath.c_str() << filename; + return new_image( fullPath.c_str() ); +} diff --git a/libs/gtkutil/image.h b/libs/gtkutil/image.h index bd865142..cf452559 100644 --- a/libs/gtkutil/image.h +++ b/libs/gtkutil/image.h @@ -1,36 +1,36 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_IMAGE_H) +#if !defined( INCLUDED_GTKUTIL_IMAGE_H ) #define INCLUDED_GTKUTIL_IMAGE_H -void BitmapsPath_set(const char* path); +void BitmapsPath_set( const char* path ); typedef struct _GtkImage GtkImage; typedef struct _GdkPixbuf GdkPixbuf; -GdkPixbuf* pixbuf_new_from_file_with_mask(const char* filename); -GtkImage* image_new_from_file_with_mask(const char* filename); +GdkPixbuf* pixbuf_new_from_file_with_mask( const char* filename ); +GtkImage* image_new_from_file_with_mask( const char* filename ); GtkImage* image_new_missing(); -GtkImage* new_image(const char* filename); // filename is full path to image file -GtkImage* new_local_image(const char* filename); // filename is relative to local bitmaps path +GtkImage* new_image( const char* filename ); // filename is full path to image file +GtkImage* new_local_image( const char* filename ); // filename is relative to local bitmaps path #endif diff --git a/libs/gtkutil/menu.cpp b/libs/gtkutil/menu.cpp index 86be24e7..cbb07df8 100644 --- a/libs/gtkutil/menu.cpp +++ b/libs/gtkutil/menu.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "menu.h" @@ -35,277 +35,246 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "container.h" #include "pointer.h" -void menu_add_item(GtkMenu* menu, GtkMenuItem* item) -{ - gtk_container_add(GTK_CONTAINER(menu), GTK_WIDGET(item)); +void menu_add_item( GtkMenu* menu, GtkMenuItem* item ){ + gtk_container_add( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); } -GtkMenuItem* menu_separator(GtkMenu* menu) -{ - GtkMenuItem* menu_item = GTK_MENU_ITEM(gtk_menu_item_new()); - container_add_widget(GTK_CONTAINER(menu), GTK_WIDGET(menu_item)); - gtk_widget_set_sensitive(GTK_WIDGET(menu_item), FALSE); - gtk_widget_show(GTK_WIDGET(menu_item)); - return menu_item; +GtkMenuItem* menu_separator( GtkMenu* menu ){ + GtkMenuItem* menu_item = GTK_MENU_ITEM( gtk_menu_item_new() ); + container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( menu_item ) ); + gtk_widget_set_sensitive( GTK_WIDGET( menu_item ), FALSE ); + gtk_widget_show( GTK_WIDGET( menu_item ) ); + return menu_item; } -GtkTearoffMenuItem* menu_tearoff(GtkMenu* menu) -{ - GtkTearoffMenuItem* menu_item = GTK_TEAROFF_MENU_ITEM(gtk_tearoff_menu_item_new()); - container_add_widget(GTK_CONTAINER(menu), GTK_WIDGET(menu_item)); +GtkTearoffMenuItem* menu_tearoff( GtkMenu* menu ){ + GtkTearoffMenuItem* menu_item = GTK_TEAROFF_MENU_ITEM( gtk_tearoff_menu_item_new() ); + container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( menu_item ) ); // gtk_widget_set_sensitive(GTK_WIDGET(menu_item), FALSE); -- controls whether menu is detachable - gtk_widget_show(GTK_WIDGET(menu_item)); - return menu_item; + gtk_widget_show( GTK_WIDGET( menu_item ) ); + return menu_item; } -GtkMenuItem* new_sub_menu_item_with_mnemonic(const char* mnemonic) -{ - GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_mnemonic(mnemonic)); - gtk_widget_show(GTK_WIDGET(item)); +GtkMenuItem* new_sub_menu_item_with_mnemonic( const char* mnemonic ){ + GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_mnemonic( mnemonic ) ); + gtk_widget_show( GTK_WIDGET( item ) ); - GtkWidget* sub_menu = gtk_menu_new(); - gtk_menu_item_set_submenu(item, sub_menu); + GtkWidget* sub_menu = gtk_menu_new(); + gtk_menu_item_set_submenu( item, sub_menu ); - return item; + return item; } -GtkMenu* create_sub_menu_with_mnemonic(GtkMenuShell* parent, const char* mnemonic) -{ - GtkMenuItem* item = new_sub_menu_item_with_mnemonic(mnemonic); - container_add_widget(GTK_CONTAINER(parent), GTK_WIDGET(item)); - return GTK_MENU(gtk_menu_item_get_submenu(item)); +GtkMenu* create_sub_menu_with_mnemonic( GtkMenuShell* parent, const char* mnemonic ){ + GtkMenuItem* item = new_sub_menu_item_with_mnemonic( mnemonic ); + container_add_widget( GTK_CONTAINER( parent ), GTK_WIDGET( item ) ); + return GTK_MENU( gtk_menu_item_get_submenu( item ) ); } -GtkMenu* create_sub_menu_with_mnemonic(GtkMenuBar* bar, const char* mnemonic) -{ - return create_sub_menu_with_mnemonic(GTK_MENU_SHELL(bar), mnemonic); +GtkMenu* create_sub_menu_with_mnemonic( GtkMenuBar* bar, const char* mnemonic ){ + return create_sub_menu_with_mnemonic( GTK_MENU_SHELL( bar ), mnemonic ); } -GtkMenu* create_sub_menu_with_mnemonic(GtkMenu* parent, const char* mnemonic) -{ - return create_sub_menu_with_mnemonic(GTK_MENU_SHELL(parent), mnemonic); +GtkMenu* create_sub_menu_with_mnemonic( GtkMenu* parent, const char* mnemonic ){ + return create_sub_menu_with_mnemonic( GTK_MENU_SHELL( parent ), mnemonic ); } -void activate_closure_callback(GtkWidget* widget, gpointer data) -{ - (*reinterpret_cast(data))(); +void activate_closure_callback( GtkWidget* widget, gpointer data ){ + ( *reinterpret_cast( data ) )( ); } -guint menu_item_connect_callback(GtkMenuItem* item, const Callback& callback) -{ +guint menu_item_connect_callback( GtkMenuItem* item, const Callback& callback ){ #if 1 - return g_signal_connect_swapped(G_OBJECT(item), "activate", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); + return g_signal_connect_swapped( G_OBJECT( item ), "activate", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); #else - return g_signal_connect_closure(G_OBJECT(item), "activate", create_cclosure(G_CALLBACK(activate_closure_callback), callback), FALSE); + return g_signal_connect_closure( G_OBJECT( item ), "activate", create_cclosure( G_CALLBACK( activate_closure_callback ), callback ), FALSE ); #endif } -guint check_menu_item_connect_callback(GtkCheckMenuItem* item, const Callback& callback) -{ +guint check_menu_item_connect_callback( GtkCheckMenuItem* item, const Callback& callback ){ #if 1 - guint handler = g_signal_connect_swapped(G_OBJECT(item), "toggled", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); + guint handler = g_signal_connect_swapped( G_OBJECT( item ), "toggled", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); #else - guint handler = g_signal_connect_closure(G_OBJECT(item), "toggled", create_cclosure(G_CALLBACK(activate_closure_callback), callback), TRUE); + guint handler = g_signal_connect_closure( G_OBJECT( item ), "toggled", create_cclosure( G_CALLBACK( activate_closure_callback ), callback ), TRUE ); #endif - g_object_set_data(G_OBJECT(item), "handler", gint_to_pointer(handler)); - return handler; + g_object_set_data( G_OBJECT( item ), "handler", gint_to_pointer( handler ) ); + return handler; } -GtkMenuItem* new_menu_item_with_mnemonic(const char *mnemonic, const Callback& callback) -{ - GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_mnemonic(mnemonic)); - gtk_widget_show(GTK_WIDGET(item)); - menu_item_connect_callback(item, callback); - return item; +GtkMenuItem* new_menu_item_with_mnemonic( const char *mnemonic, const Callback& callback ){ + GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_mnemonic( mnemonic ) ); + gtk_widget_show( GTK_WIDGET( item ) ); + menu_item_connect_callback( item, callback ); + return item; } -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char *mnemonic, const Callback& callback) -{ - GtkMenuItem* item = new_menu_item_with_mnemonic(mnemonic, callback); - container_add_widget(GTK_CONTAINER(menu), GTK_WIDGET(item)); - return item; +GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char *mnemonic, const Callback& callback ){ + GtkMenuItem* item = new_menu_item_with_mnemonic( mnemonic, callback ); + container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); + return item; } -GtkCheckMenuItem* new_check_menu_item_with_mnemonic(const char* mnemonic, const Callback& callback) -{ - GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(gtk_check_menu_item_new_with_mnemonic(mnemonic)); - gtk_widget_show(GTK_WIDGET(item)); - check_menu_item_connect_callback(item, callback); - return item; +GtkCheckMenuItem* new_check_menu_item_with_mnemonic( const char* mnemonic, const Callback& callback ){ + GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM( gtk_check_menu_item_new_with_mnemonic( mnemonic ) ); + gtk_widget_show( GTK_WIDGET( item ) ); + check_menu_item_connect_callback( item, callback ); + return item; } -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Callback& callback) -{ - GtkCheckMenuItem* item = new_check_menu_item_with_mnemonic(mnemonic, callback); - container_add_widget(GTK_CONTAINER(menu), GTK_WIDGET(item)); - return item; +GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ){ + GtkCheckMenuItem* item = new_check_menu_item_with_mnemonic( mnemonic, callback ); + container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); + return item; } -GtkRadioMenuItem* new_radio_menu_item_with_mnemonic(GSList** group, const char* mnemonic, const Callback& callback) -{ - GtkRadioMenuItem* item = GTK_RADIO_MENU_ITEM(gtk_radio_menu_item_new_with_mnemonic(*group, mnemonic)); - if(*group == 0) - { - gtk_check_menu_item_set_state(GTK_CHECK_MENU_ITEM(item), TRUE); - } - *group = gtk_radio_menu_item_group(item); - gtk_widget_show(GTK_WIDGET(item)); - check_menu_item_connect_callback(GTK_CHECK_MENU_ITEM(item), callback); - return item; +GtkRadioMenuItem* new_radio_menu_item_with_mnemonic( GSList** group, const char* mnemonic, const Callback& callback ){ + GtkRadioMenuItem* item = GTK_RADIO_MENU_ITEM( gtk_radio_menu_item_new_with_mnemonic( *group, mnemonic ) ); + if ( *group == 0 ) { + gtk_check_menu_item_set_state( GTK_CHECK_MENU_ITEM( item ), TRUE ); + } + *group = gtk_radio_menu_item_group( item ); + gtk_widget_show( GTK_WIDGET( item ) ); + check_menu_item_connect_callback( GTK_CHECK_MENU_ITEM( item ), callback ); + return item; } -GtkRadioMenuItem* create_radio_menu_item_with_mnemonic(GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback) -{ - GtkRadioMenuItem* item = new_radio_menu_item_with_mnemonic(group, mnemonic, callback); - container_add_widget(GTK_CONTAINER(menu), GTK_WIDGET(item)); - return item; +GtkRadioMenuItem* create_radio_menu_item_with_mnemonic( GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback ){ + GtkRadioMenuItem* item = new_radio_menu_item_with_mnemonic( group, mnemonic, callback ); + container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); + return item; } -void check_menu_item_set_active_no_signal(GtkCheckMenuItem* item, gboolean active) -{ - guint handler_id = gpointer_to_int(g_object_get_data(G_OBJECT(item), "handler")); - g_signal_handler_block(G_OBJECT(item), handler_id); - gtk_check_menu_item_set_active(item, active); - g_signal_handler_unblock(G_OBJECT(item), handler_id); +void check_menu_item_set_active_no_signal( GtkCheckMenuItem* item, gboolean active ){ + guint handler_id = gpointer_to_int( g_object_get_data( G_OBJECT( item ), "handler" ) ); + g_signal_handler_block( G_OBJECT( item ), handler_id ); + gtk_check_menu_item_set_active( item, active ); + g_signal_handler_unblock( G_OBJECT( item ), handler_id ); } -void radio_menu_item_set_active_no_signal(GtkRadioMenuItem* item, gboolean active) -{ - { - for(GSList* l = gtk_radio_menu_item_get_group(item); l != 0; l = g_slist_next(l)) - { - g_signal_handler_block(G_OBJECT(l->data), gpointer_to_int(g_object_get_data(G_OBJECT(l->data), "handler"))); - } - } - gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), active); - { - for(GSList* l = gtk_radio_menu_item_get_group(item); l != 0; l = g_slist_next(l)) - { - g_signal_handler_unblock(G_OBJECT(l->data), gpointer_to_int(g_object_get_data(G_OBJECT(l->data), "handler"))); - } - } +void radio_menu_item_set_active_no_signal( GtkRadioMenuItem* item, gboolean active ){ + { + for ( GSList* l = gtk_radio_menu_item_get_group( item ); l != 0; l = g_slist_next( l ) ) + { + g_signal_handler_block( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); + } + } + gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( item ), active ); + { + for ( GSList* l = gtk_radio_menu_item_get_group( item ); l != 0; l = g_slist_next( l ) ) + { + g_signal_handler_unblock( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); + } + } } -void menu_item_set_accelerator(GtkMenuItem* item, GClosure* closure) -{ - GtkAccelLabel* accel_label = GTK_ACCEL_LABEL(gtk_bin_get_child(GTK_BIN(item))); - gtk_accel_label_set_accel_closure(accel_label, closure); +void menu_item_set_accelerator( GtkMenuItem* item, GClosure* closure ){ + GtkAccelLabel* accel_label = GTK_ACCEL_LABEL( gtk_bin_get_child( GTK_BIN( item ) ) ); + gtk_accel_label_set_accel_closure( accel_label, closure ); } -void accelerator_name(const Accelerator& accelerator, GString* gstring) -{ - gboolean had_mod = FALSE; - if (accelerator.modifiers & GDK_SHIFT_MASK) - { - g_string_append (gstring, "Shift"); - had_mod = TRUE; - } - if (accelerator.modifiers & GDK_CONTROL_MASK) - { - if (had_mod) - g_string_append (gstring, "+"); - g_string_append (gstring, "Ctrl"); - had_mod = TRUE; - } - if (accelerator.modifiers & GDK_MOD1_MASK) - { - if (had_mod) - g_string_append (gstring, "+"); - g_string_append (gstring, "Alt"); - had_mod = TRUE; - } - - if (had_mod) - g_string_append (gstring, "+"); - if (accelerator.key < 0x80 || (accelerator.key > 0x80 && accelerator.key <= 0xff)) - { - switch (accelerator.key) - { - case ' ': - g_string_append (gstring, "Space"); - break; - case '\\': - g_string_append (gstring, "Backslash"); - break; - default: - g_string_append_c (gstring, gchar(toupper(accelerator.key))); - break; - } - } - else - { - gchar *tmp; - - tmp = gtk_accelerator_name (accelerator.key, (GdkModifierType)0); - if (tmp[0] != 0 && tmp[1] == 0) - tmp[0] = gchar(toupper(tmp[0])); - g_string_append (gstring, tmp); - g_free (tmp); - } +void accelerator_name( const Accelerator& accelerator, GString* gstring ){ + gboolean had_mod = FALSE; + if ( accelerator.modifiers & GDK_SHIFT_MASK ) { + g_string_append( gstring, "Shift" ); + had_mod = TRUE; + } + if ( accelerator.modifiers & GDK_CONTROL_MASK ) { + if ( had_mod ) { + g_string_append( gstring, "+" ); + } + g_string_append( gstring, "Ctrl" ); + had_mod = TRUE; + } + if ( accelerator.modifiers & GDK_MOD1_MASK ) { + if ( had_mod ) { + g_string_append( gstring, "+" ); + } + g_string_append( gstring, "Alt" ); + had_mod = TRUE; + } + + if ( had_mod ) { + g_string_append( gstring, "+" ); + } + if ( accelerator.key < 0x80 || ( accelerator.key > 0x80 && accelerator.key <= 0xff ) ) { + switch ( accelerator.key ) + { + case ' ': + g_string_append( gstring, "Space" ); + break; + case '\\': + g_string_append( gstring, "Backslash" ); + break; + default: + g_string_append_c( gstring, gchar( toupper( accelerator.key ) ) ); + break; + } + } + else + { + gchar *tmp; + + tmp = gtk_accelerator_name( accelerator.key, (GdkModifierType)0 ); + if ( tmp[0] != 0 && tmp[1] == 0 ) { + tmp[0] = gchar( toupper( tmp[0] ) ); + } + g_string_append( gstring, tmp ); + g_free( tmp ); + } } -void menu_item_set_accelerator(GtkMenuItem* item, Accelerator accelerator) -{ - GtkAccelLabel* accel_label = GTK_ACCEL_LABEL(gtk_bin_get_child(GTK_BIN(item))); +void menu_item_set_accelerator( GtkMenuItem* item, Accelerator accelerator ){ + GtkAccelLabel* accel_label = GTK_ACCEL_LABEL( gtk_bin_get_child( GTK_BIN( item ) ) ); - g_free (accel_label->accel_string); - accel_label->accel_string = 0; + g_free( accel_label->accel_string ); + accel_label->accel_string = 0; - GString* gstring = g_string_new (accel_label->accel_string); - g_string_append (gstring, " "); + GString* gstring = g_string_new( accel_label->accel_string ); + g_string_append( gstring, " " ); - accelerator_name(accelerator, gstring); + accelerator_name( accelerator, gstring ); - g_free (accel_label->accel_string); - accel_label->accel_string = gstring->str; - g_string_free (gstring, FALSE); + g_free( accel_label->accel_string ); + accel_label->accel_string = gstring->str; + g_string_free( gstring, FALSE ); - if (!accel_label->accel_string) - accel_label->accel_string = g_strdup (""); + if ( !accel_label->accel_string ) { + accel_label->accel_string = g_strdup( "" ); + } - gtk_widget_queue_resize (GTK_WIDGET (accel_label)); + gtk_widget_queue_resize( GTK_WIDGET( accel_label ) ); } -void menu_item_add_accelerator(GtkMenuItem* item, Accelerator accelerator) -{ - if(accelerator.key != 0) - { - GClosure* closure = global_accel_group_find(accelerator); - if(closure != 0) - { - menu_item_set_accelerator(item, closure); - } - else - { - menu_item_set_accelerator(item, accelerator); - } - } +void menu_item_add_accelerator( GtkMenuItem* item, Accelerator accelerator ){ + if ( accelerator.key != 0 ) { + GClosure* closure = global_accel_group_find( accelerator ); + if ( closure != 0 ) { + menu_item_set_accelerator( item, closure ); + } + else + { + menu_item_set_accelerator( item, accelerator ); + } + } } -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Command& command) -{ - GtkMenuItem* item = create_menu_item_with_mnemonic(menu, mnemonic, command.m_callback); - menu_item_add_accelerator(item, command.m_accelerator); - return item; +GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Command& command ){ + GtkMenuItem* item = create_menu_item_with_mnemonic( menu, mnemonic, command.m_callback ); + menu_item_add_accelerator( item, command.m_accelerator ); + return item; } -void check_menu_item_set_active_callback(GtkCheckMenuItem& item, bool enabled) -{ - check_menu_item_set_active_no_signal(&item, enabled); +void check_menu_item_set_active_callback( GtkCheckMenuItem& item, bool enabled ){ + check_menu_item_set_active_no_signal( &item, enabled ); } typedef ReferenceCaller1 CheckMenuItemSetActiveCaller; -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Toggle& toggle) -{ - GtkCheckMenuItem* item = create_check_menu_item_with_mnemonic(menu, mnemonic, toggle.m_command.m_callback); - menu_item_add_accelerator(GTK_MENU_ITEM(item), toggle.m_command.m_accelerator); - toggle.m_exportCallback(CheckMenuItemSetActiveCaller(*item)); - return item; +GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Toggle& toggle ){ + GtkCheckMenuItem* item = create_check_menu_item_with_mnemonic( menu, mnemonic, toggle.m_command.m_callback ); + menu_item_add_accelerator( GTK_MENU_ITEM( item ), toggle.m_command.m_accelerator ); + toggle.m_exportCallback( CheckMenuItemSetActiveCaller( *item ) ); + return item; } - - - - diff --git a/libs/gtkutil/menu.h b/libs/gtkutil/menu.h index a394d823..a64291d4 100644 --- a/libs/gtkutil/menu.h +++ b/libs/gtkutil/menu.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_MENU_H) +#if !defined( INCLUDED_GTKUTIL_MENU_H ) #define INCLUDED_GTKUTIL_MENU_H #include "generic/callbackfwd.h" @@ -34,25 +34,25 @@ typedef struct _GtkCheckMenuItem GtkCheckMenuItem; typedef struct _GtkRadioMenuItem GtkRadioMenuItem; typedef struct _GtkTearoffMenuItem GtkTearoffMenuItem; -void menu_add_item(GtkMenu* menu, GtkMenuItem* item); -GtkMenuItem* menu_separator(GtkMenu* menu); -GtkTearoffMenuItem* menu_tearoff(GtkMenu* menu); -GtkMenuItem* new_sub_menu_item_with_mnemonic(const char* mnemonic); -GtkMenu* create_sub_menu_with_mnemonic(GtkMenuBar* bar, const char* mnemonic); -GtkMenu* create_sub_menu_with_mnemonic(GtkMenu* parent, const char* mnemonic); -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Callback& callback); -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Callback& callback); -GtkRadioMenuItem* create_radio_menu_item_with_mnemonic(GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback); +void menu_add_item( GtkMenu* menu, GtkMenuItem* item ); +GtkMenuItem* menu_separator( GtkMenu* menu ); +GtkTearoffMenuItem* menu_tearoff( GtkMenu* menu ); +GtkMenuItem* new_sub_menu_item_with_mnemonic( const char* mnemonic ); +GtkMenu* create_sub_menu_with_mnemonic( GtkMenuBar* bar, const char* mnemonic ); +GtkMenu* create_sub_menu_with_mnemonic( GtkMenu* parent, const char* mnemonic ); +GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ); +GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ); +GtkRadioMenuItem* create_radio_menu_item_with_mnemonic( GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback ); class Command; -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Command& command); +GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Command& command ); class Toggle; -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const Toggle& toggle); +GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Toggle& toggle ); typedef struct _GtkCheckMenuItem GtkCheckMenuItem; -void check_menu_item_set_active_no_signal(GtkCheckMenuItem* item, gboolean active); +void check_menu_item_set_active_no_signal( GtkCheckMenuItem* item, gboolean active ); typedef struct _GtkRadioMenuItem GtkRadioMenuItem; -void radio_menu_item_set_active_no_signal(GtkRadioMenuItem* item, gboolean active); +void radio_menu_item_set_active_no_signal( GtkRadioMenuItem* item, gboolean active ); #endif diff --git a/libs/gtkutil/messagebox.cpp b/libs/gtkutil/messagebox.cpp index 4c430ed3..8f9fb7fa 100644 --- a/libs/gtkutil/messagebox.cpp +++ b/libs/gtkutil/messagebox.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "messagebox.h" @@ -35,179 +35,170 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "dialog.h" #include "widget.h" -GtkWidget* create_padding(int width, int height) -{ - GtkWidget* widget = gtk_alignment_new(0.0, 0.0, 0.0, 0.0); - gtk_widget_show(widget); - gtk_widget_set_size_request(widget, width, height); - return widget; +GtkWidget* create_padding( int width, int height ){ + GtkWidget* widget = gtk_alignment_new( 0.0, 0.0, 0.0, 0.0 ); + gtk_widget_show( widget ); + gtk_widget_set_size_request( widget, width, height ); + return widget; } -const char* messagebox_stock_icon(EMessageBoxIcon type) -{ - switch(type) - { - default: - case eMB_ICONDEFAULT: - return GTK_STOCK_DIALOG_INFO; - case eMB_ICONERROR: - return GTK_STOCK_DIALOG_ERROR; - case eMB_ICONWARNING: - return GTK_STOCK_DIALOG_WARNING; - case eMB_ICONQUESTION: - return GTK_STOCK_DIALOG_QUESTION; - case eMB_ICONASTERISK: - return GTK_STOCK_DIALOG_INFO; - } +const char* messagebox_stock_icon( EMessageBoxIcon type ){ + switch ( type ) + { + default: + case eMB_ICONDEFAULT: + return GTK_STOCK_DIALOG_INFO; + case eMB_ICONERROR: + return GTK_STOCK_DIALOG_ERROR; + case eMB_ICONWARNING: + return GTK_STOCK_DIALOG_WARNING; + case eMB_ICONQUESTION: + return GTK_STOCK_DIALOG_QUESTION; + case eMB_ICONASTERISK: + return GTK_STOCK_DIALOG_INFO; + } } -EMessageBoxReturn gtk_MessageBox (GtkWidget *parent, const char* text, const char* title, EMessageBoxType type, EMessageBoxIcon icon) -{ - ModalDialog dialog; - ModalDialogButton ok_button(dialog, eIDOK); - ModalDialogButton cancel_button(dialog, eIDCANCEL); - ModalDialogButton yes_button(dialog, eIDYES); - ModalDialogButton no_button(dialog, eIDNO); - - GtkWindow* parentWindow = parent != 0 ? GTK_WINDOW(parent) : 0; - - GtkWindow* window = create_fixedsize_modal_dialog_window(parentWindow, title, dialog, 400, 100); - - if(parentWindow != 0) - { - //g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(floating_window_delete_present), parent); - gtk_window_deiconify(parentWindow); - } - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - GtkVBox* vbox = create_dialog_vbox(8, 8); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - - - GtkHBox* hboxDummy = create_dialog_hbox(0, 0); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hboxDummy), FALSE, FALSE, 0); - - gtk_box_pack_start(GTK_BOX(hboxDummy), create_padding(0, 50), FALSE, FALSE, 0); // HACK to force minimum height - - GtkHBox* iconBox = create_dialog_hbox(16, 0); - gtk_box_pack_start(GTK_BOX(hboxDummy), GTK_WIDGET(iconBox), FALSE, FALSE, 0); - - GtkImage* image = GTK_IMAGE(gtk_image_new_from_stock(messagebox_stock_icon(icon), GTK_ICON_SIZE_DIALOG)); - gtk_widget_show(GTK_WIDGET(image)); - gtk_box_pack_start(GTK_BOX(iconBox), GTK_WIDGET(image), FALSE, FALSE, 0); - - GtkLabel* label = GTK_LABEL(gtk_label_new(text)); - gtk_widget_show(GTK_WIDGET(label)); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); - gtk_label_set_line_wrap(label, TRUE); - gtk_box_pack_start(GTK_BOX(iconBox), GTK_WIDGET(label), TRUE, TRUE, 0); - - - GtkVBox* vboxDummy = create_dialog_vbox(0, 0); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(vboxDummy), FALSE, FALSE, 0); - - GtkAlignment* alignment = GTK_ALIGNMENT(gtk_alignment_new(0.5, 0.0, 0.0, 0.0)); - gtk_widget_show(GTK_WIDGET(alignment)); - gtk_box_pack_start(GTK_BOX(vboxDummy), GTK_WIDGET(alignment), FALSE, FALSE, 0); - - GtkHBox* hbox = create_dialog_hbox(8, 0); - gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(hbox)); - - gtk_box_pack_start(GTK_BOX(vboxDummy), create_padding(400, 0), FALSE, FALSE, 0); // HACK to force minimum width - - - if (type == eMB_OK) - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_show(GTK_WIDGET(button)); - - dialog.ret = eIDOK; - } - else if (type == eMB_OKCANCEL) - { - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_show(GTK_WIDGET(button)); - } - - { - GtkButton* button = create_modal_dialog_button("OK", cancel_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - gtk_widget_show(GTK_WIDGET(button)); - } - - dialog.ret = eIDCANCEL; - } - else if (type == eMB_YESNOCANCEL) - { - { - GtkButton* button = create_modal_dialog_button("Yes", yes_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_show(GTK_WIDGET(button)); - } - - { - GtkButton* button = create_modal_dialog_button("No", no_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_show(GTK_WIDGET(button)); - } - { - GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_show(GTK_WIDGET(button)); - } - - dialog.ret = eIDCANCEL; - } - else if (type == eMB_NOYES) - { - { - GtkButton* button = create_modal_dialog_button("No", no_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_show(GTK_WIDGET(button)); - } - { - GtkButton* button = create_modal_dialog_button("Yes", yes_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_show(GTK_WIDGET(button)); - } - - dialog.ret = eIDNO; - } - else /* if (type == eMB_YESNO) */ - { - { - GtkButton* button = create_modal_dialog_button("Yes", yes_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_show(GTK_WIDGET(button)); - } - - { - GtkButton* button = create_modal_dialog_button("No", no_button); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), TRUE, FALSE, 0); - gtk_widget_show(GTK_WIDGET(button)); - } - dialog.ret = eIDNO; - } - - modal_dialog_show(window, dialog); - - gtk_widget_destroy(GTK_WIDGET(window)); - - return dialog.ret; +EMessageBoxReturn gtk_MessageBox( GtkWidget *parent, const char* text, const char* title, EMessageBoxType type, EMessageBoxIcon icon ){ + ModalDialog dialog; + ModalDialogButton ok_button( dialog, eIDOK ); + ModalDialogButton cancel_button( dialog, eIDCANCEL ); + ModalDialogButton yes_button( dialog, eIDYES ); + ModalDialogButton no_button( dialog, eIDNO ); + + GtkWindow* parentWindow = parent != 0 ? GTK_WINDOW( parent ) : 0; + + GtkWindow* window = create_fixedsize_modal_dialog_window( parentWindow, title, dialog, 400, 100 ); + + if ( parentWindow != 0 ) { + //g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(floating_window_delete_present), parent); + gtk_window_deiconify( parentWindow ); + } + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group( window, accel ); + + GtkVBox* vbox = create_dialog_vbox( 8, 8 ); + gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox ) ); + + + GtkHBox* hboxDummy = create_dialog_hbox( 0, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hboxDummy ), FALSE, FALSE, 0 ); + + gtk_box_pack_start( GTK_BOX( hboxDummy ), create_padding( 0, 50 ), FALSE, FALSE, 0 ); // HACK to force minimum height + + GtkHBox* iconBox = create_dialog_hbox( 16, 0 ); + gtk_box_pack_start( GTK_BOX( hboxDummy ), GTK_WIDGET( iconBox ), FALSE, FALSE, 0 ); + + GtkImage* image = GTK_IMAGE( gtk_image_new_from_stock( messagebox_stock_icon( icon ), GTK_ICON_SIZE_DIALOG ) ); + gtk_widget_show( GTK_WIDGET( image ) ); + gtk_box_pack_start( GTK_BOX( iconBox ), GTK_WIDGET( image ), FALSE, FALSE, 0 ); + + GtkLabel* label = GTK_LABEL( gtk_label_new( text ) ); + gtk_widget_show( GTK_WIDGET( label ) ); + gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); + gtk_label_set_justify( label, GTK_JUSTIFY_LEFT ); + gtk_label_set_line_wrap( label, TRUE ); + gtk_box_pack_start( GTK_BOX( iconBox ), GTK_WIDGET( label ), TRUE, TRUE, 0 ); + + + GtkVBox* vboxDummy = create_dialog_vbox( 0, 0 ); + gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( vboxDummy ), FALSE, FALSE, 0 ); + + GtkAlignment* alignment = GTK_ALIGNMENT( gtk_alignment_new( 0.5, 0.0, 0.0, 0.0 ) ); + gtk_widget_show( GTK_WIDGET( alignment ) ); + gtk_box_pack_start( GTK_BOX( vboxDummy ), GTK_WIDGET( alignment ), FALSE, FALSE, 0 ); + + GtkHBox* hbox = create_dialog_hbox( 8, 0 ); + gtk_container_add( GTK_CONTAINER( alignment ), GTK_WIDGET( hbox ) ); + + gtk_box_pack_start( GTK_BOX( vboxDummy ), create_padding( 400, 0 ), FALSE, FALSE, 0 ); // HACK to force minimum width + + + if ( type == eMB_OK ) { + GtkButton* button = create_modal_dialog_button( "OK", ok_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 ); + gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 ); + widget_make_default( GTK_WIDGET( button ) ); + gtk_widget_show( GTK_WIDGET( button ) ); + + dialog.ret = eIDOK; + } + else if ( type == eMB_OKCANCEL ) { + { + GtkButton* button = create_modal_dialog_button( "OK", ok_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 ); + widget_make_default( GTK_WIDGET( button ) ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + { + GtkButton* button = create_modal_dialog_button( "OK", cancel_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + dialog.ret = eIDCANCEL; + } + else if ( type == eMB_YESNOCANCEL ) { + { + GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + widget_make_default( GTK_WIDGET( button ) ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + { + GtkButton* button = create_modal_dialog_button( "No", no_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + { + GtkButton* button = create_modal_dialog_button( "Cancel", cancel_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + dialog.ret = eIDCANCEL; + } + else if ( type == eMB_NOYES ) { + { + GtkButton* button = create_modal_dialog_button( "No", no_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + widget_make_default( GTK_WIDGET( button ) ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + { + GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + dialog.ret = eIDNO; + } + else /* if (type == eMB_YESNO) */ + { + { + GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + widget_make_default( GTK_WIDGET( button ) ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + + { + GtkButton* button = create_modal_dialog_button( "No", no_button ); + gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); + gtk_widget_show( GTK_WIDGET( button ) ); + } + dialog.ret = eIDNO; + } + + modal_dialog_show( window, dialog ); + + gtk_widget_destroy( GTK_WIDGET( window ) ); + + return dialog.ret; } - diff --git a/libs/gtkutil/messagebox.h b/libs/gtkutil/messagebox.h index 8806a3bd..8bdc0ba2 100644 --- a/libs/gtkutil/messagebox.h +++ b/libs/gtkutil/messagebox.h @@ -1,31 +1,31 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_MESSAGEBOX_H) +#if !defined( INCLUDED_GTKUTIL_MESSAGEBOX_H ) #define INCLUDED_GTKUTIL_MESSAGEBOX_H #include "qerplugin.h" typedef struct _GtkWidget GtkWidget; /// \brief Shows a modal message-box. -EMessageBoxReturn gtk_MessageBox(GtkWidget *parent, const char* text, const char* title = "NetRadiant", EMessageBoxType type = eMB_OK, EMessageBoxIcon icon = eMB_ICONDEFAULT); +EMessageBoxReturn gtk_MessageBox( GtkWidget *parent, const char* text, const char* title = "NetRadiant", EMessageBoxType type = eMB_OK, EMessageBoxIcon icon = eMB_ICONDEFAULT ); #endif diff --git a/libs/gtkutil/nonmodal.cpp b/libs/gtkutil/nonmodal.cpp index 6252e2dd..edca0b73 100644 --- a/libs/gtkutil/nonmodal.cpp +++ b/libs/gtkutil/nonmodal.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "nonmodal.h" - diff --git a/libs/gtkutil/nonmodal.h b/libs/gtkutil/nonmodal.h index eed4be37..864779bd 100644 --- a/libs/gtkutil/nonmodal.h +++ b/libs/gtkutil/nonmodal.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_NONMODAL_H) +#if !defined( INCLUDED_GTKUTIL_NONMODAL_H ) #define INCLUDED_GTKUTIL_NONMODAL_H #include @@ -35,151 +35,129 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA typedef struct _GtkEntry GtkEntry; -inline gboolean escape_clear_focus_widget(GtkWidget* widget, GdkEventKey* event, gpointer data) -{ - if(event->keyval == GDK_Escape) - { - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(widget))), NULL); - return TRUE; - } - return FALSE; +inline gboolean escape_clear_focus_widget( GtkWidget* widget, GdkEventKey* event, gpointer data ){ + if ( event->keyval == GDK_Escape ) { + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( widget ) ) ), NULL ); + return TRUE; + } + return FALSE; } -inline void widget_connect_escape_clear_focus_widget(GtkWidget* widget) -{ - g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(escape_clear_focus_widget), 0); +inline void widget_connect_escape_clear_focus_widget( GtkWidget* widget ){ + g_signal_connect( G_OBJECT( widget ), "key_press_event", G_CALLBACK( escape_clear_focus_widget ), 0 ); } class NonModalEntry { - bool m_editing; - Callback m_apply; - Callback m_cancel; - - static gboolean focus_in(GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self) - { - self->m_editing = false; - return FALSE; - } - - static gboolean focus_out(GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self) - { - if(self->m_editing && GTK_WIDGET_VISIBLE(entry)) - { - self->m_apply(); - } - self->m_editing = false; - return FALSE; - } - - static gboolean changed(GtkEntry* entry, NonModalEntry* self) - { - self->m_editing = true; - return FALSE; - } - - static gboolean enter(GtkEntry* entry, GdkEventKey* event, NonModalEntry* self) - { - if(event->keyval == GDK_Return) - { - self->m_apply(); - self->m_editing = false; - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(entry))), NULL); - return TRUE; - } - return FALSE; - } - - static gboolean escape(GtkEntry* entry, GdkEventKey* event, NonModalEntry* self) - { - if(event->keyval == GDK_Escape) - { - self->m_cancel(); - self->m_editing = false; - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(entry))), NULL); - return TRUE; - } - return FALSE; - } +bool m_editing; +Callback m_apply; +Callback m_cancel; + +static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ + self->m_editing = false; + return FALSE; +} + +static gboolean focus_out( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ + if ( self->m_editing && GTK_WIDGET_VISIBLE( entry ) ) { + self->m_apply(); + } + self->m_editing = false; + return FALSE; +} + +static gboolean changed( GtkEntry* entry, NonModalEntry* self ){ + self->m_editing = true; + return FALSE; +} + +static gboolean enter( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ + if ( event->keyval == GDK_Return ) { + self->m_apply(); + self->m_editing = false; + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); + return TRUE; + } + return FALSE; +} + +static gboolean escape( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ + if ( event->keyval == GDK_Escape ) { + self->m_cancel(); + self->m_editing = false; + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); + return TRUE; + } + return FALSE; +} public: - NonModalEntry(const Callback& apply, const Callback& cancel) : m_editing(false), m_apply(apply), m_cancel(cancel) - { - } - void connect(GtkEntry* entry) - { - g_signal_connect(G_OBJECT(entry), "focus_in_event", G_CALLBACK(focus_in), this); - g_signal_connect(G_OBJECT(entry), "focus_out_event", G_CALLBACK(focus_out), this); - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(enter), this); - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(escape), this); - g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(changed), this); - } +NonModalEntry( const Callback& apply, const Callback& cancel ) : m_editing( false ), m_apply( apply ), m_cancel( cancel ){ +} +void connect( GtkEntry* entry ){ + g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); + g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( focus_out ), this ); + g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( enter ), this ); + g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( escape ), this ); + g_signal_connect( G_OBJECT( entry ), "changed", G_CALLBACK( changed ), this ); +} }; class NonModalSpinner { - Callback m_apply; - Callback m_cancel; - - static gboolean changed(GtkSpinButton* spin, NonModalSpinner* self) - { - self->m_apply(); - return FALSE; - } - - static gboolean enter(GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self) - { - if(event->keyval == GDK_Return) - { - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(spin))), NULL); - return TRUE; - } - return FALSE; - } - - static gboolean escape(GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self) - { - if(event->keyval == GDK_Escape) - { - self->m_cancel(); - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(spin))), NULL); - return TRUE; - } - return FALSE; - } +Callback m_apply; +Callback m_cancel; + +static gboolean changed( GtkSpinButton* spin, NonModalSpinner* self ){ + self->m_apply(); + return FALSE; +} + +static gboolean enter( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ + if ( event->keyval == GDK_Return ) { + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); + return TRUE; + } + return FALSE; +} + +static gboolean escape( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ + if ( event->keyval == GDK_Escape ) { + self->m_cancel(); + gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); + return TRUE; + } + return FALSE; +} public: - NonModalSpinner(const Callback& apply, const Callback& cancel) : m_apply(apply), m_cancel(cancel) - { - } - void connect(GtkSpinButton* spin) - { - guint handler = g_signal_connect(G_OBJECT(gtk_spin_button_get_adjustment(spin)), "value_changed", G_CALLBACK(changed), this); - g_object_set_data(G_OBJECT(spin), "handler", gint_to_pointer(handler)); - g_signal_connect(G_OBJECT(spin), "key_press_event", G_CALLBACK(enter), this); - g_signal_connect(G_OBJECT(spin), "key_press_event", G_CALLBACK(escape), this); - } +NonModalSpinner( const Callback& apply, const Callback& cancel ) : m_apply( apply ), m_cancel( cancel ){ +} +void connect( GtkSpinButton* spin ){ + guint handler = g_signal_connect( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), "value_changed", G_CALLBACK( changed ), this ); + g_object_set_data( G_OBJECT( spin ), "handler", gint_to_pointer( handler ) ); + g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( enter ), this ); + g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( escape ), this ); +} }; - + class NonModalRadio { - Callback m_changed; +Callback m_changed; public: - NonModalRadio(const Callback& changed) : m_changed(changed) - { - } - void connect(GtkRadioButton* radio) - { - GSList* group = gtk_radio_button_group(radio); - for(; group != 0; group = g_slist_next(group)) - { - toggle_button_connect_callback(GTK_TOGGLE_BUTTON(group->data), m_changed); - } - } +NonModalRadio( const Callback& changed ) : m_changed( changed ){ +} +void connect( GtkRadioButton* radio ){ + GSList* group = gtk_radio_button_group( radio ); + for (; group != 0; group = g_slist_next( group ) ) + { + toggle_button_connect_callback( GTK_TOGGLE_BUTTON( group->data ), m_changed ); + } +} }; diff --git a/libs/gtkutil/paned.cpp b/libs/gtkutil/paned.cpp index db0c308b..c5adc09c 100644 --- a/libs/gtkutil/paned.cpp +++ b/libs/gtkutil/paned.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "paned.h" @@ -30,71 +30,65 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class PanedState { public: - float position; - int size; +float position; +int size; }; -gboolean hpaned_allocate(GtkWidget* widget, GtkAllocation* allocation, PanedState* paned) -{ - if(paned->size != allocation->width) - { - paned->size = allocation->width; - gtk_paned_set_position (GTK_PANED (widget), static_cast(paned->size * paned->position)); - } - return FALSE; +gboolean hpaned_allocate( GtkWidget* widget, GtkAllocation* allocation, PanedState* paned ){ + if ( paned->size != allocation->width ) { + paned->size = allocation->width; + gtk_paned_set_position( GTK_PANED( widget ), static_cast( paned->size * paned->position ) ); + } + return FALSE; } -gboolean vpaned_allocate(GtkWidget* widget, GtkAllocation* allocation, PanedState* paned) -{ - if(paned->size != allocation->height) - { - paned->size = allocation->height; - gtk_paned_set_position (GTK_PANED (widget), static_cast(paned->size * paned->position)); - } - return FALSE; +gboolean vpaned_allocate( GtkWidget* widget, GtkAllocation* allocation, PanedState* paned ){ + if ( paned->size != allocation->height ) { + paned->size = allocation->height; + gtk_paned_set_position( GTK_PANED( widget ), static_cast( paned->size * paned->position ) ); + } + return FALSE; } -gboolean paned_position(GtkWidget* widget, gpointer dummy, PanedState* paned) -{ - if(paned->size != -1) - paned->position = gtk_paned_get_position (GTK_PANED (widget)) / static_cast(paned->size); - return FALSE; +gboolean paned_position( GtkWidget* widget, gpointer dummy, PanedState* paned ){ + if ( paned->size != -1 ) { + paned->position = gtk_paned_get_position( GTK_PANED( widget ) ) / static_cast( paned->size ); + } + return FALSE; } PanedState g_hpaned = { 0.5f, -1, }; PanedState g_vpaned1 = { 0.5f, -1, }; PanedState g_vpaned2 = { 0.5f, -1, }; -GtkHPaned* create_split_views(GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright) -{ - GtkHPaned* hsplit = GTK_HPANED(gtk_hpaned_new()); - gtk_widget_show(GTK_WIDGET(hsplit)); - - g_signal_connect(G_OBJECT(hsplit), "size_allocate", G_CALLBACK(hpaned_allocate), &g_hpaned); - g_signal_connect(G_OBJECT(hsplit), "notify::position", G_CALLBACK(paned_position), &g_hpaned); - - { - GtkVPaned* vsplit = GTK_VPANED(gtk_vpaned_new()); - gtk_paned_add1(GTK_PANED(hsplit), GTK_WIDGET(vsplit)); - gtk_widget_show(GTK_WIDGET(vsplit)); - - g_signal_connect(G_OBJECT(vsplit), "size_allocate", G_CALLBACK(vpaned_allocate), &g_vpaned1); - g_signal_connect(G_OBJECT(vsplit), "notify::position", G_CALLBACK(paned_position), &g_vpaned1); - - gtk_paned_add1(GTK_PANED(vsplit), GTK_WIDGET(create_framed_widget(topleft))); - gtk_paned_add2(GTK_PANED(vsplit), GTK_WIDGET(create_framed_widget(topright))); - } - { - GtkVPaned* vsplit = GTK_VPANED(gtk_vpaned_new()); - gtk_paned_add2(GTK_PANED(hsplit), GTK_WIDGET(vsplit)); - gtk_widget_show(GTK_WIDGET(vsplit)); - - g_signal_connect(G_OBJECT(vsplit), "size_allocate", G_CALLBACK(vpaned_allocate), &g_vpaned2); - g_signal_connect(G_OBJECT(vsplit), "notify::position", G_CALLBACK(paned_position), &g_vpaned2); - - gtk_paned_add1(GTK_PANED(vsplit), GTK_WIDGET(create_framed_widget(botleft))); - gtk_paned_add2(GTK_PANED(vsplit), GTK_WIDGET(create_framed_widget(botright))); - } - return hsplit; -} +GtkHPaned* create_split_views( GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright ){ + GtkHPaned* hsplit = GTK_HPANED( gtk_hpaned_new() ); + gtk_widget_show( GTK_WIDGET( hsplit ) ); + + g_signal_connect( G_OBJECT( hsplit ), "size_allocate", G_CALLBACK( hpaned_allocate ), &g_hpaned ); + g_signal_connect( G_OBJECT( hsplit ), "notify::position", G_CALLBACK( paned_position ), &g_hpaned ); + { + GtkVPaned* vsplit = GTK_VPANED( gtk_vpaned_new() ); + gtk_paned_add1( GTK_PANED( hsplit ), GTK_WIDGET( vsplit ) ); + gtk_widget_show( GTK_WIDGET( vsplit ) ); + + g_signal_connect( G_OBJECT( vsplit ), "size_allocate", G_CALLBACK( vpaned_allocate ), &g_vpaned1 ); + g_signal_connect( G_OBJECT( vsplit ), "notify::position", G_CALLBACK( paned_position ), &g_vpaned1 ); + + gtk_paned_add1( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( topleft ) ) ); + gtk_paned_add2( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( topright ) ) ); + } + { + GtkVPaned* vsplit = GTK_VPANED( gtk_vpaned_new() ); + gtk_paned_add2( GTK_PANED( hsplit ), GTK_WIDGET( vsplit ) ); + gtk_widget_show( GTK_WIDGET( vsplit ) ); + + g_signal_connect( G_OBJECT( vsplit ), "size_allocate", G_CALLBACK( vpaned_allocate ), &g_vpaned2 ); + g_signal_connect( G_OBJECT( vsplit ), "notify::position", G_CALLBACK( paned_position ), &g_vpaned2 ); + + gtk_paned_add1( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( botleft ) ) ); + gtk_paned_add2( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( botright ) ) ); + } + return hsplit; +} diff --git a/libs/gtkutil/paned.h b/libs/gtkutil/paned.h index 578a3c5d..8b79f931 100644 --- a/libs/gtkutil/paned.h +++ b/libs/gtkutil/paned.h @@ -1,29 +1,29 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_PANED_H) +#if !defined( INCLUDED_GTKUTIL_PANED_H ) #define INCLUDED_GTKUTIL_PANED_H typedef struct _GtkWidget GtkWidget; typedef struct _GtkHPaned GtkHPaned; -GtkHPaned* create_split_views(GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright); +GtkHPaned* create_split_views( GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright ); #endif diff --git a/libs/gtkutil/pointer.cpp b/libs/gtkutil/pointer.cpp index 2c36d2d7..503845a4 100644 --- a/libs/gtkutil/pointer.cpp +++ b/libs/gtkutil/pointer.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "pointer.h" - diff --git a/libs/gtkutil/pointer.h b/libs/gtkutil/pointer.h index c8294467..035ab8e3 100644 --- a/libs/gtkutil/pointer.h +++ b/libs/gtkutil/pointer.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_POINTER_H) +#if !defined( INCLUDED_GTKUTIL_POINTER_H ) #define INCLUDED_GTKUTIL_POINTER_H typedef int gint; @@ -27,14 +27,12 @@ typedef void* gpointer; #include -inline gint gpointer_to_int(gpointer p) -{ - return gint(std::size_t(p)); +inline gint gpointer_to_int( gpointer p ){ + return gint( std::size_t( p ) ); } -inline gpointer gint_to_pointer(gint i) -{ - return gpointer(std::size_t(i)); +inline gpointer gint_to_pointer( gint i ){ + return gpointer( std::size_t( i ) ); } #endif diff --git a/libs/gtkutil/toolbar.cpp b/libs/gtkutil/toolbar.cpp index 194aff2d..3ac74f61 100644 --- a/libs/gtkutil/toolbar.cpp +++ b/libs/gtkutil/toolbar.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "toolbar.h" @@ -32,47 +32,41 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "pointer.h" -void toolbar_append(GtkToolbar* toolbar, GtkButton* button, const char* description) -{ - gtk_widget_show(GTK_WIDGET(button)); - gtk_button_set_relief(button, GTK_RELIEF_NONE); - GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(button), GTK_CAN_FOCUS); - GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(button), GTK_CAN_DEFAULT); - gtk_toolbar_append_element(toolbar, GTK_TOOLBAR_CHILD_WIDGET, GTK_WIDGET(button), "", description, "", 0, 0, 0); +void toolbar_append( GtkToolbar* toolbar, GtkButton* button, const char* description ){ + gtk_widget_show( GTK_WIDGET( button ) ); + gtk_button_set_relief( button, GTK_RELIEF_NONE ); + GTK_WIDGET_UNSET_FLAGS( GTK_WIDGET( button ), GTK_CAN_FOCUS ); + GTK_WIDGET_UNSET_FLAGS( GTK_WIDGET( button ), GTK_CAN_DEFAULT ); + gtk_toolbar_append_element( toolbar, GTK_TOOLBAR_CHILD_WIDGET, GTK_WIDGET( button ), "", description, "", 0, 0, 0 ); } -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback) -{ - GtkButton* button = GTK_BUTTON(gtk_button_new()); - button_set_icon(button, icon); - button_connect_callback(button, callback); - toolbar_append(toolbar, button, description); - return button; +GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ){ + GtkButton* button = GTK_BUTTON( gtk_button_new() ); + button_set_icon( button, icon ); + button_connect_callback( button, callback ); + toolbar_append( toolbar, button, description ); + return button; } -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback) -{ - GtkToggleButton* button = GTK_TOGGLE_BUTTON(gtk_toggle_button_new()); - button_set_icon(GTK_BUTTON(button), icon); - toggle_button_connect_callback(button, callback); - toolbar_append(toolbar, GTK_BUTTON(button), description); - return button; +GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ){ + GtkToggleButton* button = GTK_TOGGLE_BUTTON( gtk_toggle_button_new() ); + button_set_icon( GTK_BUTTON( button ), icon ); + toggle_button_connect_callback( button, callback ); + toolbar_append( toolbar, GTK_BUTTON( button ), description ); + return button; } -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const Command& command) -{ - return toolbar_append_button(toolbar, description, icon, command.m_callback); +GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Command& command ){ + return toolbar_append_button( toolbar, description, icon, command.m_callback ); } -void toggle_button_set_active_callback(GtkToggleButton& button, bool active) -{ - toggle_button_set_active_no_signal(&button, active); +void toggle_button_set_active_callback( GtkToggleButton& button, bool active ){ + toggle_button_set_active_no_signal( &button, active ); } typedef ReferenceCaller1 ToggleButtonSetActiveCaller; -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle) -{ - GtkToggleButton* button = toolbar_append_toggle_button(toolbar, description, icon, toggle.m_command.m_callback); - toggle.m_exportCallback(ToggleButtonSetActiveCaller(*button)); - return button; +GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle ){ + GtkToggleButton* button = toolbar_append_toggle_button( toolbar, description, icon, toggle.m_command.m_callback ); + toggle.m_exportCallback( ToggleButtonSetActiveCaller( *button ) ); + return button; } diff --git a/libs/gtkutil/toolbar.h b/libs/gtkutil/toolbar.h index 9bf847d2..6b9e32fb 100644 --- a/libs/gtkutil/toolbar.h +++ b/libs/gtkutil/toolbar.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_TOOLBAR_H) +#if !defined( INCLUDED_GTKUTIL_TOOLBAR_H ) #define INCLUDED_GTKUTIL_TOOLBAR_H #include "generic/callbackfwd.h" @@ -30,9 +30,9 @@ typedef struct _GtkToolbar GtkToolbar; class Command; class Toggle; -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback); -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const Command& command); -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback); -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle); +GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ); +GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Command& command ); +GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ); +GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle ); #endif diff --git a/libs/gtkutil/widget.cpp b/libs/gtkutil/widget.cpp index 62a1b6ca..e212fdf6 100644 --- a/libs/gtkutil/widget.cpp +++ b/libs/gtkutil/widget.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "widget.h" - diff --git a/libs/gtkutil/widget.h b/libs/gtkutil/widget.h index 225fccf4..ceb92409 100644 --- a/libs/gtkutil/widget.h +++ b/libs/gtkutil/widget.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_WIDGET_H) +#if !defined( INCLUDED_GTKUTIL_WIDGET_H ) #define INCLUDED_GTKUTIL_WIDGET_H #include @@ -28,163 +28,139 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "warnings.h" #include "debugging/debugging.h" -inline void widget_set_visible(GtkWidget* widget, bool shown) -{ - if(shown) - { - gtk_widget_show(widget); - } - else - { - gtk_widget_hide(widget); - } +inline void widget_set_visible( GtkWidget* widget, bool shown ){ + if ( shown ) { + gtk_widget_show( widget ); + } + else + { + gtk_widget_hide( widget ); + } } -inline bool widget_is_visible(GtkWidget* widget) -{ - return GTK_WIDGET_VISIBLE(widget) != FALSE; +inline bool widget_is_visible( GtkWidget* widget ){ + return GTK_WIDGET_VISIBLE( widget ) != FALSE; } -inline void widget_toggle_visible(GtkWidget* widget) -{ - widget_set_visible(widget, !widget_is_visible(widget)); +inline void widget_toggle_visible( GtkWidget* widget ){ + widget_set_visible( widget, !widget_is_visible( widget ) ); } class ToggleItem { - BoolExportCallback m_exportCallback; - typedef std::list ImportCallbacks; - ImportCallbacks m_importCallbacks; +BoolExportCallback m_exportCallback; +typedef std::list ImportCallbacks; +ImportCallbacks m_importCallbacks; public: - ToggleItem(const BoolExportCallback& exportCallback) : m_exportCallback(exportCallback) - { - } - - void update() - { - for(ImportCallbacks::iterator i = m_importCallbacks.begin(); i != m_importCallbacks.end(); ++i) - { - m_exportCallback(*i); - } - } - - void addCallback(const BoolImportCallback& callback) - { - m_importCallbacks.push_back(callback); - m_exportCallback(callback); - } - typedef MemberCaller1 AddCallbackCaller; +ToggleItem( const BoolExportCallback& exportCallback ) : m_exportCallback( exportCallback ){ +} + +void update(){ + for ( ImportCallbacks::iterator i = m_importCallbacks.begin(); i != m_importCallbacks.end(); ++i ) + { + m_exportCallback( *i ); + } +} + +void addCallback( const BoolImportCallback& callback ){ + m_importCallbacks.push_back( callback ); + m_exportCallback( callback ); +} +typedef MemberCaller1 AddCallbackCaller; }; class ToggleShown { - bool m_shownDeferred; - - ToggleShown(const ToggleShown& other); // NOT COPYABLE - ToggleShown& operator=(const ToggleShown& other); // NOT ASSIGNABLE - - static gboolean notify_visible(GtkWidget* widget, gpointer dummy, ToggleShown* self) - { - self->update(); - return FALSE; - } - static gboolean destroy(GtkWidget* widget, ToggleShown* self) - { - self->m_shownDeferred = GTK_WIDGET_VISIBLE(self->m_widget) != FALSE; - self->m_widget = 0; - return FALSE; - } +bool m_shownDeferred; + +ToggleShown( const ToggleShown& other ); // NOT COPYABLE +ToggleShown& operator=( const ToggleShown& other ); // NOT ASSIGNABLE + +static gboolean notify_visible( GtkWidget* widget, gpointer dummy, ToggleShown* self ){ + self->update(); + return FALSE; +} +static gboolean destroy( GtkWidget* widget, ToggleShown* self ){ + self->m_shownDeferred = GTK_WIDGET_VISIBLE( self->m_widget ) != FALSE; + self->m_widget = 0; + return FALSE; +} public: - GtkWidget* m_widget; - ToggleItem m_item; - - ToggleShown(bool shown) - : m_shownDeferred(shown), m_widget(0), m_item(ActiveCaller(*this)) - { - } - void update() - { - m_item.update(); - } - bool active() const - { - if(m_widget == 0) - { - return m_shownDeferred; - } - else - { - return GTK_WIDGET_VISIBLE(m_widget) != FALSE; - } - } - void exportActive(const BoolImportCallback& importCallback) - { - importCallback(active()); - } - typedef MemberCaller1 ActiveCaller; - void set(bool shown) - { - if(m_widget == 0) - { - m_shownDeferred = shown; - } - else - { - widget_set_visible(m_widget, shown); - } - } - void toggle() - { - widget_toggle_visible(m_widget); - } - typedef MemberCaller ToggleCaller; - void connect(GtkWidget* widget) - { - m_widget = widget; - widget_set_visible(m_widget, m_shownDeferred); - g_signal_connect(G_OBJECT(m_widget), "notify::visible", G_CALLBACK(notify_visible), this); - g_signal_connect(G_OBJECT(m_widget), "destroy", G_CALLBACK(destroy), this); - update(); - } +GtkWidget* m_widget; +ToggleItem m_item; + +ToggleShown( bool shown ) + : m_shownDeferred( shown ), m_widget( 0 ), m_item( ActiveCaller( *this ) ){ +} +void update(){ + m_item.update(); +} +bool active() const { + if ( m_widget == 0 ) { + return m_shownDeferred; + } + else + { + return GTK_WIDGET_VISIBLE( m_widget ) != FALSE; + } +} +void exportActive( const BoolImportCallback& importCallback ){ + importCallback( active() ); +} +typedef MemberCaller1 ActiveCaller; +void set( bool shown ){ + if ( m_widget == 0 ) { + m_shownDeferred = shown; + } + else + { + widget_set_visible( m_widget, shown ); + } +} +void toggle(){ + widget_toggle_visible( m_widget ); +} +typedef MemberCaller ToggleCaller; +void connect( GtkWidget* widget ){ + m_widget = widget; + widget_set_visible( m_widget, m_shownDeferred ); + g_signal_connect( G_OBJECT( m_widget ), "notify::visible", G_CALLBACK( notify_visible ), this ); + g_signal_connect( G_OBJECT( m_widget ), "destroy", G_CALLBACK( destroy ), this ); + update(); +} }; -inline void widget_queue_draw(GtkWidget& widget) -{ - gtk_widget_queue_draw(&widget); +inline void widget_queue_draw( GtkWidget& widget ){ + gtk_widget_queue_draw( &widget ); } typedef ReferenceCaller WidgetQueueDrawCaller; -inline void widget_make_default(GtkWidget* widget) -{ - GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT); - gtk_widget_grab_default(widget); +inline void widget_make_default( GtkWidget* widget ){ + GTK_WIDGET_SET_FLAGS( widget, GTK_CAN_DEFAULT ); + gtk_widget_grab_default( widget ); } class WidgetFocusPrinter { - const char* m_name; - - static gboolean focus_in(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) - { - globalOutputStream() << self->m_name << " takes focus\n"; - return FALSE; - } - static gboolean focus_out(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) - { - globalOutputStream() << self->m_name << " loses focus\n"; - return FALSE; - } +const char* m_name; + +static gboolean focus_in( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ + globalOutputStream() << self->m_name << " takes focus\n"; + return FALSE; +} +static gboolean focus_out( GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self ){ + globalOutputStream() << self->m_name << " loses focus\n"; + return FALSE; +} public: - WidgetFocusPrinter(const char* name) : m_name(name) - { - } - void connect(GtkWidget* widget) - { - g_signal_connect(G_OBJECT(widget), "focus_in_event", G_CALLBACK(focus_in), this); - g_signal_connect(G_OBJECT(widget), "focus_out_event", G_CALLBACK(focus_out), this); - } +WidgetFocusPrinter( const char* name ) : m_name( name ){ +} +void connect( GtkWidget* widget ){ + g_signal_connect( G_OBJECT( widget ), "focus_in_event", G_CALLBACK( focus_in ), this ); + g_signal_connect( G_OBJECT( widget ), "focus_out_event", G_CALLBACK( focus_out ), this ); +} }; #endif diff --git a/libs/gtkutil/window.cpp b/libs/gtkutil/window.cpp index 5d465531..48b174b3 100644 --- a/libs/gtkutil/window.cpp +++ b/libs/gtkutil/window.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "window.h" @@ -26,145 +26,121 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "pointer.h" #include "accelerator.h" -inline void CHECK_RESTORE(GtkWidget* w) -{ - if(gpointer_to_int(g_object_get_data(G_OBJECT(w), "was_mapped")) != 0) - { - gtk_widget_show(w); - } +inline void CHECK_RESTORE( GtkWidget* w ){ + if ( gpointer_to_int( g_object_get_data( G_OBJECT( w ), "was_mapped" ) ) != 0 ) { + gtk_widget_show( w ); + } } -inline void CHECK_MINIMIZE(GtkWidget* w) -{ - g_object_set_data(G_OBJECT(w), "was_mapped", gint_to_pointer(GTK_WIDGET_VISIBLE(w))); - gtk_widget_hide(w); +inline void CHECK_MINIMIZE( GtkWidget* w ){ + g_object_set_data( G_OBJECT( w ), "was_mapped", gint_to_pointer( GTK_WIDGET_VISIBLE( w ) ) ); + gtk_widget_hide( w ); } -static gboolean main_window_iconified(GtkWidget* widget, GdkEventWindowState* event, gpointer data) -{ - if((event->changed_mask & (GDK_WINDOW_STATE_ICONIFIED|GDK_WINDOW_STATE_WITHDRAWN)) != 0) - { - if((event->new_window_state & (GDK_WINDOW_STATE_ICONIFIED|GDK_WINDOW_STATE_WITHDRAWN)) != 0) - { - CHECK_MINIMIZE(GTK_WIDGET(data)); - } - else - { - CHECK_RESTORE(GTK_WIDGET(data)); - } - } - return FALSE; +static gboolean main_window_iconified( GtkWidget* widget, GdkEventWindowState* event, gpointer data ){ + if ( ( event->changed_mask & ( GDK_WINDOW_STATE_ICONIFIED | GDK_WINDOW_STATE_WITHDRAWN ) ) != 0 ) { + if ( ( event->new_window_state & ( GDK_WINDOW_STATE_ICONIFIED | GDK_WINDOW_STATE_WITHDRAWN ) ) != 0 ) { + CHECK_MINIMIZE( GTK_WIDGET( data ) ); + } + else + { + CHECK_RESTORE( GTK_WIDGET( data ) ); + } + } + return FALSE; } -unsigned int connect_floating(GtkWindow* main_window, GtkWindow* floating) -{ - return g_signal_connect(G_OBJECT(main_window), "window_state_event", G_CALLBACK(main_window_iconified), floating); +unsigned int connect_floating( GtkWindow* main_window, GtkWindow* floating ){ + return g_signal_connect( G_OBJECT( main_window ), "window_state_event", G_CALLBACK( main_window_iconified ), floating ); } -gboolean destroy_disconnect_floating(GtkWindow* widget, gpointer data) -{ - g_signal_handler_disconnect(G_OBJECT(data), gpointer_to_int(g_object_get_data(G_OBJECT(widget), "floating_handler"))); - return FALSE; +gboolean destroy_disconnect_floating( GtkWindow* widget, gpointer data ){ + g_signal_handler_disconnect( G_OBJECT( data ), gpointer_to_int( g_object_get_data( G_OBJECT( widget ), "floating_handler" ) ) ); + return FALSE; } -gboolean floating_window_delete_present(GtkWindow* floating, GdkEventFocus *event, GtkWindow* main_window) -{ - if(gtk_window_is_active(floating) || gtk_window_is_active(main_window)) - { - gtk_window_present(main_window); - } - return FALSE; +gboolean floating_window_delete_present( GtkWindow* floating, GdkEventFocus *event, GtkWindow* main_window ){ + if ( gtk_window_is_active( floating ) || gtk_window_is_active( main_window ) ) { + gtk_window_present( main_window ); + } + return FALSE; } -guint connect_floating_window_delete_present(GtkWindow* floating, GtkWindow* main_window) -{ - return g_signal_connect(G_OBJECT(floating), "delete_event", G_CALLBACK(floating_window_delete_present), main_window); +guint connect_floating_window_delete_present( GtkWindow* floating, GtkWindow* main_window ){ + return g_signal_connect( G_OBJECT( floating ), "delete_event", G_CALLBACK( floating_window_delete_present ), main_window ); } -gboolean floating_window_destroy_present(GtkWindow* floating, GtkWindow* main_window) -{ - if(gtk_window_is_active(floating) || gtk_window_is_active(main_window)) - { - gtk_window_present(main_window); - } - return FALSE; +gboolean floating_window_destroy_present( GtkWindow* floating, GtkWindow* main_window ){ + if ( gtk_window_is_active( floating ) || gtk_window_is_active( main_window ) ) { + gtk_window_present( main_window ); + } + return FALSE; } -guint connect_floating_window_destroy_present(GtkWindow* floating, GtkWindow* main_window) -{ - return g_signal_connect(G_OBJECT(floating), "destroy", G_CALLBACK(floating_window_destroy_present), main_window); +guint connect_floating_window_destroy_present( GtkWindow* floating, GtkWindow* main_window ){ + return g_signal_connect( G_OBJECT( floating ), "destroy", G_CALLBACK( floating_window_destroy_present ), main_window ); } -GtkWindow* create_floating_window(const char* title, GtkWindow* parent) -{ - GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL)); - gtk_window_set_title(window, title); +GtkWindow* create_floating_window( const char* title, GtkWindow* parent ){ + GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) ); + gtk_window_set_title( window, title ); - if(parent != 0) - { - gtk_window_set_transient_for(window, parent); - connect_floating_window_destroy_present(window, parent); - g_object_set_data(G_OBJECT(window), "floating_handler", gint_to_pointer(connect_floating(parent, window))); - g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy_disconnect_floating), parent); - } + if ( parent != 0 ) { + gtk_window_set_transient_for( window, parent ); + connect_floating_window_destroy_present( window, parent ); + g_object_set_data( G_OBJECT( window ), "floating_handler", gint_to_pointer( connect_floating( parent, window ) ) ); + g_signal_connect( G_OBJECT( window ), "destroy", G_CALLBACK( destroy_disconnect_floating ), parent ); + } - return window; + return window; } -void destroy_floating_window(GtkWindow* window) -{ - gtk_widget_destroy(GTK_WIDGET(window)); +void destroy_floating_window( GtkWindow* window ){ + gtk_widget_destroy( GTK_WIDGET( window ) ); } -gint window_realize_remove_sysmenu(GtkWidget* widget, gpointer data) -{ - gdk_window_set_decorations(widget->window, (GdkWMDecoration)(GDK_DECOR_ALL|GDK_DECOR_MENU)); - return FALSE; +gint window_realize_remove_sysmenu( GtkWidget* widget, gpointer data ){ + gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU ) ); + return FALSE; } -gboolean persistent_floating_window_delete(GtkWindow* floating, GdkEvent *event, GtkWindow* main_window) -{ - gtk_widget_hide(GTK_WIDGET(floating)); - return TRUE; +gboolean persistent_floating_window_delete( GtkWindow* floating, GdkEvent *event, GtkWindow* main_window ){ + gtk_widget_hide( GTK_WIDGET( floating ) ); + return TRUE; } -GtkWindow* create_persistent_floating_window(const char* title, GtkWindow* main_window) -{ - GtkWindow* window = GTK_WINDOW(create_floating_window(title, main_window)); +GtkWindow* create_persistent_floating_window( const char* title, GtkWindow* main_window ){ + GtkWindow* window = GTK_WINDOW( create_floating_window( title, main_window ) ); - gtk_widget_set_events(GTK_WIDGET(window), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); + gtk_widget_set_events( GTK_WIDGET( window ), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK ); - connect_floating_window_delete_present(window, main_window); - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(persistent_floating_window_delete), 0); + connect_floating_window_delete_present( window, main_window ); + g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( persistent_floating_window_delete ), 0 ); #if 0 - if(g_multimon_globals.m_bStartOnPrimMon && g_multimon_globals.m_bNoSysMenuPopups) - g_signal_connect(G_OBJECT(window), "realize", G_CALLBACK(window_realize_remove_sysmenu), 0); + if ( g_multimon_globals.m_bStartOnPrimMon && g_multimon_globals.m_bNoSysMenuPopups ) { + g_signal_connect( G_OBJECT( window ), "realize", G_CALLBACK( window_realize_remove_sysmenu ), 0 ); + } #endif - return window; + return window; } -gint window_realize_remove_minmax(GtkWidget* widget, gpointer data) -{ - gdk_window_set_decorations(widget->window, (GdkWMDecoration)(GDK_DECOR_ALL|GDK_DECOR_MINIMIZE|GDK_DECOR_MAXIMIZE)); - return FALSE; +gint window_realize_remove_minmax( GtkWidget* widget, gpointer data ){ + gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) ); + return FALSE; } -void window_remove_minmax(GtkWindow* window) -{ - g_signal_connect(G_OBJECT(window), "realize", G_CALLBACK(window_realize_remove_minmax), 0); +void window_remove_minmax( GtkWindow* window ){ + g_signal_connect( G_OBJECT( window ), "realize", G_CALLBACK( window_realize_remove_minmax ), 0 ); } -GtkScrolledWindow* create_scrolled_window(GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border) -{ - GtkScrolledWindow* scr = GTK_SCROLLED_WINDOW(gtk_scrolled_window_new(0, 0)); - gtk_widget_show(GTK_WIDGET(scr)); - gtk_scrolled_window_set_policy(scr, hscrollbar_policy, vscrollbar_policy); - gtk_scrolled_window_set_shadow_type(scr, GTK_SHADOW_IN); - gtk_container_set_border_width(GTK_CONTAINER(scr), border); - return scr; +GtkScrolledWindow* create_scrolled_window( GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border ){ + GtkScrolledWindow* scr = GTK_SCROLLED_WINDOW( gtk_scrolled_window_new( 0, 0 ) ); + gtk_widget_show( GTK_WIDGET( scr ) ); + gtk_scrolled_window_set_policy( scr, hscrollbar_policy, vscrollbar_policy ); + gtk_scrolled_window_set_shadow_type( scr, GTK_SHADOW_IN ); + gtk_container_set_border_width( GTK_CONTAINER( scr ), border ); + return scr; } - - diff --git a/libs/gtkutil/window.h b/libs/gtkutil/window.h index 5ab1e500..1a7161e6 100644 --- a/libs/gtkutil/window.h +++ b/libs/gtkutil/window.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_GTKUTIL_WINDOW_H) +#if !defined( INCLUDED_GTKUTIL_WINDOW_H ) #define INCLUDED_GTKUTIL_WINDOW_H #include @@ -28,88 +28,78 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "generic/callback.h" #include "widget.h" -inline gboolean window_focus_in_clear_focus_widget(GtkWidget* widget, GdkEventKey* event, gpointer data) -{ - gtk_window_set_focus(GTK_WINDOW(widget), NULL); - return FALSE; +inline gboolean window_focus_in_clear_focus_widget( GtkWidget* widget, GdkEventKey* event, gpointer data ){ + gtk_window_set_focus( GTK_WINDOW( widget ), NULL ); + return FALSE; } -inline guint window_connect_focus_in_clear_focus_widget(GtkWindow* window) -{ - return g_signal_connect(G_OBJECT(window), "focus_in_event", G_CALLBACK(window_focus_in_clear_focus_widget), NULL); +inline guint window_connect_focus_in_clear_focus_widget( GtkWindow* window ){ + return g_signal_connect( G_OBJECT( window ), "focus_in_event", G_CALLBACK( window_focus_in_clear_focus_widget ), NULL ); } -unsigned int connect_floating(GtkWindow* main_window, GtkWindow* floating); -GtkWindow* create_floating_window(const char* title, GtkWindow* parent); -void destroy_floating_window(GtkWindow* window); +unsigned int connect_floating( GtkWindow* main_window, GtkWindow* floating ); +GtkWindow* create_floating_window( const char* title, GtkWindow* parent ); +void destroy_floating_window( GtkWindow* window ); -GtkWindow* create_persistent_floating_window(const char* title, GtkWindow* main_window); -gboolean persistent_floating_window_delete(GtkWindow* floating, GdkEvent *event, GtkWindow* main_window); +GtkWindow* create_persistent_floating_window( const char* title, GtkWindow* main_window ); +gboolean persistent_floating_window_delete( GtkWindow* floating, GdkEvent *event, GtkWindow* main_window ); -void window_remove_minmax(GtkWindow* window); +void window_remove_minmax( GtkWindow* window ); typedef struct _GtkScrolledWindow GtkScrolledWindow; -GtkScrolledWindow* create_scrolled_window(GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border = 0); +GtkScrolledWindow* create_scrolled_window( GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border = 0 ); struct WindowPosition { - int x, y, w, h; - - WindowPosition() - { - } - WindowPosition(int _x, int _y, int _w, int _h) - : x(_x), y(_y), w(_w), h(_h) - { - } + int x, y, w, h; + + WindowPosition(){ + } + WindowPosition( int _x, int _y, int _w, int _h ) + : x( _x ), y( _y ), w( _w ), h( _h ){ + } }; -const WindowPosition c_default_window_pos(50, 25, 400, 300); +const WindowPosition c_default_window_pos( 50, 25, 400, 300 ); -inline void window_get_position(GtkWindow* window, WindowPosition& position) -{ - ASSERT_MESSAGE(window != 0, "error saving window position"); +inline void window_get_position( GtkWindow* window, WindowPosition& position ){ + ASSERT_MESSAGE( window != 0, "error saving window position" ); - gtk_window_get_position(window, &position.x, &position.y); - gtk_window_get_size(window, &position.w, &position.h); + gtk_window_get_position( window, &position.x, &position.y ); + gtk_window_get_size( window, &position.w, &position.h ); } -inline void window_set_position(GtkWindow* window, const WindowPosition& position) -{ - gtk_window_set_gravity(window, GDK_GRAVITY_STATIC); - - GdkScreen* screen = gdk_screen_get_default(); - if(position.x < 0 - || position.y < 0 - || position.x > gdk_screen_get_width(screen) - || position.y > gdk_screen_get_height(screen)) - { - gtk_window_set_position(window, GTK_WIN_POS_CENTER_ON_PARENT); - } - else - { - gtk_window_move(window, position.x, position.y); - } - - gtk_window_set_default_size(window, position.w, position.h); +inline void window_set_position( GtkWindow* window, const WindowPosition& position ){ + gtk_window_set_gravity( window, GDK_GRAVITY_STATIC ); + + GdkScreen* screen = gdk_screen_get_default(); + if ( position.x < 0 + || position.y < 0 + || position.x > gdk_screen_get_width( screen ) + || position.y > gdk_screen_get_height( screen ) ) { + gtk_window_set_position( window, GTK_WIN_POS_CENTER_ON_PARENT ); + } + else + { + gtk_window_move( window, position.x, position.y ); + } + + gtk_window_set_default_size( window, position.w, position.h ); } -inline void WindowPosition_Parse(WindowPosition& position, const char* value) -{ - if(sscanf(value, "%d %d %d %d", &position.x, &position.y, &position.w, &position.h) != 4) - { - position = WindowPosition(c_default_window_pos); // ensure sane default value for window position - } +inline void WindowPosition_Parse( WindowPosition& position, const char* value ){ + if ( sscanf( value, "%d %d %d %d", &position.x, &position.y, &position.w, &position.h ) != 4 ) { + position = WindowPosition( c_default_window_pos ); // ensure sane default value for window position + } } typedef ReferenceCaller1 WindowPositionImportStringCaller; -inline void WindowPosition_Write(const WindowPosition& position, const StringImportCallback& importCallback) -{ - char buffer[64]; - sprintf(buffer, "%d %d %d %d", position.x, position.y, position.w, position.h); - importCallback(buffer); +inline void WindowPosition_Write( const WindowPosition& position, const StringImportCallback& importCallback ){ + char buffer[64]; + sprintf( buffer, "%d %d %d %d", position.x, position.y, position.w, position.h ); + importCallback( buffer ); } typedef ConstReferenceCaller1 WindowPositionExportStringCaller; @@ -117,55 +107,47 @@ typedef ConstReferenceCaller1m_position = WindowPosition(event->x, event->y, event->width, event->height); - return FALSE; - } +static gboolean configure( GtkWidget* widget, GdkEventConfigure *event, WindowPositionTracker* self ){ + self->m_position = WindowPosition( event->x, event->y, event->width, event->height ); + return FALSE; +} public: - WindowPositionTracker() - : m_position(c_default_window_pos) - { - } - - void sync(GtkWindow* window) - { - window_set_position(window, m_position); - } - - void connect(GtkWindow* window) - { - sync(window); - g_signal_connect(G_OBJECT(window), "configure_event", G_CALLBACK(configure), this); - } - - const WindowPosition& getPosition() const - { - return m_position; - } - - //hack - void setPosition(const WindowPosition& position) - { - m_position = position; - } +WindowPositionTracker() + : m_position( c_default_window_pos ){ +} + +void sync( GtkWindow* window ){ + window_set_position( window, m_position ); +} + +void connect( GtkWindow* window ){ + sync( window ); + g_signal_connect( G_OBJECT( window ), "configure_event", G_CALLBACK( configure ), this ); +} + +const WindowPosition& getPosition() const { + return m_position; +} + +//hack +void setPosition( const WindowPosition& position ){ + m_position = position; +} }; -inline void WindowPositionTracker_importString(WindowPositionTracker& self, const char* value) -{ - WindowPosition position; - WindowPosition_Parse(position, value); - self.setPosition(position); +inline void WindowPositionTracker_importString( WindowPositionTracker& self, const char* value ){ + WindowPosition position; + WindowPosition_Parse( position, value ); + self.setPosition( position ); } typedef ReferenceCaller1 WindowPositionTrackerImportStringCaller; -inline void WindowPositionTracker_exportString(const WindowPositionTracker& self, const StringImportCallback& importer) -{ - WindowPosition_Write(self.getPosition(), importer); +inline void WindowPositionTracker_exportString( const WindowPositionTracker& self, const StringImportCallback& importer ){ + WindowPosition_Write( self.getPosition(), importer ); } typedef ConstReferenceCaller1 WindowPositionTrackerExportStringCaller; diff --git a/libs/gtkutil/xorrectangle.cpp b/libs/gtkutil/xorrectangle.cpp index d968337d..e4f46c6b 100644 --- a/libs/gtkutil/xorrectangle.cpp +++ b/libs/gtkutil/xorrectangle.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "xorrectangle.h" - diff --git a/libs/gtkutil/xorrectangle.h b/libs/gtkutil/xorrectangle.h index 0d89203e..6c4d64fc 100644 --- a/libs/gtkutil/xorrectangle.h +++ b/libs/gtkutil/xorrectangle.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_XORRECTANGLE_H) +#if !defined ( INCLUDED_XORRECTANGLE_H ) #define INCLUDED_XORRECTANGLE_H #include @@ -28,97 +28,85 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class rectangle_t { public: - rectangle_t() - : x(0), y(0), w(0), h(0) - {} - rectangle_t(float _x, float _y, float _w, float _h) - : x(_x), y(_y), w(_w), h(_h) - {} - float x; - float y; - float w; - float h; +rectangle_t() + : x( 0 ), y( 0 ), w( 0 ), h( 0 ) +{} +rectangle_t( float _x, float _y, float _w, float _h ) + : x( _x ), y( _y ), w( _w ), h( _h ) +{} +float x; +float y; +float w; +float h; }; struct Coord2D { - float x, y; - Coord2D(float _x, float _y) - : x(_x), y(_y) - { - } + float x, y; + Coord2D( float _x, float _y ) + : x( _x ), y( _y ){ + } }; -inline Coord2D coord2d_device2screen(const Coord2D& coord, unsigned int width, unsigned int height) -{ - return Coord2D(((coord.x + 1.0f) * 0.5f) * width, ((coord.y + 1.0f) * 0.5f) * height); +inline Coord2D coord2d_device2screen( const Coord2D& coord, unsigned int width, unsigned int height ){ + return Coord2D( ( ( coord.x + 1.0f ) * 0.5f ) * width, ( ( coord.y + 1.0f ) * 0.5f ) * height ); } -inline rectangle_t rectangle_from_area(const float min[2], const float max[2], unsigned int width, unsigned int height) -{ - Coord2D botleft(coord2d_device2screen(Coord2D(min[0], min[1]), width, height)); - Coord2D topright(coord2d_device2screen(Coord2D(max[0], max[1]), width, height)); - return rectangle_t(botleft.x, botleft.y, topright.x - botleft.x, topright.y - botleft.y); +inline rectangle_t rectangle_from_area( const float min[2], const float max[2], unsigned int width, unsigned int height ){ + Coord2D botleft( coord2d_device2screen( Coord2D( min[0], min[1] ), width, height ) ); + Coord2D topright( coord2d_device2screen( Coord2D( max[0], max[1] ), width, height ) ); + return rectangle_t( botleft.x, botleft.y, topright.x - botleft.x, topright.y - botleft.y ); } class XORRectangle { - rectangle_t m_rectangle; - - GtkWidget* m_widget; - GdkGC* m_gc; - - bool initialised() const - { - return m_gc != 0; - } - void lazy_init() - { - if(!initialised()) - { - m_gc = gdk_gc_new(m_widget->window); - - GdkColor color = { 0, 0xffff, 0xffff, 0xffff, }; - GdkColormap* colormap = gdk_window_get_colormap(m_widget->window); - gdk_colormap_alloc_color (colormap, &color, FALSE, TRUE); - gdk_gc_copy(m_gc, m_widget->style->white_gc); - gdk_gc_set_foreground(m_gc, &color); - gdk_gc_set_background(m_gc, &color); - - gdk_gc_set_function(m_gc, GDK_INVERT); - } - } - void draw() const - { - const int x = float_to_integer(m_rectangle.x); - const int y = float_to_integer(m_rectangle.y); - const int w = float_to_integer(m_rectangle.w); - const int h = float_to_integer(m_rectangle.h); - gdk_draw_rectangle(m_widget->window, m_gc, FALSE, x, -(h) - (y - m_widget->allocation.height), w, h); - } +rectangle_t m_rectangle; + +GtkWidget* m_widget; +GdkGC* m_gc; + +bool initialised() const { + return m_gc != 0; +} +void lazy_init(){ + if ( !initialised() ) { + m_gc = gdk_gc_new( m_widget->window ); + + GdkColor color = { 0, 0xffff, 0xffff, 0xffff, }; + GdkColormap* colormap = gdk_window_get_colormap( m_widget->window ); + gdk_colormap_alloc_color( colormap, &color, FALSE, TRUE ); + gdk_gc_copy( m_gc, m_widget->style->white_gc ); + gdk_gc_set_foreground( m_gc, &color ); + gdk_gc_set_background( m_gc, &color ); + + gdk_gc_set_function( m_gc, GDK_INVERT ); + } +} +void draw() const { + const int x = float_to_integer( m_rectangle.x ); + const int y = float_to_integer( m_rectangle.y ); + const int w = float_to_integer( m_rectangle.w ); + const int h = float_to_integer( m_rectangle.h ); + gdk_draw_rectangle( m_widget->window, m_gc, FALSE, x, -( h ) - ( y - m_widget->allocation.height ), w, h ); +} public: - XORRectangle(GtkWidget* widget) : m_widget(widget), m_gc(0) - { - } - ~XORRectangle() - { - if(initialised()) - { - gdk_gc_unref(m_gc); - } - } - void set(rectangle_t rectangle) - { - if(GTK_WIDGET_REALIZED(m_widget)) - { - lazy_init(); - draw(); - m_rectangle = rectangle; - draw(); - } - } +XORRectangle( GtkWidget* widget ) : m_widget( widget ), m_gc( 0 ){ +} +~XORRectangle(){ + if ( initialised() ) { + gdk_gc_unref( m_gc ); + } +} +void set( rectangle_t rectangle ){ + if ( GTK_WIDGET_REALIZED( m_widget ) ) { + lazy_init(); + draw(); + m_rectangle = rectangle; + draw(); + } +} }; diff --git a/libs/imagelib.cpp b/libs/imagelib.cpp index 5c205f63..08e2d27e 100644 --- a/libs/imagelib.cpp +++ b/libs/imagelib.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "imagelib.h" - diff --git a/libs/imagelib.h b/libs/imagelib.h index 5a1afa67..c3e9c1c9 100644 --- a/libs/imagelib.h +++ b/libs/imagelib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_IMAGELIB_H) +#if !defined( INCLUDED_IMAGELIB_H ) #define INCLUDED_IMAGELIB_H #include "iimage.h" @@ -29,124 +29,106 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA struct RGBAPixel { - unsigned char red, green, blue, alpha; + unsigned char red, green, blue, alpha; }; class RGBAImage : public Image { - RGBAImage(const RGBAImage& other); - RGBAImage& operator=(const RGBAImage& other); +RGBAImage( const RGBAImage& other ); +RGBAImage& operator=( const RGBAImage& other ); public: - RGBAPixel* pixels; - unsigned int width, height; - - RGBAImage(unsigned int _width, unsigned int _height) - : pixels(new RGBAPixel[_width * _height]), width(_width), height(_height) - { - } - ~RGBAImage() - { - delete[] pixels; - } - - void release() - { - delete this; - } - byte* getRGBAPixels() const - { - return reinterpret_cast(pixels); - } - unsigned int getWidth() const - { - return width; - } - unsigned int getHeight() const - { - return height; - } +RGBAPixel* pixels; +unsigned int width, height; + +RGBAImage( unsigned int _width, unsigned int _height ) + : pixels( new RGBAPixel[_width * _height] ), width( _width ), height( _height ){ +} +~RGBAImage(){ + delete[] pixels; +} + +void release(){ + delete this; +} +byte* getRGBAPixels() const { + return reinterpret_cast( pixels ); +} +unsigned int getWidth() const { + return width; +} +unsigned int getHeight() const { + return height; +} }; class RGBAImageFlags : public RGBAImage { public: - int m_surfaceFlags; - int m_contentFlags; - int m_value; - RGBAImageFlags(unsigned short _width, unsigned short _height, int surfaceFlags, int contentFlags, int value) : - RGBAImage(_width, _height), m_surfaceFlags(surfaceFlags), m_contentFlags(contentFlags), m_value(value) - { - } - - int getSurfaceFlags() const - { - return m_surfaceFlags; - } - int getContentFlags() const - { - return m_contentFlags; - } - int getValue() const - { - return m_value; - } +int m_surfaceFlags; +int m_contentFlags; +int m_value; +RGBAImageFlags( unsigned short _width, unsigned short _height, int surfaceFlags, int contentFlags, int value ) : + RGBAImage( _width, _height ), m_surfaceFlags( surfaceFlags ), m_contentFlags( contentFlags ), m_value( value ){ +} + +int getSurfaceFlags() const { + return m_surfaceFlags; +} +int getContentFlags() const { + return m_contentFlags; +} +int getValue() const { + return m_value; +} }; -inline InputStream::byte_type* ArchiveFile_loadBuffer(ArchiveFile& file, std::size_t& length) -{ - InputStream::byte_type* buffer = (InputStream::byte_type*)malloc(file.size() + 1); - length = file.getInputStream().read(buffer, file.size()); - buffer[file.size()] = 0; - return buffer; +inline InputStream::byte_type* ArchiveFile_loadBuffer( ArchiveFile& file, std::size_t& length ){ + InputStream::byte_type* buffer = (InputStream::byte_type*)malloc( file.size() + 1 ); + length = file.getInputStream().read( buffer, file.size() ); + buffer[file.size()] = 0; + return buffer; } -inline void ArchiveFile_freeBuffer(InputStream::byte_type* buffer) -{ - free(buffer); +inline void ArchiveFile_freeBuffer( InputStream::byte_type* buffer ){ + free( buffer ); } class ScopedArchiveBuffer { public: - std::size_t length; - InputStream::byte_type* buffer; - - ScopedArchiveBuffer(ArchiveFile& file) - { - buffer = ArchiveFile_loadBuffer(file, length); - } - ~ScopedArchiveBuffer() - { - ArchiveFile_freeBuffer(buffer); - } +std::size_t length; +InputStream::byte_type* buffer; + +ScopedArchiveBuffer( ArchiveFile& file ){ + buffer = ArchiveFile_loadBuffer( file, length ); +} +~ScopedArchiveBuffer(){ + ArchiveFile_freeBuffer( buffer ); +} }; class PointerInputStream : public InputStream { - const byte* m_read; +const byte* m_read; public: - PointerInputStream(const byte* pointer) - : m_read(pointer) - { - } - std::size_t read(byte* buffer, std::size_t length) - { - const byte* end = m_read + length; - while(m_read != end) - { - *buffer++ = *m_read++; - } - return length; - } - void seek(std::size_t offset) - { - m_read += offset; - } - const byte* get() - { - return m_read; - } +PointerInputStream( const byte* pointer ) + : m_read( pointer ){ +} +std::size_t read( byte* buffer, std::size_t length ){ + const byte* end = m_read + length; + while ( m_read != end ) + { + *buffer++ = *m_read++; + } + return length; +} +void seek( std::size_t offset ){ + m_read += offset; +} +const byte* get(){ + return m_read; +} }; #endif diff --git a/libs/instancelib.cpp b/libs/instancelib.cpp index 053ac73b..52dfc8d4 100644 --- a/libs/instancelib.cpp +++ b/libs/instancelib.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "instancelib.h" diff --git a/libs/instancelib.h b/libs/instancelib.h index 9ff32e6d..913288b6 100644 --- a/libs/instancelib.h +++ b/libs/instancelib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_INSTANCELIB_H) +#if !defined ( INCLUDED_INSTANCELIB_H ) #define INCLUDED_INSTANCELIB_H #include "debugging/debugging.h" @@ -33,161 +33,143 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class InstanceSubgraphWalker : public scene::Traversable::Walker { - scene::Instantiable::Observer* m_observer; - mutable scene::Path m_path; - mutable Stack m_parent; +scene::Instantiable::Observer* m_observer; +mutable scene::Path m_path; +mutable Stack m_parent; public: - InstanceSubgraphWalker(scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* parent) - : m_observer(observer), m_path(path), m_parent(parent) - { - } - bool pre(scene::Node& node) const - { - m_path.push(makeReference(node)); - scene::Instance* instance = Node_getInstantiable(node)->create(m_path, m_parent.top()); - m_observer->insert(instance); - Node_getInstantiable(node)->insert(m_observer, m_path, instance); - m_parent.push(instance); - return true; - } - void post(scene::Node& node) const - { - m_path.pop(); - m_parent.pop(); - } +InstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* parent ) + : m_observer( observer ), m_path( path ), m_parent( parent ){ +} +bool pre( scene::Node& node ) const { + m_path.push( makeReference( node ) ); + scene::Instance* instance = Node_getInstantiable( node )->create( m_path, m_parent.top() ); + m_observer->insert( instance ); + Node_getInstantiable( node )->insert( m_observer, m_path, instance ); + m_parent.push( instance ); + return true; +} +void post( scene::Node& node ) const { + m_path.pop(); + m_parent.pop(); +} }; class UninstanceSubgraphWalker : public scene::Traversable::Walker { - scene::Instantiable::Observer* m_observer; - mutable scene::Path m_path; +scene::Instantiable::Observer* m_observer; +mutable scene::Path m_path; public: - UninstanceSubgraphWalker(scene::Instantiable::Observer* observer, const scene::Path& parent) - : m_observer(observer), m_path(parent) - { - } - bool pre(scene::Node& node) const - { - m_path.push(makeReference(node)); - return true; - } - void post(scene::Node& node) const - { - scene::Instance* instance = Node_getInstantiable(node)->erase(m_observer, m_path); - m_observer->erase(instance); - delete instance; - m_path.pop(); - } +UninstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& parent ) + : m_observer( observer ), m_path( parent ){ +} +bool pre( scene::Node& node ) const { + m_path.push( makeReference( node ) ); + return true; +} +void post( scene::Node& node ) const { + scene::Instance* instance = Node_getInstantiable( node )->erase( m_observer, m_path ); + m_observer->erase( instance ); + delete instance; + m_path.pop(); +} }; class InstanceSet : public scene::Traversable::Observer { - typedef std::pair CachePath; +typedef std::pair CachePath; - typedef CachePath key_type; +typedef CachePath key_type; - typedef std::map InstanceMap; - InstanceMap m_instances; +typedef std::map InstanceMap; +InstanceMap m_instances; public: - typedef InstanceMap::iterator iterator; - - iterator begin() - { - return m_instances.begin(); - } - iterator end() - { - return m_instances.end(); - } - - // traverse observer - void insert(scene::Node& child) - { - for(iterator i = begin(); i != end(); ++i) - { - Node_traverseSubgraph(child, InstanceSubgraphWalker((*i).first.first, (*i).first.second, (*i).second)); - (*i).second->boundsChanged(); - } - } - void erase(scene::Node& child) - { - for(iterator i = begin(); i != end(); ++i) - { - Node_traverseSubgraph(child, UninstanceSubgraphWalker((*i).first.first, (*i).first.second)); - (*i).second->boundsChanged(); - } - } - - // instance - void forEachInstance(const scene::Instantiable::Visitor& visitor) - { - for(iterator i = begin(); i != end(); ++i) - { - visitor.visit(*(*i).second); - } - } - - void insert(scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance) - { - ASSERT_MESSAGE(m_instances.find(key_type(observer, PathConstReference(instance->path()))) == m_instances.end(), "InstanceSet::insert - element already exists"); - m_instances.insert(InstanceMap::value_type(key_type(observer, PathConstReference(instance->path())), instance)); - } - scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) - { - ASSERT_MESSAGE(m_instances.find(key_type(observer, PathConstReference(path))) != m_instances.end(), "InstanceSet::erase - failed to find element"); - InstanceMap::iterator i = m_instances.find(key_type(observer, PathConstReference(path))); - scene::Instance* instance = i->second; - m_instances.erase(i); - return instance; - } - - void transformChanged() - { - for(InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i) - { - (*i).second->transformChanged(); - } - } - typedef MemberCaller TransformChangedCaller; - void boundsChanged() - { - for(InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i) - { - (*i).second->boundsChanged(); - } - } - typedef MemberCaller BoundsChangedCaller; +typedef InstanceMap::iterator iterator; + +iterator begin(){ + return m_instances.begin(); +} +iterator end(){ + return m_instances.end(); +} + +// traverse observer +void insert( scene::Node& child ){ + for ( iterator i = begin(); i != end(); ++i ) + { + Node_traverseSubgraph( child, InstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second, ( *i ).second ) ); + ( *i ).second->boundsChanged(); + } +} +void erase( scene::Node& child ){ + for ( iterator i = begin(); i != end(); ++i ) + { + Node_traverseSubgraph( child, UninstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second ) ); + ( *i ).second->boundsChanged(); + } +} + +// instance +void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + for ( iterator i = begin(); i != end(); ++i ) + { + visitor.visit( *( *i ).second ); + } +} + +void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + ASSERT_MESSAGE( m_instances.find( key_type( observer, PathConstReference( instance->path() ) ) ) == m_instances.end(), "InstanceSet::insert - element already exists" ); + m_instances.insert( InstanceMap::value_type( key_type( observer, PathConstReference( instance->path() ) ), instance ) ); +} +scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + ASSERT_MESSAGE( m_instances.find( key_type( observer, PathConstReference( path ) ) ) != m_instances.end(), "InstanceSet::erase - failed to find element" ); + InstanceMap::iterator i = m_instances.find( key_type( observer, PathConstReference( path ) ) ); + scene::Instance* instance = i->second; + m_instances.erase( i ); + return instance; +} + +void transformChanged(){ + for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) + { + ( *i ).second->transformChanged(); + } +} +typedef MemberCaller TransformChangedCaller; +void boundsChanged(){ + for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) + { + ( *i ).second->boundsChanged(); + } +} +typedef MemberCaller BoundsChangedCaller; }; template -inline void InstanceSet_forEach(InstanceSet& instances, const Functor& functor) -{ - for(InstanceSet::iterator i = instances.begin(), end = instances.end(); i != end; ++i) - { - functor(*(*i).second); - } +inline void InstanceSet_forEach( InstanceSet& instances, const Functor& functor ){ + for ( InstanceSet::iterator i = instances.begin(), end = instances.end(); i != end; ++i ) + { + functor( *( *i ).second ); + } } template class InstanceEvaluateTransform { public: - inline void operator()(scene::Instance& instance) const - { - InstanceTypeCast::cast(instance)->evaluateTransform(); - } +inline void operator()( scene::Instance& instance ) const { + InstanceTypeCast::cast( instance )->evaluateTransform(); +} }; template class InstanceSetEvaluateTransform { public: - static void apply(InstanceSet& instances) - { - InstanceSet_forEach(instances, InstanceEvaluateTransform()); - } - typedef ReferenceCaller::apply> Caller; +static void apply( InstanceSet& instances ){ + InstanceSet_forEach( instances, InstanceEvaluateTransform() ); +} +typedef ReferenceCaller::apply> Caller; }; #endif diff --git a/libs/l_net/l_net.c b/libs/l_net/l_net.c index ca730d03..caf6c422 100644 --- a/libs/l_net/l_net.c +++ b/libs/l_net/l_net.c @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //==================================================================== // @@ -39,24 +39,22 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #define GetMemory malloc #define FreeMemory free -#define qtrue 1 -#define qfalse 0 +#define qtrue 1 +#define qfalse 0 #ifdef _DEBUG -void WinPrint(const char *str, ...) -{ +void WinPrint( const char *str, ... ){ va_list argptr; - char text[4096]; + char text[4096]; - va_start (argptr,str); - vsprintf (text, str, argptr); - va_end (argptr); + va_start( argptr,str ); + vsprintf( text, str, argptr ); + va_end( argptr ); - printf(text); + printf( text ); } #else -void WinPrint(const char *str, ...) -{ +void WinPrint( const char *str, ... ){ } #endif @@ -66,13 +64,12 @@ void WinPrint(const char *str, ...) // Returns: - // Changes Globals: - //=========================================================================== -void Net_SetAddressPort(address_t *address, int port) -{ +void Net_SetAddressPort( address_t *address, int port ){ sockaddr_t addr; - WINS_StringToAddr(address->ip, &addr); - WINS_SetSocketPort(&addr, port); - strcpy(address->ip, WINS_AddrToString(&addr)); + WINS_StringToAddr( address->ip, &addr ); + WINS_SetSocketPort( &addr, port ); + strcpy( address->ip, WINS_AddrToString( &addr ) ); } //end of the function Net_SetAddressPort //=========================================================================== // @@ -80,12 +77,11 @@ void Net_SetAddressPort(address_t *address, int port) // Returns: - // Changes Globals: - //=========================================================================== -int Net_AddressCompare(address_t *addr1, address_t *addr2) -{ +int Net_AddressCompare( address_t *addr1, address_t *addr2 ){ #ifdef WIN32 - return _stricmp(addr1->ip, addr2->ip); + return _stricmp( addr1->ip, addr2->ip ); #else - return strcasecmp(addr1->ip, addr2->ip); + return strcasecmp( addr1->ip, addr2->ip ); #endif } //end of the function Net_AddressCompare //=========================================================================== @@ -94,9 +90,8 @@ int Net_AddressCompare(address_t *addr1, address_t *addr2) // Returns: - // Changes Globals: - //=========================================================================== -void Net_SocketToAddress(socket_t *sock, address_t *address) -{ - strcpy(address->ip, WINS_AddrToString(&sock->addr)); +void Net_SocketToAddress( socket_t *sock, address_t *address ){ + strcpy( address->ip, WINS_AddrToString( &sock->addr ) ); } //end of the function Net_SocketToAddress //=========================================================================== // @@ -104,16 +99,15 @@ void Net_SocketToAddress(socket_t *sock, address_t *address) // Returns: - // Changes Globals: - //=========================================================================== -int Net_Send(socket_t *sock, netmessage_t *msg) -{ +int Net_Send( socket_t *sock, netmessage_t *msg ){ int size; size = msg->size; msg->size = 0; - NMSG_WriteLong(msg, size-4); + NMSG_WriteLong( msg, size - 4 ); msg->size = size; //WinPrint("Net_Send: message of size %d\n", sendmsg.size); - return WINS_Write(sock->socket, msg->data, msg->size, NULL); + return WINS_Write( sock->socket, msg->data, msg->size, NULL ); } //end of the function Net_SendSocketReliable //=========================================================================== // returns the number of bytes recieved @@ -123,64 +117,60 @@ int Net_Send(socket_t *sock, netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -int Net_Receive(socket_t *sock, netmessage_t *msg) -{ +int Net_Receive( socket_t *sock, netmessage_t *msg ){ int curread; - if (sock->remaining > 0) - { - curread = WINS_Read(sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL); - if (curread == -1) - { - WinPrint("Net_Receive: read error\n"); + if ( sock->remaining > 0 ) { + curread = WINS_Read( sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL ); + if ( curread == -1 ) { + WinPrint( "Net_Receive: read error\n" ); return -1; } //end if sock->remaining -= curread; sock->msg.size += curread; - if (sock->remaining <= 0) - { + if ( sock->remaining <= 0 ) { sock->remaining = 0; - memcpy(msg, &sock->msg, sizeof(netmessage_t)); + memcpy( msg, &sock->msg, sizeof( netmessage_t ) ); sock->msg.size = 0; return msg->size - 4; } //end if return 0; } //end if - sock->msg.size = WINS_Read(sock->socket, sock->msg.data, 4, NULL); - if (sock->msg.size == 0) return 0; - if (sock->msg.size == -1) - { - WinPrint("Net_Receive: size header read error\n"); + sock->msg.size = WINS_Read( sock->socket, sock->msg.data, 4, NULL ); + if ( sock->msg.size == 0 ) { + return 0; + } + if ( sock->msg.size == -1 ) { + WinPrint( "Net_Receive: size header read error\n" ); return -1; } //end if - //WinPrint("Net_Receive: message size header %d\n", msg->size); + //WinPrint("Net_Receive: message size header %d\n", msg->size); sock->msg.read = 0; - sock->remaining = NMSG_ReadLong(&sock->msg); - if (sock->remaining == 0) return 0; - if (sock->remaining < 0 || sock->remaining > MAX_NETMESSAGE) - { - WinPrint("Net_Receive: invalid message size %d\n", sock->remaining); + sock->remaining = NMSG_ReadLong( &sock->msg ); + if ( sock->remaining == 0 ) { + return 0; + } + if ( sock->remaining < 0 || sock->remaining > MAX_NETMESSAGE ) { + WinPrint( "Net_Receive: invalid message size %d\n", sock->remaining ); return -1; } //end if - //try to read the message - curread = WINS_Read(sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL); - if (curread == -1) - { - WinPrint("Net_Receive: read error\n"); + //try to read the message + curread = WINS_Read( sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL ); + if ( curread == -1 ) { + WinPrint( "Net_Receive: read error\n" ); return -1; } //end if sock->remaining -= curread; sock->msg.size += curread; - if (sock->remaining <= 0) - { + if ( sock->remaining <= 0 ) { sock->remaining = 0; - memcpy(msg, &sock->msg, sizeof(netmessage_t)); + memcpy( msg, &sock->msg, sizeof( netmessage_t ) ); sock->msg.size = 0; return msg->size - 4; } //end if - //the message has not been completely read yet + //the message has not been completely read yet #ifdef _DEBUG - printf("++timo TODO: debug the Net_Receive on big size messages\n"); + printf( "++timo TODO: debug the Net_Receive on big size messages\n" ); #endif return 0; } //end of the function Net_Receive @@ -190,12 +180,11 @@ int Net_Receive(socket_t *sock, netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -socket_t *Net_AllocSocket(void) -{ +socket_t *Net_AllocSocket( void ){ socket_t *sock; - sock = (socket_t *) GetMemory(sizeof(socket_t)); - memset(sock, 0, sizeof(socket_t)); + sock = (socket_t *) GetMemory( sizeof( socket_t ) ); + memset( sock, 0, sizeof( socket_t ) ); return sock; } //end of the function Net_AllocSocket //=========================================================================== @@ -204,9 +193,8 @@ socket_t *Net_AllocSocket(void) // Returns: - // Changes Globals: - //=========================================================================== -void Net_FreeSocket(socket_t *sock) -{ - FreeMemory(sock); +void Net_FreeSocket( socket_t *sock ){ + FreeMemory( sock ); } //end of the function Net_FreeSocket //=========================================================================== // @@ -214,36 +202,35 @@ void Net_FreeSocket(socket_t *sock) // Returns: - // Changes Globals: - //=========================================================================== -socket_t *Net_Connect(address_t *address, int port) -{ +socket_t *Net_Connect( address_t *address, int port ){ int newsock; socket_t *sock; sockaddr_t sendaddr; // see if we can resolve the host name - WINS_StringToAddr(address->ip, &sendaddr); + WINS_StringToAddr( address->ip, &sendaddr ); - newsock = WINS_OpenReliableSocket(port); - if (newsock == -1) return NULL; + newsock = WINS_OpenReliableSocket( port ); + if ( newsock == -1 ) { + return NULL; + } sock = Net_AllocSocket(); - if (sock == NULL) - { - WINS_CloseSocket(newsock); + if ( sock == NULL ) { + WINS_CloseSocket( newsock ); return NULL; } //end if sock->socket = newsock; //connect to the host - if (WINS_Connect(newsock, &sendaddr) == -1) - { - Net_FreeSocket(sock); - WINS_CloseSocket(newsock); - WinPrint("Net_Connect: error connecting\n"); + if ( WINS_Connect( newsock, &sendaddr ) == -1 ) { + Net_FreeSocket( sock ); + WINS_CloseSocket( newsock ); + WinPrint( "Net_Connect: error connecting\n" ); return NULL; } //end if - memcpy(&sock->addr, &sendaddr, sizeof(sockaddr_t)); + memcpy( &sock->addr, &sendaddr, sizeof( sockaddr_t ) ); //now we can send messages // return sock; @@ -255,28 +242,27 @@ socket_t *Net_Connect(address_t *address, int port) // Returns: - // Changes Globals: - //=========================================================================== -socket_t *Net_ListenSocket(int port) -{ +socket_t *Net_ListenSocket( int port ){ int newsock; socket_t *sock; - newsock = WINS_OpenReliableSocket(port); - if (newsock == -1) return NULL; + newsock = WINS_OpenReliableSocket( port ); + if ( newsock == -1 ) { + return NULL; + } - if (WINS_Listen(newsock) == -1) - { - WINS_CloseSocket(newsock); + if ( WINS_Listen( newsock ) == -1 ) { + WINS_CloseSocket( newsock ); return NULL; } //end if sock = Net_AllocSocket(); - if (sock == NULL) - { - WINS_CloseSocket(newsock); + if ( sock == NULL ) { + WINS_CloseSocket( newsock ); return NULL; } //end if sock->socket = newsock; - WINS_GetSocketAddr(newsock, &sock->addr); - WinPrint("listen socket opened at %s\n", WINS_AddrToString(&sock->addr)); + WINS_GetSocketAddr( newsock, &sock->addr ); + WinPrint( "listen socket opened at %s\n", WINS_AddrToString( &sock->addr ) ); // return sock; } //end of the function Net_ListenSocket @@ -286,23 +272,23 @@ socket_t *Net_ListenSocket(int port) // Returns: - // Changes Globals: - //=========================================================================== -socket_t *Net_Accept(socket_t *sock) -{ +socket_t *Net_Accept( socket_t *sock ){ int newsocket; sockaddr_t sendaddr; socket_t *newsock; - newsocket = WINS_Accept(sock->socket, &sendaddr); - if (newsocket == -1) return NULL; + newsocket = WINS_Accept( sock->socket, &sendaddr ); + if ( newsocket == -1 ) { + return NULL; + } newsock = Net_AllocSocket(); - if (newsock == NULL) - { - WINS_CloseSocket(newsocket); + if ( newsock == NULL ) { + WINS_CloseSocket( newsocket ); return NULL; } //end if newsock->socket = newsocket; - memcpy(&newsock->addr, &sendaddr, sizeof(sockaddr_t)); + memcpy( &newsock->addr, &sendaddr, sizeof( sockaddr_t ) ); // return newsock; } //end of the function Net_Accept @@ -312,10 +298,9 @@ socket_t *Net_Accept(socket_t *sock) // Returns: - // Changes Globals: - //=========================================================================== -void Net_Disconnect(socket_t *sock) -{ - WINS_CloseSocket(sock->socket); - Net_FreeSocket(sock); +void Net_Disconnect( socket_t *sock ){ + WINS_CloseSocket( sock->socket ); + Net_FreeSocket( sock ); } //end of the function Net_Disconnect //=========================================================================== // @@ -323,9 +308,8 @@ void Net_Disconnect(socket_t *sock) // Returns: - // Changes Globals: - //=========================================================================== -void Net_StringToAddress(const char *string, address_t *address) -{ - strcpy(address->ip, string); +void Net_StringToAddress( const char *string, address_t *address ){ + strcpy( address->ip, string ); } //end of the function Net_StringToAddress //=========================================================================== // @@ -333,9 +317,8 @@ void Net_StringToAddress(const char *string, address_t *address) // Returns: - // Changes Globals: - //=========================================================================== -void Net_MyAddress(address_t *address) -{ - strcpy(address->ip, WINS_MyAddress()); +void Net_MyAddress( address_t *address ){ + strcpy( address->ip, WINS_MyAddress() ); } //end of the function Net_MyAddress //=========================================================================== // @@ -343,11 +326,10 @@ void Net_MyAddress(address_t *address) // Returns: - // Changes Globals: - //=========================================================================== -int Net_Setup(void) -{ +int Net_Setup( void ){ WINS_Init(); // - WinPrint("my address is %s\n", WINS_MyAddress()); + WinPrint( "my address is %s\n", WINS_MyAddress() ); // return qtrue; } //end of the function Net_Setup @@ -357,8 +339,7 @@ int Net_Setup(void) // Returns: - // Changes Globals: - //=========================================================================== -void Net_Shutdown(void) -{ +void Net_Shutdown( void ){ WINS_Shutdown(); } //end of the function Net_Shutdown //=========================================================================== @@ -367,8 +348,7 @@ void Net_Shutdown(void) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_Clear(netmessage_t *msg) -{ +void NMSG_Clear( netmessage_t *msg ){ msg->size = 4; } //end of the function NMSG_Clear //=========================================================================== @@ -377,14 +357,13 @@ void NMSG_Clear(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteChar (netmessage_t *msg, int c) -{ - if (c < -128 || c > 127) - WinPrint("NMSG_WriteChar: range error\n"); +void NMSG_WriteChar( netmessage_t *msg, int c ){ + if ( c < -128 || c > 127 ) { + WinPrint( "NMSG_WriteChar: range error\n" ); + } - if (msg->size >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteChar: overflow\n"); + if ( msg->size >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteChar: overflow\n" ); return; } //end if msg->data[msg->size] = c; @@ -396,14 +375,13 @@ void NMSG_WriteChar (netmessage_t *msg, int c) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteByte(netmessage_t *msg, int c) -{ - if (c < -128 || c > 127) - WinPrint("NMSG_WriteByte: range error\n"); +void NMSG_WriteByte( netmessage_t *msg, int c ){ + if ( c < -128 || c > 127 ) { + WinPrint( "NMSG_WriteByte: range error\n" ); + } - if (msg->size + 1 >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteByte: overflow\n"); + if ( msg->size + 1 >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteByte: overflow\n" ); return; } //end if msg->data[msg->size] = c; @@ -415,18 +393,17 @@ void NMSG_WriteByte(netmessage_t *msg, int c) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteShort(netmessage_t *msg, int c) -{ - if (c < ((short)0x8000) || c > (short)0x7fff) - WinPrint("NMSG_WriteShort: range error"); +void NMSG_WriteShort( netmessage_t *msg, int c ){ + if ( c < ( (short)0x8000 ) || c > (short)0x7fff ) { + WinPrint( "NMSG_WriteShort: range error" ); + } - if (msg->size + 2 >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteShort: overflow\n"); + if ( msg->size + 2 >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteShort: overflow\n" ); return; } //end if - msg->data[msg->size] = c&0xff; - msg->data[msg->size+1] = c>>8; + msg->data[msg->size] = c & 0xff; + msg->data[msg->size + 1] = c >> 8; msg->size += 2; } //end of the function NMSG_WriteShort //=========================================================================== @@ -435,17 +412,15 @@ void NMSG_WriteShort(netmessage_t *msg, int c) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteLong(netmessage_t *msg, int c) -{ - if (msg->size + 4 >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteLong: overflow\n"); +void NMSG_WriteLong( netmessage_t *msg, int c ){ + if ( msg->size + 4 >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteLong: overflow\n" ); return; } //end if - msg->data[msg->size] = c&0xff; - msg->data[msg->size+1] = (c>>8)&0xff; - msg->data[msg->size+2] = (c>>16)&0xff; - msg->data[msg->size+3] = c>>24; + msg->data[msg->size] = c & 0xff; + msg->data[msg->size + 1] = ( c >> 8 ) & 0xff; + msg->data[msg->size + 2] = ( c >> 16 ) & 0xff; + msg->data[msg->size + 3] = c >> 24; msg->size += 4; } //end of the function NMSG_WriteLong //=========================================================================== @@ -454,17 +429,15 @@ void NMSG_WriteLong(netmessage_t *msg, int c) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteFloat(netmessage_t *msg, float c) -{ - if (msg->size + 4 >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteLong: overflow\n"); +void NMSG_WriteFloat( netmessage_t *msg, float c ){ + if ( msg->size + 4 >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteLong: overflow\n" ); return; } //end if - msg->data[msg->size] = *((int *)&c)&0xff; - msg->data[msg->size+1] = (*((int *)&c)>>8)&0xff; - msg->data[msg->size+2] = (*((int *)&c)>>16)&0xff; - msg->data[msg->size+3] = *((int *)&c)>>24; + msg->data[msg->size] = *( (int *)&c ) & 0xff; + msg->data[msg->size + 1] = ( *( (int *)&c ) >> 8 ) & 0xff; + msg->data[msg->size + 2] = ( *( (int *)&c ) >> 16 ) & 0xff; + msg->data[msg->size + 3] = *( (int *)&c ) >> 24; msg->size += 4; } //end of the function NMSG_WriteFloat //=========================================================================== @@ -473,15 +446,13 @@ void NMSG_WriteFloat(netmessage_t *msg, float c) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_WriteString(netmessage_t *msg, char *string) -{ - if (msg->size + strlen(string) + 1 >= MAX_NETMESSAGE) - { - WinPrint("NMSG_WriteString: overflow\n"); +void NMSG_WriteString( netmessage_t *msg, char *string ){ + if ( msg->size + strlen( string ) + 1 >= MAX_NETMESSAGE ) { + WinPrint( "NMSG_WriteString: overflow\n" ); return; } //end if - memcpy(&msg->data[msg->size], string, strlen(string) + 1); - msg->size += strlen(string) + 1; + memcpy( &msg->data[msg->size], string, strlen( string ) + 1 ); + msg->size += strlen( string ) + 1; } //end of the function NMSG_WriteString //=========================================================================== // @@ -489,8 +460,7 @@ void NMSG_WriteString(netmessage_t *msg, char *string) // Returns: - // Changes Globals: - //=========================================================================== -void NMSG_ReadStart(netmessage_t *msg) -{ +void NMSG_ReadStart( netmessage_t *msg ){ msg->readoverflow = qfalse; msg->read = 4; } //end of the function NMSG_ReadStart @@ -500,16 +470,14 @@ void NMSG_ReadStart(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -int NMSG_ReadChar(netmessage_t *msg) -{ - if (msg->read + 1 > msg->size) - { +int NMSG_ReadChar( netmessage_t *msg ){ + if ( msg->read + 1 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadChar: read overflow\n"); + WinPrint( "NMSG_ReadChar: read overflow\n" ); return 0; } //end if msg->read++; - return msg->data[msg->read-1]; + return msg->data[msg->read - 1]; } //end of the function NMSG_ReadChar //=========================================================================== // @@ -517,16 +485,14 @@ int NMSG_ReadChar(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -int NMSG_ReadByte(netmessage_t *msg) -{ - if (msg->read + 1 > msg->size) - { +int NMSG_ReadByte( netmessage_t *msg ){ + if ( msg->read + 1 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadByte: read overflow\n"); + WinPrint( "NMSG_ReadByte: read overflow\n" ); return 0; } //end if msg->read++; - return msg->data[msg->read-1]; + return msg->data[msg->read - 1]; } //end of the function NMSG_ReadByte //=========================================================================== // @@ -534,17 +500,15 @@ int NMSG_ReadByte(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -int NMSG_ReadShort(netmessage_t *msg) -{ +int NMSG_ReadShort( netmessage_t *msg ){ int c; - if (msg->read + 2 > msg->size) - { + if ( msg->read + 2 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadShort: read overflow\n"); + WinPrint( "NMSG_ReadShort: read overflow\n" ); return 0; } //end if - c = (short)(msg->data[msg->read] + (msg->data[msg->read+1]<<8)); + c = (short)( msg->data[msg->read] + ( msg->data[msg->read + 1] << 8 ) ); msg->read += 2; return c; } //end of the function NMSG_ReadShort @@ -554,20 +518,18 @@ int NMSG_ReadShort(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -int NMSG_ReadLong(netmessage_t *msg) -{ +int NMSG_ReadLong( netmessage_t *msg ){ int c; - if (msg->read + 4 > msg->size) - { + if ( msg->read + 4 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadLong: read overflow\n"); + WinPrint( "NMSG_ReadLong: read overflow\n" ); return 0; } //end if c = msg->data[msg->read] - + (msg->data[msg->read+1]<<8) - + (msg->data[msg->read+2]<<16) - + (msg->data[msg->read+3]<<24); + + ( msg->data[msg->read + 1] << 8 ) + + ( msg->data[msg->read + 2] << 16 ) + + ( msg->data[msg->read + 3] << 24 ); msg->read += 4; return c; } //end of the function NMSG_ReadLong @@ -577,20 +539,18 @@ int NMSG_ReadLong(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -float NMSG_ReadFloat(netmessage_t *msg) -{ +float NMSG_ReadFloat( netmessage_t *msg ){ int c; - if (msg->read + 4 > msg->size) - { + if ( msg->read + 4 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadLong: read overflow\n"); + WinPrint( "NMSG_ReadLong: read overflow\n" ); return 0; } //end if c = msg->data[msg->read] - + (msg->data[msg->read+1]<<8) - + (msg->data[msg->read+2]<<16) - + (msg->data[msg->read+3]<<24); + + ( msg->data[msg->read + 1] << 8 ) + + ( msg->data[msg->read + 2] << 16 ) + + ( msg->data[msg->read + 3] << 24 ); msg->read += 4; return *(float *)&c; } //end of the function NMSG_ReadFloat @@ -600,27 +560,27 @@ float NMSG_ReadFloat(netmessage_t *msg) // Returns: - // Changes Globals: - //=========================================================================== -char *NMSG_ReadString(netmessage_t *msg) -{ - static char string[2048]; +char *NMSG_ReadString( netmessage_t *msg ){ + static char string[2048]; int l, c; - + l = 0; do { - if (msg->read + 1 > msg->size) - { + if ( msg->read + 1 > msg->size ) { msg->readoverflow = qtrue; - WinPrint("NMSG_ReadString: read overflow\n"); + WinPrint( "NMSG_ReadString: read overflow\n" ); string[l] = 0; return string; } //end if c = msg->data[msg->read]; msg->read++; - if (c == 0) break; + if ( c == 0 ) { + break; + } string[l] = c; l++; - } while ((size_t) l < sizeof(string)-1); + } while ( (size_t) l < sizeof( string ) - 1 ); string[l] = 0; return string; } //end of the function NMSG_ReadString diff --git a/libs/l_net/l_net.h b/libs/l_net/l_net.h index 6c548334..120201b3 100644 --- a/libs/l_net/l_net.h +++ b/libs/l_net/l_net.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //==================================================================== // @@ -32,8 +32,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA //++timo FIXME: the l_net code understands that as the max size for the netmessage_s structure // we have defined unsigned char data[MAX_NETMESSAGE] in netmessage_s but actually it cannot be filled completely // we need to introduce a new #define and adapt to data[MAX_NETBUFFER] -#define MAX_NETMESSAGE 1024 -#define MAX_NETADDRESS 32 +#define MAX_NETMESSAGE 1024 +#define MAX_NETADDRESS 32 #ifdef __cplusplus extern "C" { @@ -66,61 +66,61 @@ typedef struct netmessage_s typedef struct socket_s { - int socket; //socket number - sockaddr_t addr; //socket address - netmessage_t msg; //current message being read - int remaining; //remaining bytes to read for the current message - struct socket_s *prev, *next; //prev and next socket in a list + int socket; //socket number + sockaddr_t addr; //socket address + netmessage_t msg; //current message being read + int remaining; //remaining bytes to read for the current message + struct socket_s *prev, *next; //prev and next socket in a list } socket_t; -void WinPrint(const char *format, ...); +void WinPrint( const char *format, ... ); //compare addresses -int Net_AddressCompare(address_t *addr1, address_t *addr2); +int Net_AddressCompare( address_t *addr1, address_t *addr2 ); //gives the address of a socket -void Net_SocketToAddress(socket_t *sock, address_t *address); +void Net_SocketToAddress( socket_t *sock, address_t *address ); //converts a string to an address -void Net_StringToAddress(const char *string, address_t *address); +void Net_StringToAddress( const char *string, address_t *address ); //set the address ip port -void Net_SetAddressPort(address_t *address, int port); +void Net_SetAddressPort( address_t *address, int port ); //send a message to the given socket -int Net_Send(socket_t *sock, netmessage_t *msg); +int Net_Send( socket_t *sock, netmessage_t *msg ); //recieve a message from the given socket -int Net_Receive(socket_t *sock, netmessage_t *msg); +int Net_Receive( socket_t *sock, netmessage_t *msg ); //connect to a host // NOTE: port is the localhost port, usually 0 // ex: Net_Connect( "192.168.0.1:39000", 0 ) -socket_t *Net_Connect(address_t *address, int port); +socket_t *Net_Connect( address_t *address, int port ); //disconnect from a host -void Net_Disconnect(socket_t *sock); +void Net_Disconnect( socket_t *sock ); //returns the local address -void Net_MyAddress(address_t *address); +void Net_MyAddress( address_t *address ); //listen at the given port -socket_t *Net_ListenSocket(int port); +socket_t *Net_ListenSocket( int port ); //accept new connections at the given socket -socket_t *Net_Accept(socket_t *sock); +socket_t *Net_Accept( socket_t *sock ); //setup networking -int Net_Setup(void); +int Net_Setup( void ); //shutdown networking -void Net_Shutdown(void); +void Net_Shutdown( void ); //message handling -void NMSG_Clear(netmessage_t *msg); -void NMSG_WriteChar(netmessage_t *msg, int c); -void NMSG_WriteByte(netmessage_t *msg, int c); -void NMSG_WriteShort(netmessage_t *msg, int c); -void NMSG_WriteLong(netmessage_t *msg, int c); -void NMSG_WriteFloat(netmessage_t *msg, float c); -void NMSG_WriteString(netmessage_t *msg, char *string); -void NMSG_ReadStart(netmessage_t *msg); -int NMSG_ReadChar(netmessage_t *msg); -int NMSG_ReadByte(netmessage_t *msg); -int NMSG_ReadShort(netmessage_t *msg); -int NMSG_ReadLong(netmessage_t *msg); -float NMSG_ReadFloat(netmessage_t *msg); -char *NMSG_ReadString(netmessage_t *msg); +void NMSG_Clear( netmessage_t *msg ); +void NMSG_WriteChar( netmessage_t *msg, int c ); +void NMSG_WriteByte( netmessage_t *msg, int c ); +void NMSG_WriteShort( netmessage_t *msg, int c ); +void NMSG_WriteLong( netmessage_t *msg, int c ); +void NMSG_WriteFloat( netmessage_t *msg, float c ); +void NMSG_WriteString( netmessage_t *msg, char *string ); +void NMSG_ReadStart( netmessage_t *msg ); +int NMSG_ReadChar( netmessage_t *msg ); +int NMSG_ReadByte( netmessage_t *msg ); +int NMSG_ReadShort( netmessage_t *msg ); +int NMSG_ReadLong( netmessage_t *msg ); +float NMSG_ReadFloat( netmessage_t *msg ); +char *NMSG_ReadString( netmessage_t *msg ); //++timo FIXME: the WINS_ things are not necessary, they can be made portable arther easily -const char *WINS_ErrorMessage(int error); +const char *WINS_ErrorMessage( int error ); #ifdef __cplusplus } diff --git a/libs/l_net/l_net_berkley.c b/libs/l_net/l_net_berkley.c index edc06fa1..7e5a50e0 100644 --- a/libs/l_net/l_net_berkley.c +++ b/libs/l_net/l_net_berkley.c @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //=========================================================================== // @@ -52,42 +52,41 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #define WinError WinPrint -#define qtrue 1 -#define qfalse 0 +#define qtrue 1 +#define qfalse 0 #define ioctlsocket ioctl #define closesocket close -int WSAGetLastError() -{ +int WSAGetLastError(){ return errno; } /* -typedef struct tag_error_struct -{ + typedef struct tag_error_struct + { int errnum; LPSTR errstr; -} ERROR_STRUCT; -*/ + } ERROR_STRUCT; + */ typedef struct tag_error_struct { - int errnum; - const char *errstr; + int errnum; + const char *errstr; } ERROR_STRUCT; -#define NET_NAMELEN 64 +#define NET_NAMELEN 64 static char my_tcpip_address[NET_NAMELEN]; -#define DEFAULTnet_hostport 26000 +#define DEFAULTnet_hostport 26000 -#define MAXHOSTNAMELEN 256 +#define MAXHOSTNAMELEN 256 -static int net_acceptsocket = -1; // socket for fielding new connections +static int net_acceptsocket = -1; // socket for fielding new connections static int net_controlsocket; -static int net_hostport; // udp port number for acceptsocket +static int net_hostport; // udp port number for acceptsocket static int net_broadcastsocket = 0; //static qboolean ifbcastinit = qfalse; //static struct sockaddr_s broadcastaddr; @@ -96,18 +95,18 @@ static struct sockaddr_s broadcastaddr; static unsigned long myAddr; ERROR_STRUCT errlist[] = { - {EACCES,"EACCES - The address is protected, user is not root"}, - {EAGAIN,"EAGAIN - Operation on non-blocking socket that cannot return immediatly"}, - {EBADF, "EBADF - sockfd is not a valid descriptor"}, - {EFAULT, "EFAULT - The parameter is not in a writable part of the user address space"}, - {EINVAL,"EINVAL - The socket is already bound to an address"}, - {ENOBUFS,"ENOBUFS - not enough memory"}, - {ENOMEM, "ENOMEM - not enough memory"}, - {ENOTCONN, "ENOTCONN - not connected"}, - {ENOTSOCK,"ENOTSOCK - Argument is file descriptor not a socket"}, - {EOPNOTSUPP,"ENOTSUPP - The referenced socket is not of type SOCK_STREAM"}, - {EPERM, "EPERM - Firewall rules forbid connection"}, - {-1, NULL} + {EACCES,"EACCES - The address is protected, user is not root"}, + {EAGAIN,"EAGAIN - Operation on non-blocking socket that cannot return immediatly"}, + {EBADF, "EBADF - sockfd is not a valid descriptor"}, + {EFAULT, "EFAULT - The parameter is not in a writable part of the user address space"}, + {EINVAL,"EINVAL - The socket is already bound to an address"}, + {ENOBUFS,"ENOBUFS - not enough memory"}, + {ENOMEM, "ENOMEM - not enough memory"}, + {ENOTCONN, "ENOTCONN - not connected"}, + {ENOTSOCK,"ENOTSOCK - Argument is file descriptor not a socket"}, + {EOPNOTSUPP,"ENOTSUPP - The referenced socket is not of type SOCK_STREAM"}, + {EPERM, "EPERM - Firewall rules forbid connection"}, + {-1, NULL} }; //=========================================================================== @@ -116,19 +115,21 @@ ERROR_STRUCT errlist[] = { // Returns: - // Changes Globals: - //=========================================================================== -const char *WINS_ErrorMessage(int error) -{ - int search = 0; +const char *WINS_ErrorMessage( int error ){ + int search = 0; - if (!error) return "No error occurred"; + if ( !error ) { + return "No error occurred"; + } - for (search = 0; errlist[search].errstr; search++) - { - if (error == errlist[search].errnum) - return errlist[search].errstr; - } //end for + for ( search = 0; errlist[search].errstr; search++ ) + { + if ( error == errlist[search].errnum ) { + return errlist[search].errstr; + } + } //end for - return "Unknown error"; + return "Unknown error"; } //end of the function WINS_ErrorMessage //=========================================================================== // @@ -136,78 +137,80 @@ const char *WINS_ErrorMessage(int error) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Init(void) -{ - int i; +int WINS_Init( void ){ + int i; struct hostent *local; - char buff[MAXHOSTNAMELEN]; + char buff[MAXHOSTNAMELEN]; struct sockaddr_s addr; - char *p; -/* - linux doesn't have anything to initialize for the net - "Windows .. built for the internet .. the internet .. built with unix" + char *p; +/* + linux doesn't have anything to initialize for the net + "Windows .. built for the internet .. the internet .. built with unix" */ #if 0 - WORD wVersionRequested; + WORD wVersionRequested; - wVersionRequested = MAKEWORD(2, 2); + wVersionRequested = MAKEWORD( 2, 2 ); - r = WSAStartup (wVersionRequested, &winsockdata); + r = WSAStartup( wVersionRequested, &winsockdata ); - if (r) - { - WinPrint("Winsock initialization failed.\n"); + if ( r ) { + WinPrint( "Winsock initialization failed.\n" ); return -1; } #endif /* - i = COM_CheckParm ("-udpport"); - if (i == 0)*/ - net_hostport = DEFAULTnet_hostport; + i = COM_CheckParm ("-udpport"); + if (i == 0)*/ + net_hostport = DEFAULTnet_hostport; /* - else if (i < com_argc-1) - net_hostport = Q_atoi (com_argv[i+1]); - else - Sys_Error ("WINS_Init: you must specify a number after -udpport"); - */ + else if (i < com_argc-1) + net_hostport = Q_atoi (com_argv[i+1]); + else + Sys_Error ("WINS_Init: you must specify a number after -udpport"); + */ // determine my name & address - gethostname(buff, MAXHOSTNAMELEN); - local = gethostbyname(buff); + gethostname( buff, MAXHOSTNAMELEN ); + local = gethostbyname( buff ); myAddr = *(int *)local->h_addr_list[0]; // if the quake hostname isn't set, set it to the machine name // if (Q_strcmp(hostname.string, "UNNAMED") == 0) { // see if it's a text IP address (well, close enough) - for (p = buff; *p; p++) - if ((*p < '0' || *p > '9') && *p != '.') + for ( p = buff; *p; p++ ) + if ( ( *p < '0' || *p > '9' ) && *p != '.' ) { break; + } // if it is a real name, strip off the domain; we only want the host - if (*p) - { - for (i = 0; i < 15; i++) - if (buff[i] == '.') + if ( *p ) { + for ( i = 0; i < 15; i++ ) + if ( buff[i] == '.' ) { break; + } buff[i] = 0; } // Cvar_Set ("hostname", buff); } - //++timo WTF is that net_controlsocket? it's sole purpose is to retrieve the local IP? - if ((net_controlsocket = WINS_OpenSocket (0)) == SOCKET_ERROR) - WinError("WINS_Init: Unable to open control socket\n"); + //++timo WTF is that net_controlsocket? it's sole purpose is to retrieve the local IP? + if ( ( net_controlsocket = WINS_OpenSocket( 0 ) ) == SOCKET_ERROR ) { + WinError( "WINS_Init: Unable to open control socket\n" ); + } - ((struct sockaddr_in *)&broadcastaddr)->sin_family = AF_INET; - ((struct sockaddr_in *)&broadcastaddr)->sin_addr.s_addr = INADDR_BROADCAST; - ((struct sockaddr_in *)&broadcastaddr)->sin_port = htons((u_short)net_hostport); + ( (struct sockaddr_in *)&broadcastaddr )->sin_family = AF_INET; + ( (struct sockaddr_in *)&broadcastaddr )->sin_addr.s_addr = INADDR_BROADCAST; + ( (struct sockaddr_in *)&broadcastaddr )->sin_port = htons( (u_short)net_hostport ); - WINS_GetSocketAddr (net_controlsocket, &addr); - strcpy(my_tcpip_address, WINS_AddrToString (&addr)); - p = strrchr (my_tcpip_address, ':'); - if (p) *p = 0; - WinPrint("Winsock Initialized\n"); + WINS_GetSocketAddr( net_controlsocket, &addr ); + strcpy( my_tcpip_address, WINS_AddrToString( &addr ) ); + p = strrchr( my_tcpip_address, ':' ); + if ( p ) { + *p = 0; + } + WinPrint( "Winsock Initialized\n" ); return net_controlsocket; } //end of the function WINS_Init @@ -217,8 +220,7 @@ int WINS_Init(void) // Returns: - // Changes Globals: - //=========================================================================== -char *WINS_MyAddress(void) -{ +char *WINS_MyAddress( void ){ return my_tcpip_address; } //end of the function WINS_MyAddress //=========================================================================== @@ -227,10 +229,9 @@ char *WINS_MyAddress(void) // Returns: - // Changes Globals: - //=========================================================================== -void WINS_Shutdown(void) -{ +void WINS_Shutdown( void ){ //WINS_Listen(0); - WINS_CloseSocket(net_controlsocket); + WINS_CloseSocket( net_controlsocket ); // WSACleanup(); // //WinPrint("Winsock Shutdown\n"); @@ -242,57 +243,53 @@ void WINS_Shutdown(void) // Changes Globals: - //=========================================================================== /* -void WINS_Listen(int state) -{ - // enable listening - if (state) - { - if (net_acceptsocket != -1) - return; - if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) - WinError ("WINS_Listen: Unable to open accept socket\n"); - return; - } - - // disable listening - if (net_acceptsocket == -1) - return; - WINS_CloseSocket (net_acceptsocket); - net_acceptsocket = -1; -} //end of the function WINS_Listen*/ + void WINS_Listen(int state) + { + // enable listening + if (state) + { + if (net_acceptsocket != -1) + return; + if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) + WinError ("WINS_Listen: Unable to open accept socket\n"); + return; + } + + // disable listening + if (net_acceptsocket == -1) + return; + WINS_CloseSocket (net_acceptsocket); + net_acceptsocket = -1; + } //end of the function WINS_Listen*/ //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WINS_OpenSocket(int port) -{ +int WINS_OpenSocket( int port ){ int newsocket; struct sockaddr_in address; u_long _true = 1; - if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ( newsocket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == SOCKET_ERROR ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (ioctlsocket (newsocket, FIONBIO, &_true) == SOCKET_ERROR) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + if ( ioctlsocket( newsocket, FIONBIO, &_true ) == SOCKET_ERROR ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if - memset((char *) &address, 0, sizeof(address)); + memset( (char *) &address, 0, sizeof( address ) ); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons((u_short)port); - if( bind (newsocket, (void *)&address, sizeof(address)) == -1) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + address.sin_port = htons( (u_short)port ); + if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if @@ -304,36 +301,32 @@ int WINS_OpenSocket(int port) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_OpenReliableSocket(int port) -{ +int WINS_OpenReliableSocket( int port ){ int newsocket; struct sockaddr_in address; qboolean _true = 0xFFFFFFFF; //IPPROTO_TCP // - if ((newsocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ( newsocket = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - memset((char *) &address, 0, sizeof(address)); + memset( (char *) &address, 0, sizeof( address ) ); address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl(INADDR_ANY); - address.sin_port = htons((u_short)port); - if (bind(newsocket, (void *)&address, sizeof(address)) == -1) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + address.sin_addr.s_addr = htonl( INADDR_ANY ); + address.sin_port = htons( (u_short)port ); + if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if - // - if (setsockopt(newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof(int)) == -1) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - WinPrint("setsockopt error\n"); + // + if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == -1 ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + WinPrint( "setsockopt error\n" ); } //end if return newsocket; @@ -344,18 +337,15 @@ int WINS_OpenReliableSocket(int port) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Listen(int socket) -{ +int WINS_Listen( int socket ){ u_long _true = 1; - if (ioctlsocket(socket, FIONBIO, &_true) == -1) - { - WinPrint("WINS_Listen: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ioctlsocket( socket, FIONBIO, &_true ) == -1 ) { + WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (listen(socket, SOMAXCONN) == SOCKET_ERROR) - { - WinPrint("WINS_Listen: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( listen( socket, SOMAXCONN ) == SOCKET_ERROR ) { + WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if return 0; @@ -366,24 +356,23 @@ int WINS_Listen(int socket) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Accept(int socket, struct sockaddr_s *addr) -{ - socklen_t addrlen = sizeof (struct sockaddr_s); +int WINS_Accept( int socket, struct sockaddr_s *addr ){ + socklen_t addrlen = sizeof( struct sockaddr_s ); int newsocket; qboolean _true = 1; - newsocket = accept(socket, (struct sockaddr *)addr, &addrlen); - if (newsocket == INVALID_SOCKET) - { - if (errno == EAGAIN) return -1; - WinPrint("WINS_Accept: %s\n", WINS_ErrorMessage(WSAGetLastError())); + newsocket = accept( socket, (struct sockaddr *)addr, &addrlen ); + if ( newsocket == INVALID_SOCKET ) { + if ( errno == EAGAIN ) { + return -1; + } + WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - // - if (setsockopt(newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof(int)) == SOCKET_ERROR) - { - WinPrint("WINS_Accept: %s\n", WINS_ErrorMessage(WSAGetLastError())); - WinPrint("setsockopt error\n"); + // + if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { + WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + WinPrint( "setsockopt error\n" ); } //end if return newsocket; } //end of the function WINS_Accept @@ -393,17 +382,15 @@ int WINS_Accept(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_CloseSocket(int socket) -{ +int WINS_CloseSocket( int socket ){ /* - if (socket == net_broadcastsocket) - net_broadcastsocket = 0; - */ + if (socket == net_broadcastsocket) + net_broadcastsocket = 0; + */ // shutdown(socket, SD_SEND); - if (closesocket(socket) == SOCKET_ERROR) - { - WinPrint("WINS_CloseSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( closesocket( socket ) == SOCKET_ERROR ) { + WinPrint( "WINS_CloseSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return SOCKET_ERROR; } //end if return 0; @@ -416,35 +403,38 @@ int WINS_CloseSocket(int socket) // Returns: - // Changes Globals: - //=========================================================================== -static int PartialIPAddress (char *in, struct sockaddr_s *hostaddr) -{ +static int PartialIPAddress( char *in, struct sockaddr_s *hostaddr ){ char buff[256]; char *b; int addr; int num; int mask; - + buff[0] = '.'; b = buff; - strcpy(buff+1, in); - if (buff[1] == '.') b++; + strcpy( buff + 1, in ); + if ( buff[1] == '.' ) { + b++; + } addr = 0; - mask=-1; - while (*b == '.') + mask = -1; + while ( *b == '.' ) { num = 0; - if (*++b < '0' || *b > '9') return -1; - while (!( *b < '0' || *b > '9')) - num = num*10 + *(b++) - '0'; - mask<<=8; - addr = (addr<<8) + num; + if ( *++b < '0' || *b > '9' ) { + return -1; + } + while ( !( *b < '0' || *b > '9' ) ) + num = num * 10 + *( b++ ) - '0'; + mask <<= 8; + addr = ( addr << 8 ) + num; } - + hostaddr->sa_family = AF_INET; - ((struct sockaddr_in *)hostaddr)->sin_port = htons((u_short)net_hostport); - ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr = (myAddr & htonl(mask)) | htonl(addr); - + ( (struct sockaddr_in *)hostaddr )->sin_port = htons( (u_short)net_hostport ); + ( (struct sockaddr_in *)hostaddr )->sin_addr.s_addr = ( myAddr & htonl( mask ) ) | htonl( addr ); + return 0; } //end of the function PartialIPAddress //=========================================================================== @@ -453,20 +443,17 @@ static int PartialIPAddress (char *in, struct sockaddr_s *hostaddr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Connect(int socket, struct sockaddr_s *addr) -{ +int WINS_Connect( int socket, struct sockaddr_s *addr ){ int ret; u_long _true2 = 0xFFFFFFFF; - ret = connect(socket, (struct sockaddr *)addr, sizeof(struct sockaddr_s)); - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Connect: %s\n", WINS_ErrorMessage(WSAGetLastError())); + ret = connect( socket, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (ioctlsocket(socket, FIONBIO, &_true2) == -1) - { - WinPrint("WINS_Connect: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ioctlsocket( socket, FIONBIO, &_true2 ) == -1 ) { + WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if return 0; @@ -477,15 +464,16 @@ int WINS_Connect(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_CheckNewConnections(void) -{ +int WINS_CheckNewConnections( void ){ char buf[4]; - if (net_acceptsocket == -1) + if ( net_acceptsocket == -1 ) { return -1; + } - if (recvfrom(net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL) > 0) + if ( recvfrom( net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL ) > 0 ) { return net_acceptsocket; + } return -1; } //end of the function WINS_CheckNewConnections //=========================================================================== @@ -497,41 +485,39 @@ int WINS_CheckNewConnections(void) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Read(int socket, byte *buf, int len, struct sockaddr_s *addr) -{ - socklen_t addrlen = sizeof (struct sockaddr_s); +int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ){ + socklen_t addrlen = sizeof( struct sockaddr_s ); int ret; - if (addr) - { - ret = recvfrom(socket, buf, len, 0, (struct sockaddr *)addr, &addrlen); - if (ret == -1) - { + if ( addr ) { + ret = recvfrom( socket, buf, len, 0, (struct sockaddr *)addr, &addrlen ); + if ( ret == -1 ) { // errno = WSAGetLastError(); - if (errno == EAGAIN || errno == ENOTCONN) + if ( errno == EAGAIN || errno == ENOTCONN ) { return 0; + } } //end if } //end if else { - ret = recv(socket, buf, len, 0); - // if there's no data on the socket ret == -1 and errno == EAGAIN - // MSDN states that if ret == 0 the socket has been closed - // man recv doesn't say anything - if (ret == 0) - return -1; - if (ret == SOCKET_ERROR) - { + ret = recv( socket, buf, len, 0 ); + // if there's no data on the socket ret == -1 and errno == EAGAIN + // MSDN states that if ret == 0 the socket has been closed + // man recv doesn't say anything + if ( ret == 0 ) { + return -1; + } + if ( ret == SOCKET_ERROR ) { // errno = WSAGetLastError(); - if (errno == EAGAIN || errno == ENOTCONN) + if ( errno == EAGAIN || errno == ENOTCONN ) { return 0; + } } //end if } //end else - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Read: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Read: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); } //end if return ret; } //end of the function WINS_Read @@ -541,13 +527,13 @@ int WINS_Read(int socket, byte *buf, int len, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_MakeSocketBroadcastCapable (int socket) -{ - int i = 1; +int WINS_MakeSocketBroadcastCapable( int socket ){ + int i = 1; // make this socket broadcast capable - if (setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) < 0) + if ( setsockopt( socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof( i ) ) < 0 ) { return -1; + } net_broadcastsocket = socket; return 0; @@ -558,23 +544,21 @@ int WINS_MakeSocketBroadcastCapable (int socket) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Broadcast (int socket, byte *buf, int len) -{ +int WINS_Broadcast( int socket, byte *buf, int len ){ int ret; - if (socket != net_broadcastsocket) - { - if (net_broadcastsocket != 0) - WinError("Attempted to use multiple broadcasts sockets\n"); - ret = WINS_MakeSocketBroadcastCapable (socket); - if (ret == -1) - { - WinPrint("Unable to make socket broadcast capable\n"); + if ( socket != net_broadcastsocket ) { + if ( net_broadcastsocket != 0 ) { + WinError( "Attempted to use multiple broadcasts sockets\n" ); + } + ret = WINS_MakeSocketBroadcastCapable( socket ); + if ( ret == -1 ) { + WinPrint( "Unable to make socket broadcast capable\n" ); return ret; } } - return WINS_Write (socket, buf, len, &broadcastaddr); + return WINS_Write( socket, buf, len, &broadcastaddr ); } //end of the function WINS_Broadcast //=========================================================================== // returns qtrue on success or qfalse on failure @@ -583,22 +567,20 @@ int WINS_Broadcast (int socket, byte *buf, int len) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) -{ +int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ){ int ret, written; ret = 0; - if (addr) - { + if ( addr ) { written = 0; - while(written < len) + while ( written < len ) { - ret = sendto (socket, &buf[written], len-written, 0, (struct sockaddr *)addr, sizeof(struct sockaddr_s)); - if (ret == SOCKET_ERROR) - { - if (WSAGetLastError() != EAGAIN) + ret = sendto( socket, &buf[written], len - written, 0, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); + if ( ret == SOCKET_ERROR ) { + if ( WSAGetLastError() != EAGAIN ) { return qfalse; - //++timo FIXME: what is this used for? + } + //++timo FIXME: what is this used for? // Sleep(1000); } //end if else @@ -610,14 +592,14 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) else { written = 0; - while(written < len) + while ( written < len ) { - ret = send(socket, buf, len, 0); - if (ret == SOCKET_ERROR) - { - if (WSAGetLastError() != EAGAIN) + ret = send( socket, buf, len, 0 ); + if ( ret == SOCKET_ERROR ) { + if ( WSAGetLastError() != EAGAIN ) { return qfalse; - //++timo FIXME: what is this used for? + } + //++timo FIXME: what is this used for? // Sleep(1000); } //end if else @@ -626,11 +608,10 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) } } } //end else - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Write: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Write: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); } //end if - return (ret == len); + return ( ret == len ); } //end of the function WINS_Write //=========================================================================== // @@ -638,13 +619,12 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -char *WINS_AddrToString (struct sockaddr_s *addr) -{ +char *WINS_AddrToString( struct sockaddr_s *addr ){ static char buffer[22]; int haddr; - haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr); - sprintf(buffer, "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, ntohs(((struct sockaddr_in *)addr)->sin_port)); + haddr = ntohl( ( (struct sockaddr_in *)addr )->sin_addr.s_addr ); + sprintf( buffer, "%d.%d.%d.%d:%d", ( haddr >> 24 ) & 0xff, ( haddr >> 16 ) & 0xff, ( haddr >> 8 ) & 0xff, haddr & 0xff, ntohs( ( (struct sockaddr_in *)addr )->sin_port ) ); return buffer; } //end of the function WINS_AddrToString //=========================================================================== @@ -653,17 +633,16 @@ char *WINS_AddrToString (struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_StringToAddr(char *string, struct sockaddr_s *addr) -{ +int WINS_StringToAddr( char *string, struct sockaddr_s *addr ){ int ha1, ha2, ha3, ha4, hp; int ipaddr; - sscanf(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp); - ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4; + sscanf( string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp ); + ipaddr = ( ha1 << 24 ) | ( ha2 << 16 ) | ( ha3 << 8 ) | ha4; addr->sa_family = AF_INET; - ((struct sockaddr_in *)addr)->sin_addr.s_addr = htonl(ipaddr); - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)hp); + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = htonl( ipaddr ); + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)hp ); return 0; } //end of the function WINS_StringToAddr //=========================================================================== @@ -672,16 +651,16 @@ int WINS_StringToAddr(char *string, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetSocketAddr(int socket, struct sockaddr_s *addr) -{ - socklen_t addrlen = sizeof(struct sockaddr_s); +int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ){ + socklen_t addrlen = sizeof( struct sockaddr_s ); unsigned int a; - memset(addr, 0, sizeof(struct sockaddr_s)); - getsockname(socket, (struct sockaddr *)addr, &addrlen); - a = ((struct sockaddr_in *)addr)->sin_addr.s_addr; - if (a == 0 || a == inet_addr("127.0.0.1")) - ((struct sockaddr_in *)addr)->sin_addr.s_addr = myAddr; + memset( addr, 0, sizeof( struct sockaddr_s ) ); + getsockname( socket, (struct sockaddr *)addr, &addrlen ); + a = ( (struct sockaddr_in *)addr )->sin_addr.s_addr; + if ( a == 0 || a == inet_addr( "127.0.0.1" ) ) { + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = myAddr; + } return 0; } //end of the function WINS_GetSocketAddr @@ -691,18 +670,16 @@ int WINS_GetSocketAddr(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetNameFromAddr (struct sockaddr_s *addr, char *name) -{ +int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ){ struct hostent *hostentry; - hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, sizeof(struct in_addr), AF_INET); - if (hostentry) - { - strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1); + hostentry = gethostbyaddr( (char *)&( (struct sockaddr_in *)addr )->sin_addr, sizeof( struct in_addr ), AF_INET ); + if ( hostentry ) { + strncpy( name, (char *)hostentry->h_name, NET_NAMELEN - 1 ); return 0; } - strcpy (name, WINS_AddrToString (addr)); + strcpy( name, WINS_AddrToString( addr ) ); return 0; } //end of the function WINS_GetNameFromAddr //=========================================================================== @@ -711,20 +688,21 @@ int WINS_GetNameFromAddr (struct sockaddr_s *addr, char *name) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetAddrFromName(char *name, struct sockaddr_s *addr) -{ +int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ){ struct hostent *hostentry; - if (name[0] >= '0' && name[0] <= '9') - return PartialIPAddress (name, addr); - - hostentry = gethostbyname (name); - if (!hostentry) + if ( name[0] >= '0' && name[0] <= '9' ) { + return PartialIPAddress( name, addr ); + } + + hostentry = gethostbyname( name ); + if ( !hostentry ) { return -1; + } addr->sa_family = AF_INET; - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)net_hostport); - ((struct sockaddr_in *)addr)->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)net_hostport ); + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; return 0; } //end of the function WINS_GetAddrFromName @@ -734,16 +712,18 @@ int WINS_GetAddrFromName(char *name, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_AddrCompare (struct sockaddr_s *addr1, struct sockaddr_s *addr2) -{ - if (addr1->sa_family != addr2->sa_family) +int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ){ + if ( addr1->sa_family != addr2->sa_family ) { return -1; + } - if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != ((struct sockaddr_in *)addr2)->sin_addr.s_addr) + if ( ( (struct sockaddr_in *)addr1 )->sin_addr.s_addr != ( (struct sockaddr_in *)addr2 )->sin_addr.s_addr ) { return -1; + } - if (((struct sockaddr_in *)addr1)->sin_port != ((struct sockaddr_in *)addr2)->sin_port) + if ( ( (struct sockaddr_in *)addr1 )->sin_port != ( (struct sockaddr_in *)addr2 )->sin_port ) { return 1; + } return 0; } //end of the function WINS_AddrCompare @@ -753,9 +733,8 @@ int WINS_AddrCompare (struct sockaddr_s *addr1, struct sockaddr_s *addr2) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetSocketPort (struct sockaddr_s *addr) -{ - return ntohs(((struct sockaddr_in *)addr)->sin_port); +int WINS_GetSocketPort( struct sockaddr_s *addr ){ + return ntohs( ( (struct sockaddr_in *)addr )->sin_port ); } //end of the function WINS_GetSocketPort //=========================================================================== // @@ -763,8 +742,7 @@ int WINS_GetSocketPort (struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_SetSocketPort (struct sockaddr_s *addr, int port) -{ - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)port); +int WINS_SetSocketPort( struct sockaddr_s *addr, int port ){ + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)port ); return 0; } //end of the function WINS_SetSocketPort diff --git a/libs/l_net/l_net_wins.c b/libs/l_net/l_net_wins.c index 1b365da0..ca888259 100644 --- a/libs/l_net/l_net_wins.c +++ b/libs/l_net/l_net_wins.c @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //=========================================================================== // @@ -40,26 +40,26 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #define WinError WinPrint -#define qtrue 1 -#define qfalse 0 +#define qtrue 1 +#define qfalse 0 typedef struct tag_error_struct { - int errnum; - LPSTR errstr; + int errnum; + LPSTR errstr; } ERROR_STRUCT; -#define NET_NAMELEN 64 +#define NET_NAMELEN 64 char my_tcpip_address[NET_NAMELEN]; -#define DEFAULTnet_hostport 26000 +#define DEFAULTnet_hostport 26000 -#define MAXHOSTNAMELEN 256 +#define MAXHOSTNAMELEN 256 -static int net_acceptsocket = -1; // socket for fielding new connections +static int net_acceptsocket = -1; // socket for fielding new connections static int net_controlsocket; -static int net_hostport; // udp port number for acceptsocket +static int net_hostport; // udp port number for acceptsocket static int net_broadcastsocket = 0; //static qboolean ifbcastinit = qfalse; static struct sockaddr_s broadcastaddr; @@ -69,71 +69,71 @@ static unsigned long myAddr; WSADATA winsockdata; ERROR_STRUCT errlist[] = { - {WSAEINTR, "WSAEINTR - Interrupted"}, - {WSAEBADF, "WSAEBADF - Bad file number"}, - {WSAEFAULT, "WSAEFAULT - Bad address"}, - {WSAEINVAL, "WSAEINVAL - Invalid argument"}, - {WSAEMFILE, "WSAEMFILE - Too many open files"}, + {WSAEINTR, "WSAEINTR - Interrupted"}, + {WSAEBADF, "WSAEBADF - Bad file number"}, + {WSAEFAULT, "WSAEFAULT - Bad address"}, + {WSAEINVAL, "WSAEINVAL - Invalid argument"}, + {WSAEMFILE, "WSAEMFILE - Too many open files"}, /* -* Windows Sockets definitions of regular Berkeley error constants -*/ - - {WSAEWOULDBLOCK, "WSAEWOULDBLOCK - Socket marked as non-blocking"}, - {WSAEINPROGRESS, "WSAEINPROGRESS - Blocking call in progress"}, - {WSAEALREADY, "WSAEALREADY - Command already completed"}, - {WSAENOTSOCK, "WSAENOTSOCK - Descriptor is not a socket"}, - {WSAEDESTADDRREQ, "WSAEDESTADDRREQ - Destination address required"}, - {WSAEMSGSIZE, "WSAEMSGSIZE - Data size too large"}, - {WSAEPROTOTYPE, "WSAEPROTOTYPE - Protocol is of wrong type for this socket"}, - {WSAENOPROTOOPT, "WSAENOPROTOOPT - Protocol option not supported for this socket type"}, - {WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT - Protocol is not supported"}, - {WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT - Socket type not supported by this address family"}, - {WSAEOPNOTSUPP, "WSAEOPNOTSUPP - Option not supported"}, - {WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT - "}, - {WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT - Address family not supported by this protocol"}, - {WSAEADDRINUSE, "WSAEADDRINUSE - Address is in use"}, - {WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL - Address not available from local machine"}, - {WSAENETDOWN, "WSAENETDOWN - Network subsystem is down"}, - {WSAENETUNREACH, "WSAENETUNREACH - Network cannot be reached"}, - {WSAENETRESET, "WSAENETRESET - Connection has been dropped"}, - {WSAECONNABORTED, "WSAECONNABORTED - Connection aborted"}, - {WSAECONNRESET, "WSAECONNRESET - Connection reset"}, - {WSAENOBUFS, "WSAENOBUFS - No buffer space available"}, - {WSAEISCONN, "WSAEISCONN - Socket is already connected"}, - {WSAENOTCONN, "WSAENOTCONN - Socket is not connected"}, - {WSAESHUTDOWN, "WSAESHUTDOWN - Socket has been shut down"}, - {WSAETOOMANYREFS, "WSAETOOMANYREFS - Too many references"}, - {WSAETIMEDOUT, "WSAETIMEDOUT - Command timed out"}, - {WSAECONNREFUSED, "WSAECONNREFUSED - Connection refused"}, - {WSAELOOP, "WSAELOOP - "}, - {WSAENAMETOOLONG, "WSAENAMETOOLONG - "}, - {WSAEHOSTDOWN, "WSAEHOSTDOWN - Host is down"}, - {WSAEHOSTUNREACH, "WSAEHOSTUNREACH - "}, - {WSAENOTEMPTY, "WSAENOTEMPTY - "}, - {WSAEPROCLIM, "WSAEPROCLIM - "}, - {WSAEUSERS, "WSAEUSERS - "}, - {WSAEDQUOT, "WSAEDQUOT - "}, - {WSAESTALE, "WSAESTALE - "}, - {WSAEREMOTE, "WSAEREMOTE - "}, + * Windows Sockets definitions of regular Berkeley error constants + */ + + {WSAEWOULDBLOCK, "WSAEWOULDBLOCK - Socket marked as non-blocking"}, + {WSAEINPROGRESS, "WSAEINPROGRESS - Blocking call in progress"}, + {WSAEALREADY, "WSAEALREADY - Command already completed"}, + {WSAENOTSOCK, "WSAENOTSOCK - Descriptor is not a socket"}, + {WSAEDESTADDRREQ, "WSAEDESTADDRREQ - Destination address required"}, + {WSAEMSGSIZE, "WSAEMSGSIZE - Data size too large"}, + {WSAEPROTOTYPE, "WSAEPROTOTYPE - Protocol is of wrong type for this socket"}, + {WSAENOPROTOOPT, "WSAENOPROTOOPT - Protocol option not supported for this socket type"}, + {WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT - Protocol is not supported"}, + {WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT - Socket type not supported by this address family"}, + {WSAEOPNOTSUPP, "WSAEOPNOTSUPP - Option not supported"}, + {WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT - "}, + {WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT - Address family not supported by this protocol"}, + {WSAEADDRINUSE, "WSAEADDRINUSE - Address is in use"}, + {WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL - Address not available from local machine"}, + {WSAENETDOWN, "WSAENETDOWN - Network subsystem is down"}, + {WSAENETUNREACH, "WSAENETUNREACH - Network cannot be reached"}, + {WSAENETRESET, "WSAENETRESET - Connection has been dropped"}, + {WSAECONNABORTED, "WSAECONNABORTED - Connection aborted"}, + {WSAECONNRESET, "WSAECONNRESET - Connection reset"}, + {WSAENOBUFS, "WSAENOBUFS - No buffer space available"}, + {WSAEISCONN, "WSAEISCONN - Socket is already connected"}, + {WSAENOTCONN, "WSAENOTCONN - Socket is not connected"}, + {WSAESHUTDOWN, "WSAESHUTDOWN - Socket has been shut down"}, + {WSAETOOMANYREFS, "WSAETOOMANYREFS - Too many references"}, + {WSAETIMEDOUT, "WSAETIMEDOUT - Command timed out"}, + {WSAECONNREFUSED, "WSAECONNREFUSED - Connection refused"}, + {WSAELOOP, "WSAELOOP - "}, + {WSAENAMETOOLONG, "WSAENAMETOOLONG - "}, + {WSAEHOSTDOWN, "WSAEHOSTDOWN - Host is down"}, + {WSAEHOSTUNREACH, "WSAEHOSTUNREACH - "}, + {WSAENOTEMPTY, "WSAENOTEMPTY - "}, + {WSAEPROCLIM, "WSAEPROCLIM - "}, + {WSAEUSERS, "WSAEUSERS - "}, + {WSAEDQUOT, "WSAEDQUOT - "}, + {WSAESTALE, "WSAESTALE - "}, + {WSAEREMOTE, "WSAEREMOTE - "}, /* -* Extended Windows Sockets error constant definitions -*/ + * Extended Windows Sockets error constant definitions + */ - {WSASYSNOTREADY, "WSASYSNOTREADY - Network subsystem not ready"}, - {WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED - Version not supported"}, - {WSANOTINITIALISED, "WSANOTINITIALISED - WSAStartup() has not been successfully called"}, + {WSASYSNOTREADY, "WSASYSNOTREADY - Network subsystem not ready"}, + {WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED - Version not supported"}, + {WSANOTINITIALISED, "WSANOTINITIALISED - WSAStartup() has not been successfully called"}, /* -* Other error constants. -*/ - - {WSAHOST_NOT_FOUND, "WSAHOST_NOT_FOUND - Host not found"}, - {WSATRY_AGAIN, "WSATRY_AGAIN - Host not found or SERVERFAIL"}, - {WSANO_RECOVERY, "WSANO_RECOVERY - Non-recoverable error"}, - {WSANO_DATA, "WSANO_DATA - (or WSANO_ADDRESS) - No data record of requested type"}, - {-1, NULL} + * Other error constants. + */ + + {WSAHOST_NOT_FOUND, "WSAHOST_NOT_FOUND - Host not found"}, + {WSATRY_AGAIN, "WSATRY_AGAIN - Host not found or SERVERFAIL"}, + {WSANO_RECOVERY, "WSANO_RECOVERY - Non-recoverable error"}, + {WSANO_DATA, "WSANO_DATA - (or WSANO_ADDRESS) - No data record of requested type"}, + {-1, NULL} }; //=========================================================================== @@ -142,19 +142,21 @@ ERROR_STRUCT errlist[] = { // Returns: - // Changes Globals: - //=========================================================================== -const char *WINS_ErrorMessage(int error) -{ - int search = 0; +const char *WINS_ErrorMessage( int error ){ + int search = 0; - if (!error) return "No error occurred"; + if ( !error ) { + return "No error occurred"; + } - for (search = 0; errlist[search].errstr; search++) - { - if (error == errlist[search].errnum) - return errlist[search].errstr; - } //end for + for ( search = 0; errlist[search].errstr; search++ ) + { + if ( error == errlist[search].errnum ) { + return errlist[search].errstr; + } + } //end for - return "Unknown error"; + return "Unknown error"; } //end of the function WINS_ErrorMessage //=========================================================================== // @@ -162,73 +164,75 @@ const char *WINS_ErrorMessage(int error) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Init(void) -{ - int i; +int WINS_Init( void ){ + int i; struct hostent *local; - char buff[MAXHOSTNAMELEN]; + char buff[MAXHOSTNAMELEN]; struct sockaddr_s addr; - char *p; - int r; - WORD wVersionRequested; + char *p; + int r; + WORD wVersionRequested; - wVersionRequested = MAKEWORD(1, 1); + wVersionRequested = MAKEWORD( 1, 1 ); - r = WSAStartup (wVersionRequested, &winsockdata); + r = WSAStartup( wVersionRequested, &winsockdata ); - if (r) - { - WinPrint("Winsock initialization failed.\n"); + if ( r ) { + WinPrint( "Winsock initialization failed.\n" ); return -1; } /* - i = COM_CheckParm ("-udpport"); - if (i == 0)*/ - net_hostport = DEFAULTnet_hostport; + i = COM_CheckParm ("-udpport"); + if (i == 0)*/ + net_hostport = DEFAULTnet_hostport; /* - else if (i < com_argc-1) - net_hostport = Q_atoi (com_argv[i+1]); - else - Sys_Error ("WINS_Init: you must specify a number after -udpport"); - */ + else if (i < com_argc-1) + net_hostport = Q_atoi (com_argv[i+1]); + else + Sys_Error ("WINS_Init: you must specify a number after -udpport"); + */ // determine my name & address - gethostname(buff, MAXHOSTNAMELEN); - local = gethostbyname(buff); + gethostname( buff, MAXHOSTNAMELEN ); + local = gethostbyname( buff ); myAddr = *(int *)local->h_addr_list[0]; // if the quake hostname isn't set, set it to the machine name // if (Q_strcmp(hostname.string, "UNNAMED") == 0) { // see if it's a text IP address (well, close enough) - for (p = buff; *p; p++) - if ((*p < '0' || *p > '9') && *p != '.') + for ( p = buff; *p; p++ ) + if ( ( *p < '0' || *p > '9' ) && *p != '.' ) { break; + } // if it is a real name, strip off the domain; we only want the host - if (*p) - { - for (i = 0; i < 15; i++) - if (buff[i] == '.') + if ( *p ) { + for ( i = 0; i < 15; i++ ) + if ( buff[i] == '.' ) { break; + } buff[i] = 0; } // Cvar_Set ("hostname", buff); } - if ((net_controlsocket = WINS_OpenSocket (0)) == -1) - WinError("WINS_Init: Unable to open control socket\n"); + if ( ( net_controlsocket = WINS_OpenSocket( 0 ) ) == -1 ) { + WinError( "WINS_Init: Unable to open control socket\n" ); + } - ((struct sockaddr_in *)&broadcastaddr)->sin_family = AF_INET; - ((struct sockaddr_in *)&broadcastaddr)->sin_addr.s_addr = INADDR_BROADCAST; - ((struct sockaddr_in *)&broadcastaddr)->sin_port = htons((u_short)net_hostport); + ( (struct sockaddr_in *)&broadcastaddr )->sin_family = AF_INET; + ( (struct sockaddr_in *)&broadcastaddr )->sin_addr.s_addr = INADDR_BROADCAST; + ( (struct sockaddr_in *)&broadcastaddr )->sin_port = htons( (u_short)net_hostport ); - WINS_GetSocketAddr (net_controlsocket, &addr); - strcpy(my_tcpip_address, WINS_AddrToString (&addr)); - p = strrchr (my_tcpip_address, ':'); - if (p) *p = 0; - WinPrint("Winsock Initialized\n"); + WINS_GetSocketAddr( net_controlsocket, &addr ); + strcpy( my_tcpip_address, WINS_AddrToString( &addr ) ); + p = strrchr( my_tcpip_address, ':' ); + if ( p ) { + *p = 0; + } + WinPrint( "Winsock Initialized\n" ); return net_controlsocket; } //end of the function WINS_Init @@ -238,8 +242,7 @@ int WINS_Init(void) // Returns: - // Changes Globals: - //=========================================================================== -char *WINS_MyAddress(void) -{ +char *WINS_MyAddress( void ){ return my_tcpip_address; } //end of the function WINS_MyAddress //=========================================================================== @@ -248,10 +251,9 @@ char *WINS_MyAddress(void) // Returns: - // Changes Globals: - //=========================================================================== -void WINS_Shutdown(void) -{ +void WINS_Shutdown( void ){ //WINS_Listen(0); - WINS_CloseSocket(net_controlsocket); + WINS_CloseSocket( net_controlsocket ); WSACleanup(); // //WinPrint("Winsock Shutdown\n"); @@ -263,57 +265,53 @@ void WINS_Shutdown(void) // Changes Globals: - //=========================================================================== /* -void WINS_Listen(int state) -{ - // enable listening - if (state) - { - if (net_acceptsocket != -1) - return; - if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) - WinError ("WINS_Listen: Unable to open accept socket\n"); - return; - } - - // disable listening - if (net_acceptsocket == -1) - return; - WINS_CloseSocket (net_acceptsocket); - net_acceptsocket = -1; -} //end of the function WINS_Listen*/ + void WINS_Listen(int state) + { + // enable listening + if (state) + { + if (net_acceptsocket != -1) + return; + if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) + WinError ("WINS_Listen: Unable to open accept socket\n"); + return; + } + + // disable listening + if (net_acceptsocket == -1) + return; + WINS_CloseSocket (net_acceptsocket); + net_acceptsocket = -1; + } //end of the function WINS_Listen*/ //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WINS_OpenSocket(int port) -{ +int WINS_OpenSocket( int port ){ int newsocket; struct sockaddr_in address; u_long _true = 1; - if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ( newsocket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == -1 ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (ioctlsocket (newsocket, FIONBIO, &_true) == -1) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + if ( ioctlsocket( newsocket, FIONBIO, &_true ) == -1 ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if - memset((char *) &address, 0, sizeof(address)); + memset( (char *) &address, 0, sizeof( address ) ); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons((u_short)port); - if( bind (newsocket, (void *)&address, sizeof(address)) == -1) - { - WinPrint("WINS_OpenSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + address.sin_port = htons( (u_short)port ); + if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { + WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if @@ -325,36 +323,32 @@ int WINS_OpenSocket(int port) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_OpenReliableSocket(int port) -{ +int WINS_OpenReliableSocket( int port ){ int newsocket; struct sockaddr_in address; BOOL _true = 0xFFFFFFFF; //IPPROTO_TCP // - if ((newsocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ( newsocket = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - memset((char *) &address, 0, sizeof(address)); + memset( (char *) &address, 0, sizeof( address ) ); address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl(INADDR_ANY); - address.sin_port = htons((u_short)port); - if (bind(newsocket, (void *)&address, sizeof(address)) == -1) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - closesocket(newsocket); + address.sin_addr.s_addr = htonl( INADDR_ANY ); + address.sin_port = htons( (u_short)port ); + if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + closesocket( newsocket ); return -1; } //end if - // - if (setsockopt(newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof(int)) == SOCKET_ERROR) - { - WinPrint("WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); - WinPrint("setsockopt error\n"); + // + if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { + WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + WinPrint( "setsockopt error\n" ); } //end if return newsocket; @@ -365,18 +359,15 @@ int WINS_OpenReliableSocket(int port) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Listen(int socket) -{ +int WINS_Listen( int socket ){ u_long _true = 1; - if (ioctlsocket(socket, FIONBIO, &_true) == -1) - { - WinPrint("WINS_Listen: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ioctlsocket( socket, FIONBIO, &_true ) == -1 ) { + WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (listen(socket, SOMAXCONN) == SOCKET_ERROR) - { - WinPrint("WINS_Listen: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( listen( socket, SOMAXCONN ) == SOCKET_ERROR ) { + WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if return 0; @@ -387,24 +378,23 @@ int WINS_Listen(int socket) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Accept(int socket, struct sockaddr_s *addr) -{ - int addrlen = sizeof (struct sockaddr_s); +int WINS_Accept( int socket, struct sockaddr_s *addr ){ + int addrlen = sizeof( struct sockaddr_s ); int newsocket; BOOL _true = 1; - newsocket = accept(socket, (struct sockaddr *)addr, &addrlen); - if (newsocket == INVALID_SOCKET) - { - if (WSAGetLastError() == WSAEWOULDBLOCK) return -1; - WinPrint("WINS_Accept: %s\n", WINS_ErrorMessage(WSAGetLastError())); + newsocket = accept( socket, (struct sockaddr *)addr, &addrlen ); + if ( newsocket == INVALID_SOCKET ) { + if ( WSAGetLastError() == WSAEWOULDBLOCK ) { + return -1; + } + WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - // - if (setsockopt(newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof(int)) == SOCKET_ERROR) - { - WinPrint("WINS_Accept: %s\n", WINS_ErrorMessage(WSAGetLastError())); - WinPrint("setsockopt error\n"); + // + if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { + WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); + WinPrint( "setsockopt error\n" ); } //end if return newsocket; } //end of the function WINS_Accept @@ -414,17 +404,15 @@ int WINS_Accept(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_CloseSocket(int socket) -{ +int WINS_CloseSocket( int socket ){ /* - if (socket == net_broadcastsocket) - net_broadcastsocket = 0; - */ + if (socket == net_broadcastsocket) + net_broadcastsocket = 0; + */ // shutdown(socket, SD_SEND); - if (closesocket(socket) == SOCKET_ERROR) - { - WinPrint("WINS_CloseSocket: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( closesocket( socket ) == SOCKET_ERROR ) { + WinPrint( "WINS_CloseSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return SOCKET_ERROR; } //end if return 0; @@ -437,35 +425,38 @@ int WINS_CloseSocket(int socket) // Returns: - // Changes Globals: - //=========================================================================== -static int PartialIPAddress (char *in, struct sockaddr_s *hostaddr) -{ +static int PartialIPAddress( char *in, struct sockaddr_s *hostaddr ){ char buff[256]; char *b; int addr; int num; int mask; - + buff[0] = '.'; b = buff; - strcpy(buff+1, in); - if (buff[1] == '.') b++; + strcpy( buff + 1, in ); + if ( buff[1] == '.' ) { + b++; + } addr = 0; - mask=-1; - while (*b == '.') + mask = -1; + while ( *b == '.' ) { num = 0; - if (*++b < '0' || *b > '9') return -1; - while (!( *b < '0' || *b > '9')) - num = num*10 + *(b++) - '0'; - mask<<=8; - addr = (addr<<8) + num; + if ( *++b < '0' || *b > '9' ) { + return -1; + } + while ( !( *b < '0' || *b > '9' ) ) + num = num * 10 + *( b++ ) - '0'; + mask <<= 8; + addr = ( addr << 8 ) + num; } - + hostaddr->sa_family = AF_INET; - ((struct sockaddr_in *)hostaddr)->sin_port = htons((u_short)net_hostport); - ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr = (myAddr & htonl(mask)) | htonl(addr); - + ( (struct sockaddr_in *)hostaddr )->sin_port = htons( (u_short)net_hostport ); + ( (struct sockaddr_in *)hostaddr )->sin_addr.s_addr = ( myAddr & htonl( mask ) ) | htonl( addr ); + return 0; } //end of the function PartialIPAddress //=========================================================================== @@ -474,20 +465,17 @@ static int PartialIPAddress (char *in, struct sockaddr_s *hostaddr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Connect(int socket, struct sockaddr_s *addr) -{ +int WINS_Connect( int socket, struct sockaddr_s *addr ){ int ret; u_long _true2 = 0xFFFFFFFF; - ret = connect(socket, (struct sockaddr *)addr, sizeof(struct sockaddr_s)); - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Connect: %s\n", WINS_ErrorMessage(WSAGetLastError())); + ret = connect( socket, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if - if (ioctlsocket(socket, FIONBIO, &_true2) == -1) - { - WinPrint("WINS_Connect: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ioctlsocket( socket, FIONBIO, &_true2 ) == -1 ) { + WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); return -1; } //end if return 0; @@ -498,15 +486,16 @@ int WINS_Connect(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_CheckNewConnections(void) -{ +int WINS_CheckNewConnections( void ){ char buf[4]; - if (net_acceptsocket == -1) + if ( net_acceptsocket == -1 ) { return -1; + } - if (recvfrom(net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL) > 0) + if ( recvfrom( net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL ) > 0 ) { return net_acceptsocket; + } return -1; } //end of the function WINS_CheckNewConnections //=========================================================================== @@ -518,36 +507,33 @@ int WINS_CheckNewConnections(void) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Read(int socket, byte *buf, int len, struct sockaddr_s *addr) -{ - int addrlen = sizeof (struct sockaddr_s); +int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ){ + int addrlen = sizeof( struct sockaddr_s ); int ret, errno; - if (addr) - { - ret = recvfrom(socket, buf, len, 0, (struct sockaddr *)addr, &addrlen); - if (ret == -1) - { + if ( addr ) { + ret = recvfrom( socket, buf, len, 0, (struct sockaddr *)addr, &addrlen ); + if ( ret == -1 ) { errno = WSAGetLastError(); - if (errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED) + if ( errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED ) { return 0; + } } //end if } //end if else { - ret = recv(socket, buf, len, 0); - if (ret == SOCKET_ERROR) - { + ret = recv( socket, buf, len, 0 ); + if ( ret == SOCKET_ERROR ) { errno = WSAGetLastError(); - if (errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED) + if ( errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED ) { return 0; + } } //end if } //end else - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Read: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Read: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); } //end if return ret; } //end of the function WINS_Read @@ -557,13 +543,13 @@ int WINS_Read(int socket, byte *buf, int len, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_MakeSocketBroadcastCapable (int socket) -{ - int i = 1; +int WINS_MakeSocketBroadcastCapable( int socket ){ + int i = 1; // make this socket broadcast capable - if (setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) < 0) + if ( setsockopt( socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof( i ) ) < 0 ) { return -1; + } net_broadcastsocket = socket; return 0; @@ -574,23 +560,21 @@ int WINS_MakeSocketBroadcastCapable (int socket) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Broadcast (int socket, byte *buf, int len) -{ +int WINS_Broadcast( int socket, byte *buf, int len ){ int ret; - if (socket != net_broadcastsocket) - { - if (net_broadcastsocket != 0) - WinError("Attempted to use multiple broadcasts sockets\n"); - ret = WINS_MakeSocketBroadcastCapable (socket); - if (ret == -1) - { - WinPrint("Unable to make socket broadcast capable\n"); + if ( socket != net_broadcastsocket ) { + if ( net_broadcastsocket != 0 ) { + WinError( "Attempted to use multiple broadcasts sockets\n" ); + } + ret = WINS_MakeSocketBroadcastCapable( socket ); + if ( ret == -1 ) { + WinPrint( "Unable to make socket broadcast capable\n" ); return ret; } } - return WINS_Write (socket, buf, len, &broadcastaddr); + return WINS_Write( socket, buf, len, &broadcastaddr ); } //end of the function WINS_Broadcast //=========================================================================== // returns qtrue on success or qfalse on failure @@ -599,21 +583,19 @@ int WINS_Broadcast (int socket, byte *buf, int len) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) -{ +int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ){ int ret, written; - if (addr) - { + if ( addr ) { written = 0; - while(written < len) + while ( written < len ) { - ret = sendto (socket, &buf[written], len-written, 0, (struct sockaddr *)addr, sizeof(struct sockaddr_s)); - if (ret == SOCKET_ERROR) - { - if (WSAGetLastError() != WSAEWOULDBLOCK) + ret = sendto( socket, &buf[written], len - written, 0, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); + if ( ret == SOCKET_ERROR ) { + if ( WSAGetLastError() != WSAEWOULDBLOCK ) { return qfalse; - Sleep(1000); + } + Sleep( 1000 ); } //end if else { @@ -624,14 +606,14 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) else { written = 0; - while(written < len) + while ( written < len ) { - ret = send(socket, buf, len, 0); - if (ret == SOCKET_ERROR) - { - if (WSAGetLastError() != WSAEWOULDBLOCK) + ret = send( socket, buf, len, 0 ); + if ( ret == SOCKET_ERROR ) { + if ( WSAGetLastError() != WSAEWOULDBLOCK ) { return qfalse; - Sleep(1000); + } + Sleep( 1000 ); } //end if else { @@ -639,11 +621,10 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) } } } //end else - if (ret == SOCKET_ERROR) - { - WinPrint("WINS_Write: %s\n", WINS_ErrorMessage(WSAGetLastError())); + if ( ret == SOCKET_ERROR ) { + WinPrint( "WINS_Write: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); } //end if - return (ret == len); + return ( ret == len ); } //end of the function WINS_Write //=========================================================================== // @@ -651,13 +632,12 @@ int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -char *WINS_AddrToString (struct sockaddr_s *addr) -{ +char *WINS_AddrToString( struct sockaddr_s *addr ){ static char buffer[22]; int haddr; - haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr); - sprintf(buffer, "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, ntohs(((struct sockaddr_in *)addr)->sin_port)); + haddr = ntohl( ( (struct sockaddr_in *)addr )->sin_addr.s_addr ); + sprintf( buffer, "%d.%d.%d.%d:%d", ( haddr >> 24 ) & 0xff, ( haddr >> 16 ) & 0xff, ( haddr >> 8 ) & 0xff, haddr & 0xff, ntohs( ( (struct sockaddr_in *)addr )->sin_port ) ); return buffer; } //end of the function WINS_AddrToString //=========================================================================== @@ -666,17 +646,16 @@ char *WINS_AddrToString (struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_StringToAddr(char *string, struct sockaddr_s *addr) -{ +int WINS_StringToAddr( char *string, struct sockaddr_s *addr ){ int ha1, ha2, ha3, ha4, hp; int ipaddr; - sscanf(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp); - ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4; + sscanf( string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp ); + ipaddr = ( ha1 << 24 ) | ( ha2 << 16 ) | ( ha3 << 8 ) | ha4; addr->sa_family = AF_INET; - ((struct sockaddr_in *)addr)->sin_addr.s_addr = htonl(ipaddr); - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)hp); + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = htonl( ipaddr ); + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)hp ); return 0; } //end of the function WINS_StringToAddr //=========================================================================== @@ -685,16 +664,16 @@ int WINS_StringToAddr(char *string, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetSocketAddr(int socket, struct sockaddr_s *addr) -{ - int addrlen = sizeof(struct sockaddr_s); +int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ){ + int addrlen = sizeof( struct sockaddr_s ); unsigned int a; - memset(addr, 0, sizeof(struct sockaddr_s)); - getsockname(socket, (struct sockaddr *)addr, &addrlen); - a = ((struct sockaddr_in *)addr)->sin_addr.s_addr; - if (a == 0 || a == inet_addr("127.0.0.1")) - ((struct sockaddr_in *)addr)->sin_addr.s_addr = myAddr; + memset( addr, 0, sizeof( struct sockaddr_s ) ); + getsockname( socket, (struct sockaddr *)addr, &addrlen ); + a = ( (struct sockaddr_in *)addr )->sin_addr.s_addr; + if ( a == 0 || a == inet_addr( "127.0.0.1" ) ) { + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = myAddr; + } return 0; } //end of the function WINS_GetSocketAddr @@ -704,18 +683,16 @@ int WINS_GetSocketAddr(int socket, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetNameFromAddr (struct sockaddr_s *addr, char *name) -{ +int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ){ struct hostent *hostentry; - hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, sizeof(struct in_addr), AF_INET); - if (hostentry) - { - strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1); + hostentry = gethostbyaddr( (char *)&( (struct sockaddr_in *)addr )->sin_addr, sizeof( struct in_addr ), AF_INET ); + if ( hostentry ) { + strncpy( name, (char *)hostentry->h_name, NET_NAMELEN - 1 ); return 0; } - strcpy (name, WINS_AddrToString (addr)); + strcpy( name, WINS_AddrToString( addr ) ); return 0; } //end of the function WINS_GetNameFromAddr //=========================================================================== @@ -724,20 +701,21 @@ int WINS_GetNameFromAddr (struct sockaddr_s *addr, char *name) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetAddrFromName(char *name, struct sockaddr_s *addr) -{ +int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ){ struct hostent *hostentry; - if (name[0] >= '0' && name[0] <= '9') - return PartialIPAddress (name, addr); - - hostentry = gethostbyname (name); - if (!hostentry) + if ( name[0] >= '0' && name[0] <= '9' ) { + return PartialIPAddress( name, addr ); + } + + hostentry = gethostbyname( name ); + if ( !hostentry ) { return -1; + } addr->sa_family = AF_INET; - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)net_hostport); - ((struct sockaddr_in *)addr)->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)net_hostport ); + ( (struct sockaddr_in *)addr )->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; return 0; } //end of the function WINS_GetAddrFromName @@ -747,16 +725,18 @@ int WINS_GetAddrFromName(char *name, struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_AddrCompare (struct sockaddr_s *addr1, struct sockaddr_s *addr2) -{ - if (addr1->sa_family != addr2->sa_family) +int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ){ + if ( addr1->sa_family != addr2->sa_family ) { return -1; + } - if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != ((struct sockaddr_in *)addr2)->sin_addr.s_addr) + if ( ( (struct sockaddr_in *)addr1 )->sin_addr.s_addr != ( (struct sockaddr_in *)addr2 )->sin_addr.s_addr ) { return -1; + } - if (((struct sockaddr_in *)addr1)->sin_port != ((struct sockaddr_in *)addr2)->sin_port) + if ( ( (struct sockaddr_in *)addr1 )->sin_port != ( (struct sockaddr_in *)addr2 )->sin_port ) { return 1; + } return 0; } //end of the function WINS_AddrCompare @@ -766,9 +746,8 @@ int WINS_AddrCompare (struct sockaddr_s *addr1, struct sockaddr_s *addr2) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_GetSocketPort (struct sockaddr_s *addr) -{ - return ntohs(((struct sockaddr_in *)addr)->sin_port); +int WINS_GetSocketPort( struct sockaddr_s *addr ){ + return ntohs( ( (struct sockaddr_in *)addr )->sin_port ); } //end of the function WINS_GetSocketPort //=========================================================================== // @@ -776,8 +755,7 @@ int WINS_GetSocketPort (struct sockaddr_s *addr) // Returns: - // Changes Globals: - //=========================================================================== -int WINS_SetSocketPort (struct sockaddr_s *addr, int port) -{ - ((struct sockaddr_in *)addr)->sin_port = htons((u_short)port); +int WINS_SetSocketPort( struct sockaddr_s *addr, int port ){ + ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)port ); return 0; } //end of the function WINS_SetSocketPort diff --git a/libs/l_net/l_net_wins.h b/libs/l_net/l_net_wins.h index ad1b41fb..ebe75472 100644 --- a/libs/l_net/l_net_wins.h +++ b/libs/l_net/l_net_wins.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ //=========================================================================== // @@ -29,24 +29,24 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // Notes: //=========================================================================== -int WINS_Init(void); -void WINS_Shutdown(void); -char *WINS_MyAddress(void); -int WINS_Listen(int socket); -int WINS_Accept(int socket, struct sockaddr_s *addr); -int WINS_OpenSocket(int port); -int WINS_OpenReliableSocket(int port); -int WINS_CloseSocket(int socket); -int WINS_Connect (int socket, struct sockaddr_s *addr); -int WINS_CheckNewConnections(void); -int WINS_Read(int socket, byte *buf, int len, struct sockaddr_s *addr); -int WINS_Write(int socket, byte *buf, int len, struct sockaddr_s *addr); -int WINS_Broadcast (int socket, byte *buf, int len); -char *WINS_AddrToString (struct sockaddr_s *addr); -int WINS_StringToAddr (char *string, struct sockaddr_s *addr); -int WINS_GetSocketAddr (int socket, struct sockaddr_s *addr); -int WINS_GetNameFromAddr (struct sockaddr_s *addr, char *name); -int WINS_GetAddrFromName (char *name, struct sockaddr_s *addr); -int WINS_AddrCompare (struct sockaddr_s *addr1, struct sockaddr_s *addr2); -int WINS_GetSocketPort (struct sockaddr_s *addr); -int WINS_SetSocketPort (struct sockaddr_s *addr, int port); +int WINS_Init( void ); +void WINS_Shutdown( void ); +char *WINS_MyAddress( void ); +int WINS_Listen( int socket ); +int WINS_Accept( int socket, struct sockaddr_s *addr ); +int WINS_OpenSocket( int port ); +int WINS_OpenReliableSocket( int port ); +int WINS_CloseSocket( int socket ); +int WINS_Connect( int socket, struct sockaddr_s *addr ); +int WINS_CheckNewConnections( void ); +int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ); +int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ); +int WINS_Broadcast( int socket, byte *buf, int len ); +char *WINS_AddrToString( struct sockaddr_s *addr ); +int WINS_StringToAddr( char *string, struct sockaddr_s *addr ); +int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ); +int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ); +int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ); +int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ); +int WINS_GetSocketPort( struct sockaddr_s *addr ); +int WINS_SetSocketPort( struct sockaddr_s *addr, int port ); diff --git a/libs/maplib.cpp b/libs/maplib.cpp index 80504f1d..7487a68a 100644 --- a/libs/maplib.cpp +++ b/libs/maplib.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "maplib.h" diff --git a/libs/maplib.h b/libs/maplib.h index 6a2d5cea..07da39dc 100644 --- a/libs/maplib.h +++ b/libs/maplib.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_MAPLIB_H) +#if !defined ( INCLUDED_MAPLIB_H ) #define INCLUDED_MAPLIB_H #include "nameable.h" @@ -36,246 +36,202 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class NameableString : public Nameable { - CopiedString m_name; +CopiedString m_name; public: - NameableString(const char* name) - : m_name(name) - { - } - - const char* name() const - { - return m_name.c_str(); - } - void attach(const NameCallback& callback) - { - } - void detach(const NameCallback& callback) - { - } +NameableString( const char* name ) + : m_name( name ){ +} + +const char* name() const { + return m_name.c_str(); +} +void attach( const NameCallback& callback ){ +} +void detach( const NameCallback& callback ){ +} }; class UndoFileChangeTracker : public UndoTracker, public MapFile { - std::size_t m_size; - std::size_t m_saved; - typedef void (UndoFileChangeTracker::*Pending)(); - Pending m_pending; - Callback m_changed; +std::size_t m_size; +std::size_t m_saved; +typedef void ( UndoFileChangeTracker::*Pending )(); +Pending m_pending; +Callback m_changed; public: - UndoFileChangeTracker() : m_size(0), m_saved(MAPFILE_MAX_CHANGES), m_pending(0) - { - } - void print() - { - globalOutputStream() << "saved: " << Unsigned(m_saved) << " size: " << Unsigned(m_size) << "\n"; - } - - void push() - { - ++m_size; - m_changed(); - //print(); - } - void pop() - { - --m_size; - m_changed(); - //print(); - } - void pushOperation() - { - if(m_size < m_saved) - { - // redo queue has been flushed.. it is now impossible to get back to the saved state via undo/redo - m_saved = MAPFILE_MAX_CHANGES; - } - push(); - } - void clear() - { - m_size = 0; - m_changed(); - //print(); - } - void begin() - { - m_pending = Pending(&UndoFileChangeTracker::pushOperation); - } - void undo() - { - m_pending = Pending(&UndoFileChangeTracker::pop); - } - void redo() - { - m_pending = Pending(&UndoFileChangeTracker::push); - } - - void changed() - { - if(m_pending != 0) - { - ((*this).*m_pending)(); - m_pending = 0; - } - } - - void save() - { - m_saved = m_size; - m_changed(); - } - bool saved() const - { - return m_saved == m_size; - } - - void setChangedCallback(const Callback& changed) - { - m_changed = changed; - m_changed(); - } - - std::size_t changes() const - { - return m_size; - } +UndoFileChangeTracker() : m_size( 0 ), m_saved( MAPFILE_MAX_CHANGES ), m_pending( 0 ){ +} +void print(){ + globalOutputStream() << "saved: " << Unsigned( m_saved ) << " size: " << Unsigned( m_size ) << "\n"; +} + +void push(){ + ++m_size; + m_changed(); + //print(); +} +void pop(){ + --m_size; + m_changed(); + //print(); +} +void pushOperation(){ + if ( m_size < m_saved ) { + // redo queue has been flushed.. it is now impossible to get back to the saved state via undo/redo + m_saved = MAPFILE_MAX_CHANGES; + } + push(); +} +void clear(){ + m_size = 0; + m_changed(); + //print(); +} +void begin(){ + m_pending = Pending( &UndoFileChangeTracker::pushOperation ); +} +void undo(){ + m_pending = Pending( &UndoFileChangeTracker::pop ); +} +void redo(){ + m_pending = Pending( &UndoFileChangeTracker::push ); +} + +void changed(){ + if ( m_pending != 0 ) { + ( ( *this ).*m_pending )(); + m_pending = 0; + } +} + +void save(){ + m_saved = m_size; + m_changed(); +} +bool saved() const { + return m_saved == m_size; +} + +void setChangedCallback( const Callback& changed ){ + m_changed = changed; + m_changed(); +} + +std::size_t changes() const { + return m_size; +} }; class MapRoot : public scene::Node::Symbiot, public scene::Instantiable, public scene::Traversable::Observer { - class TypeCasts - { - NodeTypeCastTable m_casts; - public: - TypeCasts() - { - NodeStaticCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - } - NodeTypeCastTable& get() - { - return m_casts; - } - }; - - scene::Node m_node; - IdentityTransform m_transform; - TraversableNodeSet m_traverse; - InstanceSet m_instances; - typedef SelectableInstance Instance; - NameableString m_name; - UndoFileChangeTracker m_changeTracker; +class TypeCasts +{ +NodeTypeCastTable m_casts; public: - typedef LazyStatic StaticTypeCasts; - - scene::Traversable& get(NullType) - { - return m_traverse; - } - TransformNode& get(NullType) - { - return m_transform; - } - Nameable& get(NullType) - { - return m_name; - } - MapFile& get(NullType) - { - return m_changeTracker; - } - - MapRoot(const char* name) : m_node(this, this, StaticTypeCasts::instance().get()), m_name(name) - { - m_node.m_isRoot = true; - - m_traverse.attach(this); - - GlobalUndoSystem().trackerAttach(m_changeTracker); - } - ~MapRoot() - { - } - void release() - { - GlobalUndoSystem().trackerDetach(m_changeTracker); - - m_traverse.detach(this); - delete this; - } - scene::Node& node() - { - return m_node; - } - - InstanceCounter m_instanceCounter; - void instanceAttach(const scene::Path& path) - { - if(++m_instanceCounter.m_count == 1) - { - m_traverse.instanceAttach(path_find_mapfile(path.begin(), path.end())); - } - } - void instanceDetach(const scene::Path& path) - { - if(--m_instanceCounter.m_count == 0) - { - m_traverse.instanceDetach(path_find_mapfile(path.begin(), path.end())); - } - } - - void insert(scene::Node& child) - { - m_instances.insert(child); - } - void erase(scene::Node& child) - { - m_instances.erase(child); - } - - scene::Node& clone() const - { - return (new MapRoot(*this))->node(); - } - - scene::Instance* create(const scene::Path& path, scene::Instance* parent) - { - return new Instance(path, parent); - } - void forEachInstance(const scene::Instantiable::Visitor& visitor) - { - m_instances.forEachInstance(visitor); - } - void insert(scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance) - { - m_instances.insert(observer, path, instance); - instanceAttach(path); - } - scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) - { - instanceDetach(path); - return m_instances.erase(observer, path); - } +TypeCasts(){ + NodeStaticCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); + NodeContainedCast::install( m_casts ); +} +NodeTypeCastTable& get(){ + return m_casts; +} }; -inline void MapRoot_construct() -{ +scene::Node m_node; +IdentityTransform m_transform; +TraversableNodeSet m_traverse; +InstanceSet m_instances; +typedef SelectableInstance Instance; +NameableString m_name; +UndoFileChangeTracker m_changeTracker; +public: +typedef LazyStatic StaticTypeCasts; + +scene::Traversable& get( NullType){ + return m_traverse; +} +TransformNode& get( NullType){ + return m_transform; +} +Nameable& get( NullType){ + return m_name; +} +MapFile& get( NullType){ + return m_changeTracker; } -inline void MapRoot_destroy() -{ +MapRoot( const char* name ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_name( name ){ + m_node.m_isRoot = true; + + m_traverse.attach( this ); + + GlobalUndoSystem().trackerAttach( m_changeTracker ); } +~MapRoot(){ +} +void release(){ + GlobalUndoSystem().trackerDetach( m_changeTracker ); -inline NodeSmartReference NewMapRoot(const char* name) -{ - return NodeSmartReference((new MapRoot(name))->node()); + m_traverse.detach( this ); + delete this; +} +scene::Node& node(){ + return m_node; +} + +InstanceCounter m_instanceCounter; +void instanceAttach( const scene::Path& path ){ + if ( ++m_instanceCounter.m_count == 1 ) { + m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); + } +} +void instanceDetach( const scene::Path& path ){ + if ( --m_instanceCounter.m_count == 0 ) { + m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); + } +} + +void insert( scene::Node& child ){ + m_instances.insert( child ); +} +void erase( scene::Node& child ){ + m_instances.erase( child ); +} + +scene::Node& clone() const { + return ( new MapRoot( *this ) )->node(); +} + +scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ + return new Instance( path, parent ); +} +void forEachInstance( const scene::Instantiable::Visitor& visitor ){ + m_instances.forEachInstance( visitor ); +} +void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ + m_instances.insert( observer, path, instance ); + instanceAttach( path ); +} +scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ + instanceDetach( path ); + return m_instances.erase( observer, path ); +} +}; + +inline void MapRoot_construct(){ +} + +inline void MapRoot_destroy(){ +} + +inline NodeSmartReference NewMapRoot( const char* name ){ + return NodeSmartReference( ( new MapRoot( name ) )->node() ); } diff --git a/libs/math/aabb.cpp b/libs/math/aabb.cpp index 8bed2209..ad4ae00c 100644 --- a/libs/math/aabb.cpp +++ b/libs/math/aabb.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "aabb.h" - diff --git a/libs/math/aabb.h b/libs/math/aabb.h index 1341a340..29e3a38e 100644 --- a/libs/math/aabb.h +++ b/libs/math/aabb.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_AABB_H) +#if !defined( INCLUDED_MATH_AABB_H ) #define INCLUDED_MATH_AABB_H /// \file @@ -31,263 +31,227 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class AABB { public: - Vector3 origin, extents; - - AABB() : origin(0, 0, 0), extents(-1,-1,-1) - { - } - AABB(const Vector3& origin_, const Vector3& extents_) : - origin(origin_), extents(extents_) - { - } +Vector3 origin, extents; + +AABB() : origin( 0, 0, 0 ), extents( -1,-1,-1 ){ +} +AABB( const Vector3& origin_, const Vector3& extents_ ) : + origin( origin_ ), extents( extents_ ){ +} }; const float c_aabb_max = FLT_MAX; -inline bool extents_valid(float f) -{ - return f >= 0.0f && f <= c_aabb_max; +inline bool extents_valid( float f ){ + return f >= 0.0f && f <= c_aabb_max; } -inline bool origin_valid(float f) -{ - return f >= -c_aabb_max && f <= c_aabb_max; +inline bool origin_valid( float f ){ + return f >= -c_aabb_max && f <= c_aabb_max; } -inline bool aabb_valid(const AABB& aabb) -{ - return origin_valid(aabb.origin[0]) - && origin_valid(aabb.origin[1]) - && origin_valid(aabb.origin[2]) - && extents_valid(aabb.extents[0]) - && extents_valid(aabb.extents[1]) - && extents_valid(aabb.extents[2]); +inline bool aabb_valid( const AABB& aabb ){ + return origin_valid( aabb.origin[0] ) + && origin_valid( aabb.origin[1] ) + && origin_valid( aabb.origin[2] ) + && extents_valid( aabb.extents[0] ) + && extents_valid( aabb.extents[1] ) + && extents_valid( aabb.extents[2] ); } -inline AABB aabb_for_minmax(const Vector3& min, const Vector3& max) -{ - AABB aabb; - aabb.origin = vector3_mid(min, max); - aabb.extents = vector3_subtracted(max, aabb.origin); - return aabb; +inline AABB aabb_for_minmax( const Vector3& min, const Vector3& max ){ + AABB aabb; + aabb.origin = vector3_mid( min, max ); + aabb.extents = vector3_subtracted( max, aabb.origin ); + return aabb; } template class AABBExtend { public: - static void apply(AABB& aabb, const Vector3& point) - { - float displacement = point[Index::VALUE] - aabb.origin[Index::VALUE]; - float half_difference = static_cast(0.5 * (fabs(displacement) - aabb.extents[Index::VALUE])); - if(half_difference > 0.0f) - { - aabb.origin[Index::VALUE] += (displacement >= 0.0f) ? half_difference : -half_difference; - aabb.extents[Index::VALUE] += half_difference; - } - } - static void apply(AABB& aabb, const AABB& other) - { - float displacement = other.origin[Index::VALUE] - aabb.origin[Index::VALUE]; - float difference = other.extents[Index::VALUE] - aabb.extents[Index::VALUE]; - if(fabs(displacement) > fabs(difference)) - { - float half_difference = static_cast(0.5 * (fabs(displacement) + difference)); - if(half_difference > 0.0f) - { - aabb.origin[Index::VALUE] += (displacement >= 0.0f) ? half_difference : -half_difference; - aabb.extents[Index::VALUE] += half_difference; - } - } - else if(difference > 0.0f) - { - aabb.origin[Index::VALUE] = other.origin[Index::VALUE]; - aabb.extents[Index::VALUE] = other.extents[Index::VALUE]; - } - } +static void apply( AABB& aabb, const Vector3& point ){ + float displacement = point[Index::VALUE] - aabb.origin[Index::VALUE]; + float half_difference = static_cast( 0.5 * ( fabs( displacement ) - aabb.extents[Index::VALUE] ) ); + if ( half_difference > 0.0f ) { + aabb.origin[Index::VALUE] += ( displacement >= 0.0f ) ? half_difference : -half_difference; + aabb.extents[Index::VALUE] += half_difference; + } +} +static void apply( AABB& aabb, const AABB& other ){ + float displacement = other.origin[Index::VALUE] - aabb.origin[Index::VALUE]; + float difference = other.extents[Index::VALUE] - aabb.extents[Index::VALUE]; + if ( fabs( displacement ) > fabs( difference ) ) { + float half_difference = static_cast( 0.5 * ( fabs( displacement ) + difference ) ); + if ( half_difference > 0.0f ) { + aabb.origin[Index::VALUE] += ( displacement >= 0.0f ) ? half_difference : -half_difference; + aabb.extents[Index::VALUE] += half_difference; + } + } + else if ( difference > 0.0f ) { + aabb.origin[Index::VALUE] = other.origin[Index::VALUE]; + aabb.extents[Index::VALUE] = other.extents[Index::VALUE]; + } +} }; -inline void aabb_extend_by_point(AABB& aabb, const Vector3& point) -{ - AABBExtend< IntegralConstant<0> >::apply(aabb, point); - AABBExtend< IntegralConstant<1> >::apply(aabb, point); - AABBExtend< IntegralConstant<2> >::apply(aabb, point); +inline void aabb_extend_by_point( AABB& aabb, const Vector3& point ){ + AABBExtend< IntegralConstant<0> >::apply( aabb, point ); + AABBExtend< IntegralConstant<1> >::apply( aabb, point ); + AABBExtend< IntegralConstant<2> >::apply( aabb, point ); } -inline void aabb_extend_by_point_safe(AABB& aabb, const Vector3& point) -{ - if(aabb_valid(aabb)) - { - aabb_extend_by_point(aabb, point); - } - else - { - aabb.origin = point; - aabb.extents = Vector3(0, 0, 0); - } +inline void aabb_extend_by_point_safe( AABB& aabb, const Vector3& point ){ + if ( aabb_valid( aabb ) ) { + aabb_extend_by_point( aabb, point ); + } + else + { + aabb.origin = point; + aabb.extents = Vector3( 0, 0, 0 ); + } } class AABBExtendByPoint { - AABB& m_aabb; +AABB& m_aabb; public: - AABBExtendByPoint(AABB& aabb) : m_aabb(aabb) - { - } - void operator()(const Vector3& point) const - { - aabb_extend_by_point_safe(m_aabb, point); - } +AABBExtendByPoint( AABB& aabb ) : m_aabb( aabb ){ +} +void operator()( const Vector3& point ) const { + aabb_extend_by_point_safe( m_aabb, point ); +} }; - -inline void aabb_extend_by_aabb(AABB& aabb, const AABB& other) -{ - AABBExtend< IntegralConstant<0> >::apply(aabb, other); - AABBExtend< IntegralConstant<1> >::apply(aabb, other); - AABBExtend< IntegralConstant<2> >::apply(aabb, other); + +inline void aabb_extend_by_aabb( AABB& aabb, const AABB& other ){ + AABBExtend< IntegralConstant<0> >::apply( aabb, other ); + AABBExtend< IntegralConstant<1> >::apply( aabb, other ); + AABBExtend< IntegralConstant<2> >::apply( aabb, other ); } -inline void aabb_extend_by_aabb_safe(AABB& aabb, const AABB& other) -{ - if(aabb_valid(aabb) && aabb_valid(other)) - { - aabb_extend_by_aabb(aabb, other); - } - else if(aabb_valid(other)) - { - aabb = other; - } +inline void aabb_extend_by_aabb_safe( AABB& aabb, const AABB& other ){ + if ( aabb_valid( aabb ) && aabb_valid( other ) ) { + aabb_extend_by_aabb( aabb, other ); + } + else if ( aabb_valid( other ) ) { + aabb = other; + } } -inline void aabb_extend_by_vec3(AABB& aabb, const Vector3& extension) -{ - vector3_add(aabb.extents, extension); +inline void aabb_extend_by_vec3( AABB& aabb, const Vector3& extension ){ + vector3_add( aabb.extents, extension ); } template -inline bool aabb_intersects_point_dimension(const AABB& aabb, const Vector3& point) -{ - return fabs(point[Index::VALUE] - aabb.origin[Index::VALUE]) < aabb.extents[Index::VALUE]; +inline bool aabb_intersects_point_dimension( const AABB& aabb, const Vector3& point ){ + return fabs( point[Index::VALUE] - aabb.origin[Index::VALUE] ) < aabb.extents[Index::VALUE]; } -inline bool aabb_intersects_point(const AABB& aabb, const Vector3& point) -{ - return aabb_intersects_point_dimension< IntegralConstant<0> >(aabb, point) - && aabb_intersects_point_dimension< IntegralConstant<1> >(aabb, point) - && aabb_intersects_point_dimension< IntegralConstant<2> >(aabb, point); +inline bool aabb_intersects_point( const AABB& aabb, const Vector3& point ){ + return aabb_intersects_point_dimension< IntegralConstant<0> >( aabb, point ) + && aabb_intersects_point_dimension< IntegralConstant<1> >( aabb, point ) + && aabb_intersects_point_dimension< IntegralConstant<2> >( aabb, point ); } template -inline bool aabb_intersects_aabb_dimension(const AABB& aabb, const AABB& other) -{ - return fabs(other.origin[Index::VALUE] - aabb.origin[Index::VALUE]) < (aabb.extents[Index::VALUE] + other.extents[Index::VALUE]); +inline bool aabb_intersects_aabb_dimension( const AABB& aabb, const AABB& other ){ + return fabs( other.origin[Index::VALUE] - aabb.origin[Index::VALUE] ) < ( aabb.extents[Index::VALUE] + other.extents[Index::VALUE] ); } -inline bool aabb_intersects_aabb(const AABB& aabb, const AABB& other) -{ - return aabb_intersects_aabb_dimension< IntegralConstant<0> >(aabb, other) - && aabb_intersects_aabb_dimension< IntegralConstant<1> >(aabb, other) - && aabb_intersects_aabb_dimension< IntegralConstant<2> >(aabb, other); +inline bool aabb_intersects_aabb( const AABB& aabb, const AABB& other ){ + return aabb_intersects_aabb_dimension< IntegralConstant<0> >( aabb, other ) + && aabb_intersects_aabb_dimension< IntegralConstant<1> >( aabb, other ) + && aabb_intersects_aabb_dimension< IntegralConstant<2> >( aabb, other ); } -inline unsigned int aabb_classify_plane(const AABB& aabb, const Plane3& plane) -{ - double distance_origin = vector3_dot(plane.normal(), aabb.origin) + plane.dist(); - - if(fabs(distance_origin) < (fabs(plane.a * aabb.extents[0]) - + fabs(plane.b * aabb.extents[1]) - + fabs(plane.c * aabb.extents[2]))) - { - return 1; // partially inside - } - else if (distance_origin < 0) - { - return 2; // totally inside - } - return 0; // totally outside +inline unsigned int aabb_classify_plane( const AABB& aabb, const Plane3& plane ){ + double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); + + if ( fabs( distance_origin ) < ( fabs( plane.a * aabb.extents[0] ) + + fabs( plane.b * aabb.extents[1] ) + + fabs( plane.c * aabb.extents[2] ) ) ) { + return 1; // partially inside + } + else if ( distance_origin < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } -inline unsigned int aabb_oriented_classify_plane(const AABB& aabb, const Matrix4& transform, const Plane3& plane) -{ - double distance_origin = vector3_dot(plane.normal(), aabb.origin) + plane.dist(); - - if(fabs(distance_origin) < (fabs(aabb.extents[0] * vector3_dot(plane.normal(), vector4_to_vector3(transform.x()))) - + fabs(aabb.extents[1] * vector3_dot(plane.normal(), vector4_to_vector3(transform.y()))) - + fabs(aabb.extents[2] * vector3_dot(plane.normal(), vector4_to_vector3(transform.z()))))) - { - return 1; // partially inside - } - else if (distance_origin < 0) - { - return 2; // totally inside - } - return 0; // totally outside +inline unsigned int aabb_oriented_classify_plane( const AABB& aabb, const Matrix4& transform, const Plane3& plane ){ + double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); + + if ( fabs( distance_origin ) < ( fabs( aabb.extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( transform.x() ) ) ) + + fabs( aabb.extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( transform.y() ) ) ) + + fabs( aabb.extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( transform.z() ) ) ) ) ) { + return 1; // partially inside + } + else if ( distance_origin < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } -inline void aabb_corners(const AABB& aabb, Vector3 corners[8]) -{ - Vector3 min(vector3_subtracted(aabb.origin, aabb.extents)); - Vector3 max(vector3_added(aabb.origin, aabb.extents)); - corners[0] = Vector3(min[0], max[1], max[2]); - corners[1] = Vector3(max[0], max[1], max[2]); - corners[2] = Vector3(max[0], min[1], max[2]); - corners[3] = Vector3(min[0], min[1], max[2]); - corners[4] = Vector3(min[0], max[1], min[2]); - corners[5] = Vector3(max[0], max[1], min[2]); - corners[6] = Vector3(max[0], min[1], min[2]); - corners[7] = Vector3(min[0], min[1], min[2]); +inline void aabb_corners( const AABB& aabb, Vector3 corners[8] ){ + Vector3 min( vector3_subtracted( aabb.origin, aabb.extents ) ); + Vector3 max( vector3_added( aabb.origin, aabb.extents ) ); + corners[0] = Vector3( min[0], max[1], max[2] ); + corners[1] = Vector3( max[0], max[1], max[2] ); + corners[2] = Vector3( max[0], min[1], max[2] ); + corners[3] = Vector3( min[0], min[1], max[2] ); + corners[4] = Vector3( min[0], max[1], min[2] ); + corners[5] = Vector3( max[0], max[1], min[2] ); + corners[6] = Vector3( max[0], min[1], min[2] ); + corners[7] = Vector3( min[0], min[1], min[2] ); } -inline void aabb_corners_oriented(const AABB& aabb, const Matrix4& rotation, Vector3 corners[8]) -{ - Vector3 x = vector4_to_vector3(rotation.x()) * aabb.extents.x(); - Vector3 y = vector4_to_vector3(rotation.y()) * aabb.extents.y(); - Vector3 z = vector4_to_vector3(rotation.z()) * aabb.extents.z(); - - corners[0] = aabb.origin + -x + y + z; - corners[1] = aabb.origin + x + y + z; - corners[2] = aabb.origin + x + -y + z; - corners[3] = aabb.origin + -x + -y + z; - corners[4] = aabb.origin + -x + y + -z; - corners[5] = aabb.origin + x + y + -z; - corners[6] = aabb.origin + x + -y + -z; - corners[7] = aabb.origin + -x + -y + -z; +inline void aabb_corners_oriented( const AABB& aabb, const Matrix4& rotation, Vector3 corners[8] ){ + Vector3 x = vector4_to_vector3( rotation.x() ) * aabb.extents.x(); + Vector3 y = vector4_to_vector3( rotation.y() ) * aabb.extents.y(); + Vector3 z = vector4_to_vector3( rotation.z() ) * aabb.extents.z(); + + corners[0] = aabb.origin + -x + y + z; + corners[1] = aabb.origin + x + y + z; + corners[2] = aabb.origin + x + -y + z; + corners[3] = aabb.origin + -x + -y + z; + corners[4] = aabb.origin + -x + y + -z; + corners[5] = aabb.origin + x + y + -z; + corners[6] = aabb.origin + x + -y + -z; + corners[7] = aabb.origin + -x + -y + -z; } -inline void aabb_planes(const AABB& aabb, Plane3 planes[6]) -{ - planes[0] = Plane3(g_vector3_axes[0], aabb.origin[0] + aabb.extents[0]); - planes[1] = Plane3(vector3_negated(g_vector3_axes[0]), -(aabb.origin[0] - aabb.extents[0])); - planes[2] = Plane3(g_vector3_axes[1], aabb.origin[1] + aabb.extents[1]); - planes[3] = Plane3(vector3_negated(g_vector3_axes[1]), -(aabb.origin[1] - aabb.extents[1])); - planes[4] = Plane3(g_vector3_axes[2], aabb.origin[2] + aabb.extents[2]); - planes[5] = Plane3(vector3_negated(g_vector3_axes[2]), -(aabb.origin[2] - aabb.extents[2])); +inline void aabb_planes( const AABB& aabb, Plane3 planes[6] ){ + planes[0] = Plane3( g_vector3_axes[0], aabb.origin[0] + aabb.extents[0] ); + planes[1] = Plane3( vector3_negated( g_vector3_axes[0] ), -( aabb.origin[0] - aabb.extents[0] ) ); + planes[2] = Plane3( g_vector3_axes[1], aabb.origin[1] + aabb.extents[1] ); + planes[3] = Plane3( vector3_negated( g_vector3_axes[1] ), -( aabb.origin[1] - aabb.extents[1] ) ); + planes[4] = Plane3( g_vector3_axes[2], aabb.origin[2] + aabb.extents[2] ); + planes[5] = Plane3( vector3_negated( g_vector3_axes[2] ), -( aabb.origin[2] - aabb.extents[2] ) ); } -inline void aabb_planes_oriented(const AABB& aabb, const Matrix4& rotation, Plane3 planes[6]) -{ - double x = vector3_dot(vector4_to_vector3(rotation.x()), aabb.origin); - double y = vector3_dot(vector4_to_vector3(rotation.y()), aabb.origin); - double z = vector3_dot(vector4_to_vector3(rotation.z()), aabb.origin); - - planes[0] = Plane3(vector4_to_vector3(rotation.x()), x + aabb.extents[0]); - planes[1] = Plane3(-vector4_to_vector3(rotation.x()), -(x - aabb.extents[0])); - planes[2] = Plane3(vector4_to_vector3(rotation.y()), y + aabb.extents[1]); - planes[3] = Plane3(-vector4_to_vector3(rotation.y()), -(y - aabb.extents[1])); - planes[4] = Plane3(vector4_to_vector3(rotation.z()), z + aabb.extents[2]); - planes[5] = Plane3(-vector4_to_vector3(rotation.z()), -(z - aabb.extents[2])); +inline void aabb_planes_oriented( const AABB& aabb, const Matrix4& rotation, Plane3 planes[6] ){ + double x = vector3_dot( vector4_to_vector3( rotation.x() ), aabb.origin ); + double y = vector3_dot( vector4_to_vector3( rotation.y() ), aabb.origin ); + double z = vector3_dot( vector4_to_vector3( rotation.z() ), aabb.origin ); + + planes[0] = Plane3( vector4_to_vector3( rotation.x() ), x + aabb.extents[0] ); + planes[1] = Plane3( -vector4_to_vector3( rotation.x() ), -( x - aabb.extents[0] ) ); + planes[2] = Plane3( vector4_to_vector3( rotation.y() ), y + aabb.extents[1] ); + planes[3] = Plane3( -vector4_to_vector3( rotation.y() ), -( y - aabb.extents[1] ) ); + planes[4] = Plane3( vector4_to_vector3( rotation.z() ), z + aabb.extents[2] ); + planes[5] = Plane3( -vector4_to_vector3( rotation.z() ), -( z - aabb.extents[2] ) ); } const Vector3 aabb_normals[6] = { - Vector3( 1, 0, 0 ), - Vector3( 0, 1, 0 ), - Vector3( 0, 0, 1 ), - Vector3(-1, 0, 0 ), - Vector3( 0,-1, 0 ), - Vector3( 0, 0,-1 ), + Vector3( 1, 0, 0 ), + Vector3( 0, 1, 0 ), + Vector3( 0, 0, 1 ), + Vector3( -1, 0, 0 ), + Vector3( 0,-1, 0 ), + Vector3( 0, 0,-1 ), }; const float aabb_texcoord_topleft[2] = { 0, 0 }; @@ -296,36 +260,32 @@ const float aabb_texcoord_botleft[2] = { 0, 1 }; const float aabb_texcoord_botright[2] = { 1, 1 }; -inline AABB aabb_for_oriented_aabb(const AABB& aabb, const Matrix4& transform) -{ - return AABB( - matrix4_transformed_point(transform, aabb.origin), - Vector3( - static_cast(fabs(transform[0] * aabb.extents[0]) - + fabs(transform[4] * aabb.extents[1]) - + fabs(transform[8] * aabb.extents[2])), - static_cast(fabs(transform[1] * aabb.extents[0]) - + fabs(transform[5] * aabb.extents[1]) - + fabs(transform[9] * aabb.extents[2])), - static_cast(fabs(transform[2] * aabb.extents[0]) - + fabs(transform[6] * aabb.extents[1]) - + fabs(transform[10] * aabb.extents[2])) - ) - ); +inline AABB aabb_for_oriented_aabb( const AABB& aabb, const Matrix4& transform ){ + return AABB( + matrix4_transformed_point( transform, aabb.origin ), + Vector3( + static_cast( fabs( transform[0] * aabb.extents[0] ) + + fabs( transform[4] * aabb.extents[1] ) + + fabs( transform[8] * aabb.extents[2] ) ), + static_cast( fabs( transform[1] * aabb.extents[0] ) + + fabs( transform[5] * aabb.extents[1] ) + + fabs( transform[9] * aabb.extents[2] ) ), + static_cast( fabs( transform[2] * aabb.extents[0] ) + + fabs( transform[6] * aabb.extents[1] ) + + fabs( transform[10] * aabb.extents[2] ) ) + ) + ); } -inline AABB aabb_for_oriented_aabb_safe(const AABB& aabb, const Matrix4& transform) -{ - if(aabb_valid(aabb)) - { - return aabb_for_oriented_aabb(aabb, transform); - } - return aabb; +inline AABB aabb_for_oriented_aabb_safe( const AABB& aabb, const Matrix4& transform ){ + if ( aabb_valid( aabb ) ) { + return aabb_for_oriented_aabb( aabb, transform ); + } + return aabb; } -inline AABB aabb_infinite() -{ - return AABB(Vector3(0, 0, 0), Vector3(c_aabb_max, c_aabb_max, c_aabb_max)); +inline AABB aabb_infinite(){ + return AABB( Vector3( 0, 0, 0 ), Vector3( c_aabb_max, c_aabb_max, c_aabb_max ) ); } #endif diff --git a/libs/math/curve.cpp b/libs/math/curve.cpp index dd2bc0e3..e38d2a11 100644 --- a/libs/math/curve.cpp +++ b/libs/math/curve.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "curve.h" - diff --git a/libs/math/curve.h b/libs/math/curve.h index 9000734c..1ba7b5e7 100644 --- a/libs/math/curve.h +++ b/libs/math/curve.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_CURVE_H) +#if !defined( INCLUDED_MATH_CURVE_H ) #define INCLUDED_MATH_CURVE_H /// \file @@ -33,10 +33,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template struct BernsteinPolynomial { - static double apply(double t) - { - return 1; // general case not implemented - } + static double apply( double t ){ + return 1; // general case not implemented + } }; typedef IntegralConstant<0> Zero; @@ -48,226 +47,206 @@ typedef IntegralConstant<4> Four; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return 1; - } + static double apply( double t ){ + return 1; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return 1 - t; - } + static double apply( double t ){ + return 1 - t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return t; - } + static double apply( double t ){ + return t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return (1 - t) * (1 - t); - } + static double apply( double t ){ + return ( 1 - t ) * ( 1 - t ); + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return 2 * (1 - t) * t; - } + static double apply( double t ){ + return 2 * ( 1 - t ) * t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return t * t; - } + static double apply( double t ){ + return t * t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return (1 - t) * (1 - t) * (1 - t); - } + static double apply( double t ){ + return ( 1 - t ) * ( 1 - t ) * ( 1 - t ); + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return 3 * (1 - t) * (1 - t) * t; - } + static double apply( double t ){ + return 3 * ( 1 - t ) * ( 1 - t ) * t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return 3 * (1 - t) * t * t; - } + static double apply( double t ){ + return 3 * ( 1 - t ) * t * t; + } }; template<> struct BernsteinPolynomial { - static double apply(double t) - { - return t * t * t; - } + static double apply( double t ){ + return t * t * t; + } }; typedef Array ControlPoints; -inline Vector3 CubicBezier_evaluate(const Vector3* firstPoint, double t) -{ - Vector3 result(0, 0, 0); - double denominator = 0; - - { - double weight = BernsteinPolynomial::apply(t); - result += vector3_scaled(*firstPoint++, weight); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply(t); - result += vector3_scaled(*firstPoint++, weight); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply(t); - result += vector3_scaled(*firstPoint++, weight); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply(t); - result += vector3_scaled(*firstPoint++, weight); - denominator += weight; - } - - return result / denominator; +inline Vector3 CubicBezier_evaluate( const Vector3* firstPoint, double t ){ + Vector3 result( 0, 0, 0 ); + double denominator = 0; + + { + double weight = BernsteinPolynomial::apply( t ); + result += vector3_scaled( *firstPoint++, weight ); + denominator += weight; + } + { + double weight = BernsteinPolynomial::apply( t ); + result += vector3_scaled( *firstPoint++, weight ); + denominator += weight; + } + { + double weight = BernsteinPolynomial::apply( t ); + result += vector3_scaled( *firstPoint++, weight ); + denominator += weight; + } + { + double weight = BernsteinPolynomial::apply( t ); + result += vector3_scaled( *firstPoint++, weight ); + denominator += weight; + } + + return result / denominator; } -inline Vector3 CubicBezier_evaluateMid(const Vector3* firstPoint) -{ - return vector3_scaled(firstPoint[0], 0.125) - + vector3_scaled(firstPoint[1], 0.375) - + vector3_scaled(firstPoint[2], 0.375) - + vector3_scaled(firstPoint[3], 0.125); +inline Vector3 CubicBezier_evaluateMid( const Vector3* firstPoint ){ + return vector3_scaled( firstPoint[0], 0.125 ) + + vector3_scaled( firstPoint[1], 0.375 ) + + vector3_scaled( firstPoint[2], 0.375 ) + + vector3_scaled( firstPoint[3], 0.125 ); } -inline Vector3 CatmullRom_evaluate(const ControlPoints& controlPoints, double t) -{ - // scale t to be segment-relative - t *= double(controlPoints.size() - 1); - - // subtract segment index; - std::size_t segment = 0; - for(std::size_t i = 0; i < controlPoints.size() - 1; ++i) - { - if(t <= double(i+1)) - { - segment = i; - break; - } - } - t -= segment; - - const double reciprocal_alpha = 1.0 / 3.0; - - Vector3 bezierPoints[4]; - bezierPoints[0] = controlPoints[segment]; - bezierPoints[1] = (segment > 0) - ? controlPoints[segment] + vector3_scaled(controlPoints[segment + 1] - controlPoints[segment - 1], reciprocal_alpha * 0.5) - : controlPoints[segment] + vector3_scaled(controlPoints[segment + 1] - controlPoints[segment], reciprocal_alpha); - bezierPoints[2] = (segment < controlPoints.size() - 2) - ? controlPoints[segment + 1] + vector3_scaled(controlPoints[segment] - controlPoints[segment + 2], reciprocal_alpha * 0.5) - : controlPoints[segment + 1] + vector3_scaled(controlPoints[segment] - controlPoints[segment + 1], reciprocal_alpha); - bezierPoints[3] = controlPoints[segment + 1]; - return CubicBezier_evaluate(bezierPoints, t); +inline Vector3 CatmullRom_evaluate( const ControlPoints& controlPoints, double t ){ + // scale t to be segment-relative + t *= double(controlPoints.size() - 1); + + // subtract segment index; + std::size_t segment = 0; + for ( std::size_t i = 0; i < controlPoints.size() - 1; ++i ) + { + if ( t <= double(i + 1) ) { + segment = i; + break; + } + } + t -= segment; + + const double reciprocal_alpha = 1.0 / 3.0; + + Vector3 bezierPoints[4]; + bezierPoints[0] = controlPoints[segment]; + bezierPoints[1] = ( segment > 0 ) + ? controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment - 1], reciprocal_alpha * 0.5 ) + : controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment], reciprocal_alpha ); + bezierPoints[2] = ( segment < controlPoints.size() - 2 ) + ? controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 2], reciprocal_alpha * 0.5 ) + : controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 1], reciprocal_alpha ); + bezierPoints[3] = controlPoints[segment + 1]; + return CubicBezier_evaluate( bezierPoints, t ); } typedef Array Knots; -inline double BSpline_basis(const Knots& knots, std::size_t i, std::size_t degree, double t) -{ - if(degree == 0) - { - if(knots[i] <= t - && t < knots[i + 1] - && knots[i] < knots[i + 1]) - { - return 1; - } - return 0; - } - double leftDenom = knots[i + degree] - knots[i]; - double left = (leftDenom == 0) ? 0 : ((t - knots[i]) / leftDenom) * BSpline_basis(knots, i, degree - 1, t); - double rightDenom = knots[i + degree + 1] - knots[i + 1]; - double right = (rightDenom == 0) ? 0 : ((knots[i + degree + 1] - t) / rightDenom) * BSpline_basis(knots, i + 1, degree - 1, t); - return left + right; +inline double BSpline_basis( const Knots& knots, std::size_t i, std::size_t degree, double t ){ + if ( degree == 0 ) { + if ( knots[i] <= t + && t < knots[i + 1] + && knots[i] < knots[i + 1] ) { + return 1; + } + return 0; + } + double leftDenom = knots[i + degree] - knots[i]; + double left = ( leftDenom == 0 ) ? 0 : ( ( t - knots[i] ) / leftDenom ) * BSpline_basis( knots, i, degree - 1, t ); + double rightDenom = knots[i + degree + 1] - knots[i + 1]; + double right = ( rightDenom == 0 ) ? 0 : ( ( knots[i + degree + 1] - t ) / rightDenom ) * BSpline_basis( knots, i + 1, degree - 1, t ); + return left + right; } -inline Vector3 BSpline_evaluate(const ControlPoints& controlPoints, const Knots& knots, std::size_t degree, double t) -{ - Vector3 result(0, 0, 0); - for(std::size_t i = 0; i < controlPoints.size(); ++i) - { - result += vector3_scaled(controlPoints[i], BSpline_basis(knots, i, degree, t)); - } - return result; +inline Vector3 BSpline_evaluate( const ControlPoints& controlPoints, const Knots& knots, std::size_t degree, double t ){ + Vector3 result( 0, 0, 0 ); + for ( std::size_t i = 0; i < controlPoints.size(); ++i ) + { + result += vector3_scaled( controlPoints[i], BSpline_basis( knots, i, degree, t ) ); + } + return result; } typedef Array NURBSWeights; -inline Vector3 NURBS_evaluate(const ControlPoints& controlPoints, const NURBSWeights& weights, const Knots& knots, std::size_t degree, double t) -{ - Vector3 result(0, 0, 0); - double denominator = 0; - for(std::size_t i = 0; i < controlPoints.size(); ++i) - { - double weight = weights[i] * BSpline_basis(knots, i, degree, t); - result += vector3_scaled(controlPoints[i], weight); - denominator += weight; - } - return result / denominator; +inline Vector3 NURBS_evaluate( const ControlPoints& controlPoints, const NURBSWeights& weights, const Knots& knots, std::size_t degree, double t ){ + Vector3 result( 0, 0, 0 ); + double denominator = 0; + for ( std::size_t i = 0; i < controlPoints.size(); ++i ) + { + double weight = weights[i] * BSpline_basis( knots, i, degree, t ); + result += vector3_scaled( controlPoints[i], weight ); + denominator += weight; + } + return result / denominator; } -inline void KnotVector_openUniform(Knots& knots, std::size_t count, std::size_t degree) -{ - knots.resize(count + degree + 1); +inline void KnotVector_openUniform( Knots& knots, std::size_t count, std::size_t degree ){ + knots.resize( count + degree + 1 ); - std::size_t equalKnots = 1; + std::size_t equalKnots = 1; - for(std::size_t i = 0; i < equalKnots; ++i) - { - knots[i] = 0; - knots[knots.size() - (i + 1)] = 1; - } + for ( std::size_t i = 0; i < equalKnots; ++i ) + { + knots[i] = 0; + knots[knots.size() - ( i + 1 )] = 1; + } - std::size_t difference = knots.size() - 2 * (equalKnots); - for(std::size_t i = 0; i < difference; ++i) - { - knots[i + equalKnots] = Knots::value_type(double(i + 1) * 1.0 / double(difference + 1)); - } + std::size_t difference = knots.size() - 2 * ( equalKnots ); + for ( std::size_t i = 0; i < difference; ++i ) + { + knots[i + equalKnots] = Knots::value_type( double(i + 1) * 1.0 / double(difference + 1) ); + } } #endif diff --git a/libs/math/expression.cpp b/libs/math/expression.cpp index 5fc8d051..13f6bfef 100644 --- a/libs/math/expression.cpp +++ b/libs/math/expression.cpp @@ -1,243 +1,209 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "expression.h" -Vector3 testAdded1(const Vector3& a, const Vector3& b) -{ - return vector3_added(a, vector3_added(a, b)); +Vector3 testAdded1( const Vector3& a, const Vector3& b ){ + return vector3_added( a, vector3_added( a, b ) ); } -Vector3 testAdded2(const Vector3& a, const Vector3& b) -{ - return vector3_for_expression( vector_added( vector3_identity(a), vector_added( vector3_identity(a), vector3_identity(b) ) ) ); +Vector3 testAdded2( const Vector3& a, const Vector3& b ){ + return vector3_for_expression( vector_added( vector3_identity( a ), vector_added( vector3_identity( a ), vector3_identity( b ) ) ) ); } -Vector3 testMultiplied1(const Vector3& a, const Vector3& b) -{ - return vector3_scaled(a, b); +Vector3 testMultiplied1( const Vector3& a, const Vector3& b ){ + return vector3_scaled( a, b ); } -Vector3 testMultiplied2(const Vector3& a, const Vector3& b) -{ - return vector3_for_expression( vector_multiplied( vector3_identity(a), vector3_identity(b) ) ); +Vector3 testMultiplied2( const Vector3& a, const Vector3& b ){ + return vector3_for_expression( vector_multiplied( vector3_identity( a ), vector3_identity( b ) ) ); } -Vector3 testCross1(const Vector3& a, const Vector3& b) -{ - return vector3_cross(a, b); +Vector3 testCross1( const Vector3& a, const Vector3& b ){ + return vector3_cross( a, b ); } -Vector3 testCross2(const Vector3& a, const Vector3& b) -{ - return vector3_for_expression( vector_cross( vector3_identity(a), vector3_identity(b) ) ); +Vector3 testCross2( const Vector3& a, const Vector3& b ){ + return vector3_for_expression( vector_cross( vector3_identity( a ), vector3_identity( b ) ) ); } -double testDot1(const Vector3& a, const Vector3& b) -{ - return vector3_dot(a, b); +double testDot1( const Vector3& a, const Vector3& b ){ + return vector3_dot( a, b ); } -double testDot2(const Vector3& a, const Vector3& b) -{ - return float_for_expression( vector_dot( vector3_identity(a), vector3_identity(b) ) ); +double testDot2( const Vector3& a, const Vector3& b ){ + return float_for_expression( vector_dot( vector3_identity( a ), vector3_identity( b ) ) ); } -double testLength1(const Vector3& a) -{ - return vector3_length(a); +double testLength1( const Vector3& a ){ + return vector3_length( a ); } -double testLength2(const Vector3& a) -{ - return float_for_expression( vector_length( vector3_identity(a) ) ); +double testLength2( const Vector3& a ){ + return float_for_expression( vector_length( vector3_identity( a ) ) ); } -Vector3 testNormalised1(const Vector3& a) -{ - return vector3_normalised(a); +Vector3 testNormalised1( const Vector3& a ){ + return vector3_normalised( a ); } -Vector3 testNormalised2(const Vector3& a) -{ - return vector3_for_expression( vector_normalised( vector3_identity(a) ) ); +Vector3 testNormalised2( const Vector3& a ){ + return vector3_for_expression( vector_normalised( vector3_identity( a ) ) ); } -Vector3 testNegated1(const Vector3& a) -{ - return vector3_negated(a); +Vector3 testNegated1( const Vector3& a ){ + return vector3_negated( a ); } -Vector3 testNegated2(const Vector3& a) -{ - return vector3_for_expression( vector_negated( vector3_identity(a) ) ); +Vector3 testNegated2( const Vector3& a ){ + return vector3_for_expression( vector_negated( vector3_identity( a ) ) ); } -Vector3 testScaled1(const Vector3& a, const double& b) -{ - return vector3_scaled(a, b); +Vector3 testScaled1( const Vector3& a, const double& b ){ + return vector3_scaled( a, b ); } -Vector3 testScaled2(const Vector3& a, const double& b) -{ - return vector3_for_expression( vector_scaled( vector3_identity(a), float_literal(b) ) ); +Vector3 testScaled2( const Vector3& a, const double& b ){ + return vector3_for_expression( vector_scaled( vector3_identity( a ), float_literal( b ) ) ); } -Vector3 testMatrixMultiplied1(const Vector3& a, const Matrix4& b) -{ - return matrix4_transformed_point(b, vector3_added(a, Vector3(1, 0, 0))); +Vector3 testMatrixMultiplied1( const Vector3& a, const Matrix4& b ){ + return matrix4_transformed_point( b, vector3_added( a, Vector3( 1, 0, 0 ) ) ); } -Vector3 testMatrixMultiplied2(const Vector3& a, const Matrix4& b) -{ - return vector3_for_expression( - point_multiplied( - vector_added( - vector3_identity(a), - vector3_literal(Vector3(1, 0, 0)) - ), - matrix4_identity(b) - ) - ); -} - -Matrix4 testMatrix4Multiplied1(const Matrix4& a, const Matrix4& b) -{ - return matrix4_multiplied_by_matrix4(a, matrix4_multiplied_by_matrix4(a, b)); +Vector3 testMatrixMultiplied2( const Vector3& a, const Matrix4& b ){ + return vector3_for_expression( + point_multiplied( + vector_added( + vector3_identity( a ), + vector3_literal( Vector3( 1, 0, 0 ) ) + ), + matrix4_identity( b ) + ) + ); } -Matrix4 testMatrix4Multiplied2(const Matrix4& a, const Matrix4& b) -{ - return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity(a), - matrix4_identity(b) - ) - ); +Matrix4 testMatrix4Multiplied1( const Matrix4& a, const Matrix4& b ){ + return matrix4_multiplied_by_matrix4( a, matrix4_multiplied_by_matrix4( a, b ) ); } -Matrix4 testMatrix4AffineMultiplied1(const Matrix4& a, const Matrix4& b) -{ - return matrix4_affine_multiplied_by_matrix4(a, b); +Matrix4 testMatrix4Multiplied2( const Matrix4& a, const Matrix4& b ){ + return matrix4_for_expression( + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( b ) + ) + ); } -Matrix4 testMatrix4AffineMultiplied2(const Matrix4& a, const Matrix4& b) -{ - return matrix4_affine_for_expression( - matrix4_multiplied( - matrix4_identity(a), - matrix4_identity(b) - ) - ); +Matrix4 testMatrix4AffineMultiplied1( const Matrix4& a, const Matrix4& b ){ + return matrix4_affine_multiplied_by_matrix4( a, b ); } -Matrix4 testMatrix4MultipliedConstant1(const Matrix4& a) -{ - return matrix4_multiplied_by_matrix4(a, g_matrix4_identity); +Matrix4 testMatrix4AffineMultiplied2( const Matrix4& a, const Matrix4& b ){ + return matrix4_affine_for_expression( + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( b ) + ) + ); } -Matrix4 testMatrix4MultipliedConstant2(const Matrix4& a) -{ - return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity(a), - matrix4_identity(g_matrix4_identity) - ) - ); -} -Matrix4 testMatrix4Transposed1(const Matrix4& a) -{ - return matrix4_transposed(a); +Matrix4 testMatrix4MultipliedConstant1( const Matrix4& a ){ + return matrix4_multiplied_by_matrix4( a, g_matrix4_identity ); } -Matrix4 testMatrix4Transposed2(const Matrix4& a) -{ - return matrix4_for_expression( matrix_transposed( matrix4_identity(a) ) ); +Matrix4 testMatrix4MultipliedConstant2( const Matrix4& a ){ + return matrix4_for_expression( + matrix4_multiplied( + matrix4_identity( a ), + matrix4_identity( g_matrix4_identity ) + ) + ); +} +Matrix4 testMatrix4Transposed1( const Matrix4& a ){ + return matrix4_transposed( a ); } -Vector3 testMulti1(const Matrix4& a, const Vector3& b, const Vector3& c) -{ - return vector3_added(matrix4_transformed_point(matrix4_transposed(a), b), c); +Matrix4 testMatrix4Transposed2( const Matrix4& a ){ + return matrix4_for_expression( matrix_transposed( matrix4_identity( a ) ) ); } -Vector3 testMulti2(const Matrix4& a, const Vector3& b, const Vector3& c) -{ - return vector3_for_expression( - vector_added( - point_multiplied( - vector3_identity(b), - matrix_transposed(matrix4_identity(a)) - ), - vector3_identity(c) - ) - ); +Vector3 testMulti1( const Matrix4& a, const Vector3& b, const Vector3& c ){ + return vector3_added( matrix4_transformed_point( matrix4_transposed( a ), b ), c ); +} + +Vector3 testMulti2( const Matrix4& a, const Vector3& b, const Vector3& c ){ + return vector3_for_expression( + vector_added( + point_multiplied( + vector3_identity( b ), + matrix_transposed( matrix4_identity( a ) ) + ), + vector3_identity( c ) + ) + ); } template class TestBinaryFunction { - typedef Value(*Function)(const First&, const Second&); - Function m_function; +typedef Value ( *Function )( const First&, const Second& ); +Function m_function; public: - TestBinaryFunction(Function function) : m_function(function) - { - } - Value run(const First& first, const Second& second) const - { - return m_function(first, second); - } +TestBinaryFunction( Function function ) : m_function( function ){ +} +Value run( const First& first, const Second& second ) const { + return m_function( first, second ); +} }; template class TestUnaryFunction { - typedef Value(*Function)(const First&); - Function m_function; +typedef Value ( *Function )( const First& ); +Function m_function; public: - TestUnaryFunction(Function function) : m_function(function) - { - } - Value run(const First& first) const - { - return m_function(first); - } +TestUnaryFunction( Function function ) : m_function( function ){ +} +Value run( const First& first ) const { + return m_function( first ); +} }; class TestAll { public: - TestAll() - { - Vector3 result1 = TestBinaryFunction(testAdded1).run(Vector3(0, 0, 0), Vector3(1, 1, 1)); - Vector3 result2 = TestBinaryFunction(testAdded2).run(Vector3(0, 0, 0), Vector3(1, 1, 1)); - Vector3 result3 = TestBinaryFunction(testMultiplied1).run(Vector3(1, 2, 3), Vector3(2, 1, 0.5f)); - Vector3 result4 = TestBinaryFunction(testMultiplied2).run(Vector3(1, 2, 3), Vector3(2, 1, 0.5f)); - Vector3 result5 = TestBinaryFunction(testScaled1).run(Vector3(1, 2, 3), 2.0); - Vector3 result6 = TestBinaryFunction(testScaled2).run(Vector3(1, 2, 3), 2.0); - Vector3 result7 = TestBinaryFunction(testMatrixMultiplied1).run(Vector3(1, 2, 3), matrix4_rotation_for_x_degrees(90)); - Vector3 result8 = TestBinaryFunction(testMatrixMultiplied2).run(Vector3(1, 2, 3), matrix4_rotation_for_x_degrees(90)); - Vector3 result9 = TestUnaryFunction(testNormalised1).run(Vector3(1, 2, 3)); - Vector3 result10 = TestUnaryFunction(testNormalised2).run(Vector3(1, 2, 3)); - } +TestAll(){ + Vector3 result1 = TestBinaryFunction( testAdded1 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); + Vector3 result2 = TestBinaryFunction( testAdded2 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); + Vector3 result3 = TestBinaryFunction( testMultiplied1 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); + Vector3 result4 = TestBinaryFunction( testMultiplied2 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); + Vector3 result5 = TestBinaryFunction( testScaled1 ).run( Vector3( 1, 2, 3 ), 2.0 ); + Vector3 result6 = TestBinaryFunction( testScaled2 ).run( Vector3( 1, 2, 3 ), 2.0 ); + Vector3 result7 = TestBinaryFunction( testMatrixMultiplied1 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); + Vector3 result8 = TestBinaryFunction( testMatrixMultiplied2 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); + Vector3 result9 = TestUnaryFunction( testNormalised1 ).run( Vector3( 1, 2, 3 ) ); + Vector3 result10 = TestUnaryFunction( testNormalised2 ).run( Vector3( 1, 2, 3 ) ); +} } g_testAll; - diff --git a/libs/math/expression.h b/libs/math/expression.h index c609bb16..0b995e3a 100644 --- a/libs/math/expression.h +++ b/libs/math/expression.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_EXPRESSION_H) +#if !defined ( INCLUDED_EXPRESSION_H ) #define INCLUDED_EXPRESSION_H #include @@ -27,108 +27,94 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class Literal { - Value m_value; +Value m_value; public: - typedef Value value_type; - - Literal(const Value& value) - : m_value(value) - { - } - const value_type& eval() const - { - return m_value; - } +typedef Value value_type; + +Literal( const Value& value ) + : m_value( value ){ +} +const value_type& eval() const { + return m_value; +} }; template -inline Literal float_literal(const Value& value) -{ - return Literal(value); +inline Literal float_literal( const Value& value ){ + return Literal( value ); } template -inline float float_for_expression(const Expression& expression) -{ - return expression.eval(); +inline float float_for_expression( const Expression& expression ){ + return expression.eval(); } template class ScalarDivided { - First first; - Second second; +First first; +Second second; public: - typedef typename First::value_type value_type; - - ScalarDivided(const First& first_, const Second& second_) : first(first_), second(second_) - { - } - value_type eval() const - { - return static_cast(first.eval() / second.eval()); - } +typedef typename First::value_type value_type; + +ScalarDivided( const First& first_, const Second& second_ ) : first( first_ ), second( second_ ){ +} +value_type eval() const { + return static_cast( first.eval() / second.eval() ); +} }; template -inline ScalarDivided float_divided(const First& first, const Second& second) -{ - return ScalarDivided(first, second); +inline ScalarDivided float_divided( const First& first, const Second& second ){ + return ScalarDivided( first, second ); } template -inline ScalarDivided, First> float_reciprocal(const First& first) -{ - typedef typename First::value_type first_value_type; - return ScalarDivided, First>(float_literal(first_value_type(1.0)), first); +inline ScalarDivided, First> float_reciprocal( const First& first ){ + typedef typename First::value_type first_value_type; + return ScalarDivided, First>( float_literal( first_value_type( 1.0 ) ), first ); } template class SquareRoot { - First first; +First first; public: - typedef typename First::value_type value_type; - - SquareRoot(const First& first_) : first(first_) - { - } - value_type eval() const - { - return static_cast(sqrt(first.eval())); - } +typedef typename First::value_type value_type; + +SquareRoot( const First& first_ ) : first( first_ ){ +} +value_type eval() const { + return static_cast( sqrt( first.eval() ) ); +} }; template -inline SquareRoot float_square_root(const First& first) -{ - return SquareRoot(first); +inline SquareRoot float_square_root( const First& first ){ + return SquareRoot( first ); } template class BasicVector3Literal { - const BasicVector3 m_value; +const BasicVector3 m_value; public: - typedef Element value_type; - typedef IntegralConstant<3> dimension; - - BasicVector3Literal(const BasicVector3& value) - : m_value(value) - { - } - const value_type& eval(unsigned int i) const - { - return m_value[i]; - } +typedef Element value_type; +typedef IntegralConstant<3> dimension; + +BasicVector3Literal( const BasicVector3& value ) + : m_value( value ){ +} +const value_type& eval( unsigned int i ) const { + return m_value[i]; +} }; template -inline BasicVector3Literal vector3_literal(const BasicVector3& value) -{ - return BasicVector3Literal(value); +inline BasicVector3Literal vector3_literal( const BasicVector3& value ){ + return BasicVector3Literal( value ); } typedef BasicVector3Literal Vector3Literal; @@ -136,53 +122,47 @@ typedef BasicVector3Literal Vector3Literal; template class BasicVector3Identity { - const BasicVector3& m_value; +const BasicVector3& m_value; public: - typedef Element value_type; - typedef IntegralConstant<3> dimension; - - BasicVector3Identity(const BasicVector3& value) - : m_value(value) - { - } - const value_type& eval(unsigned int i) const - { - return m_value[i]; - } +typedef Element value_type; +typedef IntegralConstant<3> dimension; + +BasicVector3Identity( const BasicVector3& value ) + : m_value( value ){ +} +const value_type& eval( unsigned int i ) const { + return m_value[i]; +} }; template -inline BasicVector3Identity vector3_identity(const BasicVector3& value) -{ - return BasicVector3Identity(value); +inline BasicVector3Identity vector3_identity( const BasicVector3& value ){ + return BasicVector3Identity( value ); } typedef BasicVector3Identity Vector3Identity; template -inline BasicVector3 vector3_for_expression(const Expression& expression) -{ - return Vector3(expression.eval(0), expression.eval(1), expression.eval(2)); +inline BasicVector3 vector3_for_expression( const Expression& expression ){ + return Vector3( expression.eval( 0 ), expression.eval( 1 ), expression.eval( 2 ) ); } template class VectorScalar { - First first; - Literal second; +First first; +Literal second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorScalar(const First& first_, const Second& second_) - : first(first_), second(second_.eval()) - { - } - value_type eval(unsigned int i) const - { - return Operation::apply( first.eval(i), second.eval() ); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorScalar( const First& first_, const Second& second_ ) + : first( first_ ), second( second_.eval() ){ +} +value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ), second.eval() ); +} }; @@ -190,428 +170,383 @@ public: template class VectorVector { - First first; - Second second; +First first; +Second second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorVector(const First& first_, const Second& second_) - : first(first_), second(second_) - { - } - value_type eval(unsigned int i) const - { - return Operation::apply(first.eval(i), second.eval(i)); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorVector( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ +} +value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ), second.eval( i ) ); +} }; template class Added { public: - typedef First value_type; +typedef First value_type; - static value_type apply(const First& first, const Second& second) - { - return static_cast(first + second); - } +static value_type apply( const First& first, const Second& second ){ + return static_cast( first + second ); +} }; template inline VectorVector, First, Second> -vector_added(const First& first, const Second& second) -{ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorVector, First, Second>(first, second); +vector_added( const First& first, const Second& second ){ + typedef typename First::value_type first_value_type; + typedef typename Second::value_type second_value_type; + return VectorVector, First, Second>( first, second ); } template class Multiplied { public: - typedef First value_type; +typedef First value_type; - static value_type apply(const First& first, const Second& second) - { - return static_cast(first * second); - } +static value_type apply( const First& first, const Second& second ){ + return static_cast( first * second ); +} }; template inline VectorVector, First, Second> -vector_multiplied(const First& first, const Second& second) -{ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorVector, First, Second>(first, second); +vector_multiplied( const First& first, const Second& second ){ + typedef typename First::value_type first_value_type; + typedef typename Second::value_type second_value_type; + return VectorVector, First, Second>( first, second ); } template inline VectorScalar, First, Second> -vector_scaled(const First& first, const Second& second) -{ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorScalar, First, Second>(first, second); +vector_scaled( const First& first, const Second& second ){ + typedef typename First::value_type first_value_type; + typedef typename Second::value_type second_value_type; + return VectorScalar, First, Second>( first, second ); } template class Negated { public: - typedef First value_type; +typedef First value_type; - static value_type apply(const First& first) - { - return -first; - } +static value_type apply( const First& first ){ + return -first; +} }; template class VectorUnary { - First first; +First first; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorUnary(const First& first_) : first(first_) - { - } - value_type eval(unsigned int i) const - { - return Operation::apply(first.eval(i)); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorUnary( const First& first_ ) : first( first_ ){ +} +value_type eval( unsigned int i ) const { + return Operation::apply( first.eval( i ) ); +} }; template inline VectorUnary > -vector_negated(const First& first) -{ - typedef typename First::value_type first_value_type; - return VectorUnary >(first); +vector_negated( const First& first ){ + typedef typename First::value_type first_value_type; + return VectorUnary >( first ); } template class VectorCross { - First first; - Second second; +First first; +Second second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorCross(const First& first_, const Second& second_) - : first(first_), second(second_) - { - } - value_type eval(unsigned int i) const - { - return first.eval((i+1)%3) * second.eval((i+2)%3) - first.eval((i+2)%3) * second.eval((i+1)%3); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorCross( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ +} +value_type eval( unsigned int i ) const { + return first.eval( ( i + 1 ) % 3 ) * second.eval( ( i + 2 ) % 3 ) - first.eval( ( i + 2 ) % 3 ) * second.eval( ( i + 1 ) % 3 ); +} }; template inline VectorCross -vector_cross(const First& first, const Second& second) -{ - return VectorCross(first, second); +vector_cross( const First& first, const Second& second ){ + return VectorCross( first, second ); } template class VectorDot { - First first; - Second second; +First first; +Second second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorDot(const First& first_, const Second& second_) - : first(first_), second(second_) - { - } - - template - struct eval_dot - { - static value_type apply(const First& first, const Second& second) - { - return static_cast( - first.eval(Index::VALUE) * second.eval(Index::VALUE) - + eval_dot< IntegralConstant >::apply(first, second) - ); - } - }; - - template<> - struct eval_dot< IntegralConstant<0> > - { - static value_type apply(const First& first, const Second& second) - { - return first.eval(0) * second.eval(0); - } - }; - - value_type eval() const - { - return eval_dot< IntegralConstant >::apply(first, second); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorDot( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ +} + +template +struct eval_dot +{ + static value_type apply( const First& first, const Second& second ){ + return static_cast( + first.eval( Index::VALUE ) * second.eval( Index::VALUE ) + + eval_dot< IntegralConstant >::apply( first, second ) + ); + } +}; + +template<> +struct eval_dot< IntegralConstant<0> > +{ + static value_type apply( const First& first, const Second& second ){ + return first.eval( 0 ) * second.eval( 0 ); + } +}; + +value_type eval() const { + return eval_dot< IntegralConstant >::apply( first, second ); +} }; template -inline VectorDot vector_dot(const First& first, const Second& second) -{ - return VectorDot(first, second); +inline VectorDot vector_dot( const First& first, const Second& second ){ + return VectorDot( first, second ); } template class VectorLengthSquared { - First first; +First first; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - VectorLengthSquared(const First& first_) - : first(first_) - { - } - - static value_type squared(const value_type& value) - { - return value * value; - } - - template - struct eval_squared - { - static value_type apply(const First& first) - { - return static_cast( - squared(first.eval(Index::VALUE)) - + eval_squared< IntegralConstant >::apply(first) - ); - } - }; - - template<> - struct eval_squared< IntegralConstant<0> > - { - static value_type apply(const First& first) - { - return squared(first.eval(0)); - } - }; - - value_type eval() const - { - return eval_squared< IntegralConstant >::apply(first); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +VectorLengthSquared( const First& first_ ) + : first( first_ ){ +} + +static value_type squared( const value_type& value ){ + return value * value; +} + +template +struct eval_squared +{ + static value_type apply( const First& first ){ + return static_cast( + squared( first.eval( Index::VALUE ) ) + + eval_squared< IntegralConstant >::apply( first ) + ); + } }; -template -inline VectorLengthSquared vector_length_squared(const First& first) +template<> +struct eval_squared< IntegralConstant<0> > { - return VectorLengthSquared(first); + static value_type apply( const First& first ){ + return squared( first.eval( 0 ) ); + } +}; + +value_type eval() const { + return eval_squared< IntegralConstant >::apply( first ); } +}; template -inline SquareRoot< VectorLengthSquared > vector_length(const First& first) -{ - return float_square_root(vector_length_squared(first)); +inline VectorLengthSquared vector_length_squared( const First& first ){ + return VectorLengthSquared( first ); +} + +template +inline SquareRoot< VectorLengthSquared > vector_length( const First& first ){ + return float_square_root( vector_length_squared( first ) ); } #if 1 template inline VectorScalar< - Multiplied, - First, - // multiple evaulations of subexpression - ScalarDivided< - Literal, - SquareRoot< - VectorLengthSquared - > - > -> vector_normalised(const First& first) -{ - typedef typename First::value_type first_value_type; - return vector_scaled(first, float_reciprocal(vector_length(first))); + Multiplied, + First, + // multiple evaulations of subexpression + ScalarDivided< + Literal, + SquareRoot< + VectorLengthSquared + > + > + > vector_normalised( const First& first ){ + typedef typename First::value_type first_value_type; + return vector_scaled( first, float_reciprocal( vector_length( first ) ) ); } #else template inline VectorScalar< - Multiplied, - First, - // single evaluation of subexpression - Literal -> -vector_normalised(const First& first) -{ - typedef typename First::value_type first_value_type; - return vector_scaled(first, float_literal(static_cast(first_value_type(1.0) / vector_length(first).eval()))); + Multiplied, + First, + // single evaluation of subexpression + Literal + > +vector_normalised( const First& first ){ + typedef typename First::value_type first_value_type; + return vector_scaled( first, float_literal( static_cast( first_value_type( 1.0 ) / vector_length( first ).eval() ) ) ); } #endif class Matrix4Literal { - const Matrix4 m_value; +const Matrix4 m_value; public: - typedef float value_type; - typedef IntegralConstant<4> dimension0; - typedef IntegralConstant<4> dimension1; - - Matrix4Literal(const Matrix4& value) - : m_value(value) - { - } - const value_type& eval(unsigned int r, unsigned int c) const - { - return m_value[r*4+c]; - } +typedef float value_type; +typedef IntegralConstant<4> dimension0; +typedef IntegralConstant<4> dimension1; + +Matrix4Literal( const Matrix4& value ) + : m_value( value ){ +} +const value_type& eval( unsigned int r, unsigned int c ) const { + return m_value[r * 4 + c]; +} }; -inline Matrix4Literal matrix4_literal(const Matrix4& value) -{ - return Matrix4Literal(value); +inline Matrix4Literal matrix4_literal( const Matrix4& value ){ + return Matrix4Literal( value ); } class Matrix4Identity { - const Matrix4& m_value; +const Matrix4& m_value; public: - typedef float value_type; - typedef IntegralConstant<4> dimension0; - typedef IntegralConstant<4> dimension1; - - Matrix4Identity(const Matrix4& value) - : m_value(value) - { - } - const value_type& eval(unsigned int r, unsigned int c) const - { - return m_value[r*4+c]; - } +typedef float value_type; +typedef IntegralConstant<4> dimension0; +typedef IntegralConstant<4> dimension1; + +Matrix4Identity( const Matrix4& value ) + : m_value( value ){ +} +const value_type& eval( unsigned int r, unsigned int c ) const { + return m_value[r * 4 + c]; +} }; -inline Matrix4Identity matrix4_identity(const Matrix4& value) -{ - return Matrix4Identity(value); +inline Matrix4Identity matrix4_identity( const Matrix4& value ){ + return Matrix4Identity( value ); } template -inline Matrix4 matrix4_for_expression(const Expression& expression) -{ - return Matrix4( - expression.eval(0, 0), expression.eval(0, 1), expression.eval(0, 2), expression.eval(0, 3), - expression.eval(1, 0), expression.eval(1, 1), expression.eval(1, 2), expression.eval(1, 3), - expression.eval(2, 0), expression.eval(2, 1), expression.eval(2, 2), expression.eval(2, 3), - expression.eval(3, 0), expression.eval(3, 1), expression.eval(3, 2), expression.eval(3, 3) - ); +inline Matrix4 matrix4_for_expression( const Expression& expression ){ + return Matrix4( + expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), expression.eval( 0, 3 ), + expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), expression.eval( 1, 3 ), + expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), expression.eval( 2, 3 ), + expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), expression.eval( 3, 3 ) + ); } template -inline Matrix4 matrix4_affine_for_expression(const Expression& expression) -{ - return Matrix4( - expression.eval(0, 0), expression.eval(0, 1), expression.eval(0, 2), 0, - expression.eval(1, 0), expression.eval(1, 1), expression.eval(1, 2), 0, - expression.eval(2, 0), expression.eval(2, 1), expression.eval(2, 2), 0, - expression.eval(3, 0), expression.eval(3, 1), expression.eval(3, 2), 1 - ); +inline Matrix4 matrix4_affine_for_expression( const Expression& expression ){ + return Matrix4( + expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), 0, + expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), 0, + expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), 0, + expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), 1 + ); } template class PointMultiplied { - const First& first; - const Second& second; +const First& first; +const Second& second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension dimension; - - PointMultiplied(const First& first_, const Second& second_) - : first(first_), second(second_) - { - } - value_type eval(unsigned int i) const - { - return static_cast(second.eval(0, i) * first.eval(0) - + second.eval(1, i) * first.eval(1) - + second.eval(2, i) * first.eval(2) - + second.eval(3, i)); - } +typedef typename First::value_type value_type; +typedef typename First::dimension dimension; + +PointMultiplied( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ +} +value_type eval( unsigned int i ) const { + return static_cast( second.eval( 0, i ) * first.eval( 0 ) + + second.eval( 1, i ) * first.eval( 1 ) + + second.eval( 2, i ) * first.eval( 2 ) + + second.eval( 3, i ) ); +} }; template -inline PointMultiplied point_multiplied(const First& point, const Second& matrix) -{ - return PointMultiplied(point, matrix); +inline PointMultiplied point_multiplied( const First& point, const Second& matrix ){ + return PointMultiplied( point, matrix ); } template class Matrix4Multiplied { - const First& first; - const Second& second; +const First& first; +const Second& second; public: - typedef typename First::value_type value_type; - typedef typename First::dimension0 dimension0; - typedef typename First::dimension1 dimension1; - - Matrix4Multiplied(const First& first_, const Second& second_) - : first(first_), second(second_) - { - } - - value_type eval(unsigned int r, unsigned int c) const - { - return static_cast( - second.eval(r, 0) * first.eval(0, c) - + second.eval(r, 1) * first.eval(1, c) - + second.eval(r, 2) * first.eval(2, c) - + second.eval(r, 3) * first.eval(3, c) - ); - } +typedef typename First::value_type value_type; +typedef typename First::dimension0 dimension0; +typedef typename First::dimension1 dimension1; + +Matrix4Multiplied( const First& first_, const Second& second_ ) + : first( first_ ), second( second_ ){ +} + +value_type eval( unsigned int r, unsigned int c ) const { + return static_cast( + second.eval( r, 0 ) * first.eval( 0, c ) + + second.eval( r, 1 ) * first.eval( 1, c ) + + second.eval( r, 2 ) * first.eval( 2, c ) + + second.eval( r, 3 ) * first.eval( 3, c ) + ); +} }; template -inline Matrix4Multiplied matrix4_multiplied(const First& first, const Second& second) -{ - return Matrix4Multiplied(first, second); +inline Matrix4Multiplied matrix4_multiplied( const First& first, const Second& second ){ + return Matrix4Multiplied( first, second ); } template class MatrixTransposed { - const First& first; +const First& first; public: - typedef typename First::value_type value_type; - typedef typename First::dimension0 dimension0; - typedef typename First::dimension1 dimension1; - - MatrixTransposed(const First& first_) - : first(first_) - { - } - - value_type eval(unsigned int r, unsigned int c) const - { - return first.eval(c, r); - } +typedef typename First::value_type value_type; +typedef typename First::dimension0 dimension0; +typedef typename First::dimension1 dimension1; + +MatrixTransposed( const First& first_ ) + : first( first_ ){ +} + +value_type eval( unsigned int r, unsigned int c ) const { + return first.eval( c, r ); +} }; template -inline MatrixTransposed matrix_transposed(const First& first) -{ - return MatrixTransposed(first); +inline MatrixTransposed matrix_transposed( const First& first ){ + return MatrixTransposed( first ); } #endif diff --git a/libs/math/frustum.cpp b/libs/math/frustum.cpp index 84481e20..b977549d 100644 --- a/libs/math/frustum.cpp +++ b/libs/math/frustum.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "frustum.h" - diff --git a/libs/math/frustum.h b/libs/math/frustum.h index fe98db20..08990aec 100644 --- a/libs/math/frustum.h +++ b/libs/math/frustum.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_FRUSTUM_H) +#if !defined( INCLUDED_MATH_FRUSTUM_H ) #define INCLUDED_MATH_FRUSTUM_H /// \file @@ -31,26 +31,25 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "math/aabb.h" #include "math/line.h" -inline Matrix4 matrix4_frustum(float left, float right, float bottom, float top, float nearval, float farval) -{ - return Matrix4( - static_cast( (2*nearval) / (right-left) ), - 0, - 0, - 0, - 0, - static_cast( (2*nearval) / (top-bottom) ), - 0, - 0, - static_cast( (right+left) / (right-left) ), - static_cast( (top+bottom) / (top-bottom) ), - static_cast( -(farval+nearval) / (farval-nearval) ), - -1, - 0, - 0, - static_cast( -(2*farval*nearval) / (farval-nearval) ), - 0 - ); +inline Matrix4 matrix4_frustum( float left, float right, float bottom, float top, float nearval, float farval ){ + return Matrix4( + static_cast( ( 2 * nearval ) / ( right - left ) ), + 0, + 0, + 0, + 0, + static_cast( ( 2 * nearval ) / ( top - bottom ) ), + 0, + 0, + static_cast( ( right + left ) / ( right - left ) ), + static_cast( ( top + bottom ) / ( top - bottom ) ), + static_cast( -( farval + nearval ) / ( farval - nearval ) ), + -1, + 0, + 0, + static_cast( -( 2 * farval * nearval ) / ( farval - nearval ) ), + 0 + ); } @@ -69,296 +68,297 @@ template class Vector4ClipLT { public: - static bool compare(const Vector4& self) - { - return self[Index::VALUE] < self[3]; - } - static double scale(const Vector4& self, const Vector4& other) - { - return (self[Index::VALUE] - self[3]) / (other[3] - other[Index::VALUE]); - } +static bool compare( const Vector4& self ){ + return self[Index::VALUE] < self[3]; +} +static double scale( const Vector4& self, const Vector4& other ){ + return ( self[Index::VALUE] - self[3] ) / ( other[3] - other[Index::VALUE] ); +} }; template class Vector4ClipGT { public: - static bool compare(const Vector4& self) - { - return self[Index::VALUE] > -self[3]; - } - static double scale(const Vector4& self, const Vector4& other) - { - return (self[Index::VALUE] + self[3]) / (-other[3] - other[Index::VALUE]); - } +static bool compare( const Vector4& self ){ + return self[Index::VALUE] > -self[3]; +} +static double scale( const Vector4& self, const Vector4& other ){ + return ( self[Index::VALUE] + self[3] ) / ( -other[3] - other[Index::VALUE] ); +} }; template class Vector4ClipPolygon { public: - typedef Vector4* iterator; - typedef const Vector4* const_iterator; - - static std::size_t apply(const_iterator first, const_iterator last, iterator out) - { - const_iterator next = first, i = last - 1; - iterator tmp(out); - bool b0 = ClipPlane::compare(*i); - while(next != last) - { - bool b1 = ClipPlane::compare(*next); - if(b0 ^ b1) - { - *out = vector4_subtracted(*next, *i); - - double scale = ClipPlane::scale(*i, *out); - - (*out)[0] = static_cast((*i)[0] + scale*((*out)[0])); - (*out)[1] = static_cast((*i)[1] + scale*((*out)[1])); - (*out)[2] = static_cast((*i)[2] + scale*((*out)[2])); - (*out)[3] = static_cast((*i)[3] + scale*((*out)[3])); - - ++out; - } - - if(b1) - { - *out = *next; - ++out; - } - - i = next; - ++next; - b0 = b1; - } - - return out - tmp; - } +typedef Vector4* iterator; +typedef const Vector4* const_iterator; + +static std::size_t apply( const_iterator first, const_iterator last, iterator out ){ + const_iterator next = first, i = last - 1; + iterator tmp( out ); + bool b0 = ClipPlane::compare( *i ); + while ( next != last ) + { + bool b1 = ClipPlane::compare( *next ); + if ( b0 ^ b1 ) { + *out = vector4_subtracted( *next, *i ); + + double scale = ClipPlane::scale( *i, *out ); + + ( *out )[0] = static_cast( ( *i )[0] + scale * ( ( *out )[0] ) ); + ( *out )[1] = static_cast( ( *i )[1] + scale * ( ( *out )[1] ) ); + ( *out )[2] = static_cast( ( *i )[2] + scale * ( ( *out )[2] ) ); + ( *out )[3] = static_cast( ( *i )[3] + scale * ( ( *out )[3] ) ); + + ++out; + } + + if ( b1 ) { + *out = *next; + ++out; + } + + i = next; + ++next; + b0 = b1; + } + + return out - tmp; +} }; -#define CLIP_X_LT_W(p) (Vector4ClipLT< IntegralConstant<0> >::compare(p)) -#define CLIP_X_GT_W(p) (Vector4ClipGT< IntegralConstant<0> >::compare(p)) -#define CLIP_Y_LT_W(p) (Vector4ClipLT< IntegralConstant<1> >::compare(p)) -#define CLIP_Y_GT_W(p) (Vector4ClipGT< IntegralConstant<1> >::compare(p)) -#define CLIP_Z_LT_W(p) (Vector4ClipLT< IntegralConstant<2> >::compare(p)) -#define CLIP_Z_GT_W(p) (Vector4ClipGT< IntegralConstant<2> >::compare(p)) - -inline ClipResult homogenous_clip_point(const Vector4& clipped) -{ - ClipResult result = c_CLIP_FAIL; - if(CLIP_X_LT_W(clipped)) result &= ~c_CLIP_LT_X; // X < W - if(CLIP_X_GT_W(clipped)) result &= ~c_CLIP_GT_X; // X > -W - if(CLIP_Y_LT_W(clipped)) result &= ~c_CLIP_LT_Y; // Y < W - if(CLIP_Y_GT_W(clipped)) result &= ~c_CLIP_GT_Y; // Y > -W - if(CLIP_Z_LT_W(clipped)) result &= ~c_CLIP_LT_Z; // Z < W - if(CLIP_Z_GT_W(clipped)) result &= ~c_CLIP_GT_Z; // Z > -W - return result; +#define CLIP_X_LT_W( p ) ( Vector4ClipLT< IntegralConstant<0> >::compare( p ) ) +#define CLIP_X_GT_W( p ) ( Vector4ClipGT< IntegralConstant<0> >::compare( p ) ) +#define CLIP_Y_LT_W( p ) ( Vector4ClipLT< IntegralConstant<1> >::compare( p ) ) +#define CLIP_Y_GT_W( p ) ( Vector4ClipGT< IntegralConstant<1> >::compare( p ) ) +#define CLIP_Z_LT_W( p ) ( Vector4ClipLT< IntegralConstant<2> >::compare( p ) ) +#define CLIP_Z_GT_W( p ) ( Vector4ClipGT< IntegralConstant<2> >::compare( p ) ) + +inline ClipResult homogenous_clip_point( const Vector4& clipped ){ + ClipResult result = c_CLIP_FAIL; + if ( CLIP_X_LT_W( clipped ) ) { + result &= ~c_CLIP_LT_X; // X < W + } + if ( CLIP_X_GT_W( clipped ) ) { + result &= ~c_CLIP_GT_X; // X > -W + } + if ( CLIP_Y_LT_W( clipped ) ) { + result &= ~c_CLIP_LT_Y; // Y < W + } + if ( CLIP_Y_GT_W( clipped ) ) { + result &= ~c_CLIP_GT_Y; // Y > -W + } + if ( CLIP_Z_LT_W( clipped ) ) { + result &= ~c_CLIP_LT_Z; // Z < W + } + if ( CLIP_Z_GT_W( clipped ) ) { + result &= ~c_CLIP_GT_Z; // Z > -W + } + return result; } /// \brief Clips \p point by canonical matrix \p self. /// Stores the result in \p clipped. /// Returns a bitmask indicating which clip-planes the point was outside. -inline ClipResult matrix4_clip_point(const Matrix4& self, const Vector3& point, Vector4& clipped) -{ - clipped[0] = point[0]; - clipped[1] = point[1]; - clipped[2] = point[2]; - clipped[3] = 1; - matrix4_transform_vector4(self, clipped); - return homogenous_clip_point(clipped); +inline ClipResult matrix4_clip_point( const Matrix4& self, const Vector3& point, Vector4& clipped ){ + clipped[0] = point[0]; + clipped[1] = point[1]; + clipped[2] = point[2]; + clipped[3] = 1; + matrix4_transform_vector4( self, clipped ); + return homogenous_clip_point( clipped ); } -inline std::size_t homogenous_clip_triangle(Vector4 clipped[9]) -{ - Vector4 buffer[9]; - std::size_t count = 3; - count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<0> > >::apply(clipped, clipped + count, buffer); - count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<0> > >::apply(buffer, buffer + count, clipped); - count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<1> > >::apply(clipped, clipped + count, buffer); - count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<1> > >::apply(buffer, buffer + count, clipped); - count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<2> > >::apply(clipped, clipped + count, buffer); - return Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<2> > >::apply(buffer, buffer + count, clipped); +inline std::size_t homogenous_clip_triangle( Vector4 clipped[9] ){ + Vector4 buffer[9]; + std::size_t count = 3; + count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<0> > >::apply( clipped, clipped + count, buffer ); + count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<0> > >::apply( buffer, buffer + count, clipped ); + count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<1> > >::apply( clipped, clipped + count, buffer ); + count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<1> > >::apply( buffer, buffer + count, clipped ); + count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<2> > >::apply( clipped, clipped + count, buffer ); + return Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<2> > >::apply( buffer, buffer + count, clipped ); } /// \brief Transforms and clips the triangle formed by \p p0, \p p1, \p p2 by the canonical matrix \p self. /// Stores the resulting polygon in \p clipped. /// Returns the number of points in the resulting polygon. -inline std::size_t matrix4_clip_triangle(const Matrix4& self, const Vector3& p0, const Vector3& p1, const Vector3& p2, Vector4 clipped[9]) -{ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - clipped[2][0] = p2[0]; - clipped[2][1] = p2[1]; - clipped[2][2] = p2[2]; - clipped[2][3] = 1; - - matrix4_transform_vector4(self, clipped[0]); - matrix4_transform_vector4(self, clipped[1]); - matrix4_transform_vector4(self, clipped[2]); - - return homogenous_clip_triangle(clipped); -} - -inline std::size_t homogenous_clip_line(Vector4 clipped[2]) -{ - const Vector4& p0 = clipped[0]; - const Vector4& p1 = clipped[1]; - - // early out - { - ClipResult mask0 = homogenous_clip_point(clipped[0]); - ClipResult mask1 = homogenous_clip_point(clipped[1]); - - if((mask0 | mask1) == c_CLIP_PASS) // both points passed all planes - return 2; - - if(mask0 & mask1) // both points failed any one plane - return 0; - } - - { - const bool index = CLIP_X_LT_W(p0); - if(index ^ CLIP_X_LT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[0] - p0[3]) / (clip[3] - clip[0]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - { - const bool index = CLIP_X_GT_W(p0); - if(index ^ CLIP_X_GT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[0] + p0[3]) / (-clip[3] - clip[0]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - { - const bool index = CLIP_Y_LT_W(p0); - if(index ^ CLIP_Y_LT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[1] - p0[3]) / (clip[3] - clip[1]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - { - const bool index = CLIP_Y_GT_W(p0); - if(index ^ CLIP_Y_GT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[1] + p0[3]) / (-clip[3] - clip[1]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - { - const bool index = CLIP_Z_LT_W(p0); - if(index ^ CLIP_Z_LT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[2] - p0[3]) / (clip[3] - clip[2]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - { - const bool index = CLIP_Z_GT_W(p0); - if(index ^ CLIP_Z_GT_W(p1)) - { - Vector4 clip(vector4_subtracted(p1, p0)); - - double scale = (p0[2] + p0[3]) / (-clip[3] - clip[2]); - - clip[0] = static_cast(p0[0] + scale * clip[0]); - clip[1] = static_cast(p0[1] + scale * clip[1]); - clip[2] = static_cast(p0[2] + scale * clip[2]); - clip[3] = static_cast(p0[3] + scale * clip[3]); - - clipped[index] = clip; - } - else if(index == 0) - return 0; - } - - return 2; +inline std::size_t matrix4_clip_triangle( const Matrix4& self, const Vector3& p0, const Vector3& p1, const Vector3& p2, Vector4 clipped[9] ){ + clipped[0][0] = p0[0]; + clipped[0][1] = p0[1]; + clipped[0][2] = p0[2]; + clipped[0][3] = 1; + clipped[1][0] = p1[0]; + clipped[1][1] = p1[1]; + clipped[1][2] = p1[2]; + clipped[1][3] = 1; + clipped[2][0] = p2[0]; + clipped[2][1] = p2[1]; + clipped[2][2] = p2[2]; + clipped[2][3] = 1; + + matrix4_transform_vector4( self, clipped[0] ); + matrix4_transform_vector4( self, clipped[1] ); + matrix4_transform_vector4( self, clipped[2] ); + + return homogenous_clip_triangle( clipped ); +} + +inline std::size_t homogenous_clip_line( Vector4 clipped[2] ){ + const Vector4& p0 = clipped[0]; + const Vector4& p1 = clipped[1]; + + // early out + { + ClipResult mask0 = homogenous_clip_point( clipped[0] ); + ClipResult mask1 = homogenous_clip_point( clipped[1] ); + + if ( ( mask0 | mask1 ) == c_CLIP_PASS ) { // both points passed all planes + return 2; + } + + if ( mask0 & mask1 ) { // both points failed any one plane + return 0; + } + } + + { + const bool index = CLIP_X_LT_W( p0 ); + if ( index ^ CLIP_X_LT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[0] - p0[3] ) / ( clip[3] - clip[0] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + { + const bool index = CLIP_X_GT_W( p0 ); + if ( index ^ CLIP_X_GT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[0] + p0[3] ) / ( -clip[3] - clip[0] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + { + const bool index = CLIP_Y_LT_W( p0 ); + if ( index ^ CLIP_Y_LT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[1] - p0[3] ) / ( clip[3] - clip[1] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + { + const bool index = CLIP_Y_GT_W( p0 ); + if ( index ^ CLIP_Y_GT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[1] + p0[3] ) / ( -clip[3] - clip[1] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + { + const bool index = CLIP_Z_LT_W( p0 ); + if ( index ^ CLIP_Z_LT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[2] - p0[3] ) / ( clip[3] - clip[2] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + { + const bool index = CLIP_Z_GT_W( p0 ); + if ( index ^ CLIP_Z_GT_W( p1 ) ) { + Vector4 clip( vector4_subtracted( p1, p0 ) ); + + double scale = ( p0[2] + p0[3] ) / ( -clip[3] - clip[2] ); + + clip[0] = static_cast( p0[0] + scale * clip[0] ); + clip[1] = static_cast( p0[1] + scale * clip[1] ); + clip[2] = static_cast( p0[2] + scale * clip[2] ); + clip[3] = static_cast( p0[3] + scale * clip[3] ); + + clipped[index] = clip; + } + else if ( index == 0 ) { + return 0; + } + } + + return 2; } /// \brief Transforms and clips the line formed by \p p0, \p p1 by the canonical matrix \p self. /// Stores the resulting line in \p clipped. /// Returns the number of points in the resulting line. -inline std::size_t matrix4_clip_line(const Matrix4& self, const Vector3& p0, const Vector3& p1, Vector4 clipped[2]) -{ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - - matrix4_transform_vector4(self, clipped[0]); - matrix4_transform_vector4(self, clipped[1]); - - return homogenous_clip_line(clipped); +inline std::size_t matrix4_clip_line( const Matrix4& self, const Vector3& p0, const Vector3& p1, Vector4 clipped[2] ){ + clipped[0][0] = p0[0]; + clipped[0][1] = p0[1]; + clipped[0][2] = p0[2]; + clipped[0][3] = 1; + clipped[1][0] = p1[0]; + clipped[1][1] = p1[1]; + clipped[1][2] = p1[2]; + clipped[1][3] = 1; + + matrix4_transform_vector4( self, clipped[0] ); + matrix4_transform_vector4( self, clipped[1] ); + + return homogenous_clip_line( clipped ); } @@ -366,264 +366,242 @@ inline std::size_t matrix4_clip_line(const Matrix4& self, const Vector3& p0, con struct Frustum { - Plane3 right, left, bottom, top, back, front; - - Frustum() - { - } - Frustum(const Plane3& _right, - const Plane3& _left, - const Plane3& _bottom, - const Plane3& _top, - const Plane3& _back, - const Plane3& _front) - : right(_right), left(_left), bottom(_bottom), top(_top), back(_back), front(_front) - { - } + Plane3 right, left, bottom, top, back, front; + + Frustum(){ + } + Frustum( const Plane3& _right, + const Plane3& _left, + const Plane3& _bottom, + const Plane3& _top, + const Plane3& _back, + const Plane3& _front ) + : right( _right ), left( _left ), bottom( _bottom ), top( _top ), back( _back ), front( _front ){ + } }; -inline Frustum frustum_transformed(const Frustum& frustum, const Matrix4& transform) -{ - return Frustum( - plane3_transformed(frustum.right, transform), - plane3_transformed(frustum.left, transform), - plane3_transformed(frustum.bottom, transform), - plane3_transformed(frustum.top, transform), - plane3_transformed(frustum.back, transform), - plane3_transformed(frustum.front, transform) - ); +inline Frustum frustum_transformed( const Frustum& frustum, const Matrix4& transform ){ + return Frustum( + plane3_transformed( frustum.right, transform ), + plane3_transformed( frustum.left, transform ), + plane3_transformed( frustum.bottom, transform ), + plane3_transformed( frustum.top, transform ), + plane3_transformed( frustum.back, transform ), + plane3_transformed( frustum.front, transform ) + ); } -inline Frustum frustum_inverse_transformed(const Frustum& frustum, const Matrix4& transform) -{ - return Frustum( - plane3_inverse_transformed(frustum.right, transform), - plane3_inverse_transformed(frustum.left, transform), - plane3_inverse_transformed(frustum.bottom, transform), - plane3_inverse_transformed(frustum.top, transform), - plane3_inverse_transformed(frustum.back, transform), - plane3_inverse_transformed(frustum.front, transform) - ); +inline Frustum frustum_inverse_transformed( const Frustum& frustum, const Matrix4& transform ){ + return Frustum( + plane3_inverse_transformed( frustum.right, transform ), + plane3_inverse_transformed( frustum.left, transform ), + plane3_inverse_transformed( frustum.bottom, transform ), + plane3_inverse_transformed( frustum.top, transform ), + plane3_inverse_transformed( frustum.back, transform ), + plane3_inverse_transformed( frustum.front, transform ) + ); } -inline bool viewproj_test_point(const Matrix4& viewproj, const Vector3& point) -{ - Vector4 hpoint(matrix4_transformed_vector4(viewproj, Vector4(point, 1.0f))); - if(fabs(hpoint[0]) < fabs(hpoint[3]) - && fabs(hpoint[1]) < fabs(hpoint[3]) - && fabs(hpoint[2]) < fabs(hpoint[3])) - return true; - return false; +inline bool viewproj_test_point( const Matrix4& viewproj, const Vector3& point ){ + Vector4 hpoint( matrix4_transformed_vector4( viewproj, Vector4( point, 1.0f ) ) ); + if ( fabs( hpoint[0] ) < fabs( hpoint[3] ) + && fabs( hpoint[1] ) < fabs( hpoint[3] ) + && fabs( hpoint[2] ) < fabs( hpoint[3] ) ) { + return true; + } + return false; } -inline bool viewproj_test_transformed_point(const Matrix4& viewproj, const Vector3& point, const Matrix4& localToWorld) -{ - return viewproj_test_point(viewproj, matrix4_transformed_point(localToWorld, point)); +inline bool viewproj_test_transformed_point( const Matrix4& viewproj, const Vector3& point, const Matrix4& localToWorld ){ + return viewproj_test_point( viewproj, matrix4_transformed_point( localToWorld, point ) ); } -inline Frustum frustum_from_viewproj(const Matrix4& viewproj) -{ - return Frustum - ( - plane3_normalised(Plane3(viewproj[ 3] - viewproj[ 0], viewproj[ 7] - viewproj[ 4], viewproj[11] - viewproj[ 8], viewproj[15] - viewproj[12])), - plane3_normalised(Plane3(viewproj[ 3] + viewproj[ 0], viewproj[ 7] + viewproj[ 4], viewproj[11] + viewproj[ 8], viewproj[15] + viewproj[12])), - plane3_normalised(Plane3(viewproj[ 3] + viewproj[ 1], viewproj[ 7] + viewproj[ 5], viewproj[11] + viewproj[ 9], viewproj[15] + viewproj[13])), - plane3_normalised(Plane3(viewproj[ 3] - viewproj[ 1], viewproj[ 7] - viewproj[ 5], viewproj[11] - viewproj[ 9], viewproj[15] - viewproj[13])), - plane3_normalised(Plane3(viewproj[ 3] - viewproj[ 2], viewproj[ 7] - viewproj[ 6], viewproj[11] - viewproj[10], viewproj[15] - viewproj[14])), - plane3_normalised(Plane3(viewproj[ 3] + viewproj[ 2], viewproj[ 7] + viewproj[ 6], viewproj[11] + viewproj[10], viewproj[15] + viewproj[14])) - ); +inline Frustum frustum_from_viewproj( const Matrix4& viewproj ){ + return Frustum + ( + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 0], viewproj[ 7] - viewproj[ 4], viewproj[11] - viewproj[ 8], viewproj[15] - viewproj[12] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 0], viewproj[ 7] + viewproj[ 4], viewproj[11] + viewproj[ 8], viewproj[15] + viewproj[12] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 1], viewproj[ 7] + viewproj[ 5], viewproj[11] + viewproj[ 9], viewproj[15] + viewproj[13] ) ), + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 1], viewproj[ 7] - viewproj[ 5], viewproj[11] - viewproj[ 9], viewproj[15] - viewproj[13] ) ), + plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 2], viewproj[ 7] - viewproj[ 6], viewproj[11] - viewproj[10], viewproj[15] - viewproj[14] ) ), + plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 2], viewproj[ 7] + viewproj[ 6], viewproj[11] + viewproj[10], viewproj[15] + viewproj[14] ) ) + ); } struct VolumeIntersection { - enum Value - { - OUTSIDE, - INSIDE, - PARTIAL - }; + enum Value + { + OUTSIDE, + INSIDE, + PARTIAL + }; }; typedef EnumeratedValue VolumeIntersectionValue; -const VolumeIntersectionValue c_volumeOutside(VolumeIntersectionValue::OUTSIDE); -const VolumeIntersectionValue c_volumeInside(VolumeIntersectionValue::INSIDE); -const VolumeIntersectionValue c_volumePartial(VolumeIntersectionValue::PARTIAL); +const VolumeIntersectionValue c_volumeOutside( VolumeIntersectionValue::OUTSIDE ); +const VolumeIntersectionValue c_volumeInside( VolumeIntersectionValue::INSIDE ); +const VolumeIntersectionValue c_volumePartial( VolumeIntersectionValue::PARTIAL ); + +inline VolumeIntersectionValue frustum_test_aabb( const Frustum& frustum, const AABB& aabb ){ + VolumeIntersectionValue result = c_volumeInside; + + switch ( aabb_classify_plane( aabb, frustum.right ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + switch ( aabb_classify_plane( aabb, frustum.left ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + switch ( aabb_classify_plane( aabb, frustum.bottom ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + switch ( aabb_classify_plane( aabb, frustum.top ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + switch ( aabb_classify_plane( aabb, frustum.back ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + switch ( aabb_classify_plane( aabb, frustum.front ) ) + { + case 2: + return c_volumeOutside; + case 1: + result = c_volumePartial; + } + + return result; +} -inline VolumeIntersectionValue frustum_test_aabb(const Frustum& frustum, const AABB& aabb) -{ - VolumeIntersectionValue result = c_volumeInside; - - switch(aabb_classify_plane(aabb, frustum.right)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch(aabb_classify_plane(aabb, frustum.left)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch(aabb_classify_plane(aabb, frustum.bottom)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch(aabb_classify_plane(aabb, frustum.top)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch(aabb_classify_plane(aabb, frustum.back)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch(aabb_classify_plane(aabb, frustum.front)) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - return result; -} - -inline double plane_distance_to_point(const Plane3& plane, const Vector3& point) -{ - return vector3_dot(plane.normal(), point) + plane.d; +inline double plane_distance_to_point( const Plane3& plane, const Vector3& point ){ + return vector3_dot( plane.normal(), point ) + plane.d; } -inline double plane_distance_to_oriented_extents(const Plane3& plane, const Vector3& extents, const Matrix4& orientation) -{ - return fabs(extents[0] * vector3_dot(plane.normal(), vector4_to_vector3(orientation.x()))) - + fabs(extents[1] * vector3_dot(plane.normal(), vector4_to_vector3(orientation.y()))) - + fabs(extents[2] * vector3_dot(plane.normal(), vector4_to_vector3(orientation.z()))); +inline double plane_distance_to_oriented_extents( const Plane3& plane, const Vector3& extents, const Matrix4& orientation ){ + return fabs( extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.x() ) ) ) + + fabs( extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.y() ) ) ) + + fabs( extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.z() ) ) ); } /// \brief Return false if \p aabb with \p orientation is partially or completely outside \p plane. -inline bool plane_contains_oriented_aabb(const Plane3& plane, const AABB& aabb, const Matrix4& orientation) -{ - double dot = plane_distance_to_point(plane, aabb.origin); - return !(dot > 0 || -dot < plane_distance_to_oriented_extents(plane, aabb.extents, orientation)); +inline bool plane_contains_oriented_aabb( const Plane3& plane, const AABB& aabb, const Matrix4& orientation ){ + double dot = plane_distance_to_point( plane, aabb.origin ); + return !( dot > 0 || -dot < plane_distance_to_oriented_extents( plane, aabb.extents, orientation ) ); } -inline VolumeIntersectionValue frustum_intersects_transformed_aabb(const Frustum& frustum, const AABB& aabb, const Matrix4& localToWorld) -{ - AABB aabb_world(aabb); - matrix4_transform_point(localToWorld, aabb_world.origin); - - if(plane_contains_oriented_aabb(frustum.right, aabb_world, localToWorld) - || plane_contains_oriented_aabb(frustum.left, aabb_world, localToWorld) - || plane_contains_oriented_aabb(frustum.bottom, aabb_world, localToWorld) - || plane_contains_oriented_aabb(frustum.top, aabb_world, localToWorld) - || plane_contains_oriented_aabb(frustum.back, aabb_world, localToWorld) - || plane_contains_oriented_aabb(frustum.front, aabb_world, localToWorld)) - return c_volumeOutside; - return c_volumeInside; +inline VolumeIntersectionValue frustum_intersects_transformed_aabb( const Frustum& frustum, const AABB& aabb, const Matrix4& localToWorld ){ + AABB aabb_world( aabb ); + matrix4_transform_point( localToWorld, aabb_world.origin ); + + if ( plane_contains_oriented_aabb( frustum.right, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.left, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.bottom, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.top, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.back, aabb_world, localToWorld ) + || plane_contains_oriented_aabb( frustum.front, aabb_world, localToWorld ) ) { + return c_volumeOutside; + } + return c_volumeInside; } -inline bool plane3_test_point(const Plane3& plane, const Vector3& point) -{ - return vector3_dot(point, plane.normal()) + plane.dist() <= 0; +inline bool plane3_test_point( const Plane3& plane, const Vector3& point ){ + return vector3_dot( point, plane.normal() ) + plane.dist() <= 0; } -inline bool plane3_test_line(const Plane3& plane, const Segment& segment) -{ - return segment_classify_plane(segment, plane) == 2; +inline bool plane3_test_line( const Plane3& plane, const Segment& segment ){ + return segment_classify_plane( segment, plane ) == 2; } -inline bool frustum_test_point(const Frustum& frustum, const Vector3& point) -{ - return !plane3_test_point(frustum.right, point) - && !plane3_test_point(frustum.left, point) - && !plane3_test_point(frustum.bottom, point) - && !plane3_test_point(frustum.top, point) - && !plane3_test_point(frustum.back, point) - && !plane3_test_point(frustum.front, point); +inline bool frustum_test_point( const Frustum& frustum, const Vector3& point ){ + return !plane3_test_point( frustum.right, point ) + && !plane3_test_point( frustum.left, point ) + && !plane3_test_point( frustum.bottom, point ) + && !plane3_test_point( frustum.top, point ) + && !plane3_test_point( frustum.back, point ) + && !plane3_test_point( frustum.front, point ); } -inline bool frustum_test_line(const Frustum& frustum, const Segment& segment) -{ - return !plane3_test_line(frustum.right, segment) - && !plane3_test_line(frustum.left, segment) - && !plane3_test_line(frustum.bottom, segment) - && !plane3_test_line(frustum.top, segment) - && !plane3_test_line(frustum.back, segment) - && !plane3_test_line(frustum.front, segment); +inline bool frustum_test_line( const Frustum& frustum, const Segment& segment ){ + return !plane3_test_line( frustum.right, segment ) + && !plane3_test_line( frustum.left, segment ) + && !plane3_test_line( frustum.bottom, segment ) + && !plane3_test_line( frustum.top, segment ) + && !plane3_test_line( frustum.back, segment ) + && !plane3_test_line( frustum.front, segment ); } -inline bool viewer_test_plane(const Vector4& viewer, const Plane3& plane) -{ - return ((plane.a * viewer[0]) - + (plane.b * viewer[1]) - + (plane.c * viewer[2]) - + (plane.d * viewer[3])) > 0; +inline bool viewer_test_plane( const Vector4& viewer, const Plane3& plane ){ + return ( ( plane.a * viewer[0] ) + + ( plane.b * viewer[1] ) + + ( plane.c * viewer[2] ) + + ( plane.d * viewer[3] ) ) > 0; } -inline Vector3 triangle_cross(const Vector3& p0, const Vector3& p1, const Vector3& p2) -{ - return vector3_cross(vector3_subtracted(p1, p0), vector3_subtracted(p1, p2)); +inline Vector3 triangle_cross( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ + return vector3_cross( vector3_subtracted( p1, p0 ), vector3_subtracted( p1, p2 ) ); } -inline bool viewer_test_triangle(const Vector4& viewer, const Vector3& p0, const Vector3& p1, const Vector3& p2) -{ - Vector3 cross(triangle_cross(p0, p1, p2)); - return ((viewer[0] * cross[0]) - + (viewer[1] * cross[1]) - + (viewer[2] * cross[2]) - + (viewer[3] * 0)) > 0; +inline bool viewer_test_triangle( const Vector4& viewer, const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ + Vector3 cross( triangle_cross( p0, p1, p2 ) ); + return ( ( viewer[0] * cross[0] ) + + ( viewer[1] * cross[1] ) + + ( viewer[2] * cross[2] ) + + ( viewer[3] * 0 ) ) > 0; } -inline Vector4 viewer_from_transformed_viewer(const Vector4& viewer, const Matrix4& transform) -{ - if(viewer[3] == 0) - { - return Vector4(matrix4_transformed_direction(transform, vector4_to_vector3(viewer)), 0); - } - else - { - return Vector4(matrix4_transformed_point(transform, vector4_to_vector3(viewer)), viewer[3]); - } +inline Vector4 viewer_from_transformed_viewer( const Vector4& viewer, const Matrix4& transform ){ + if ( viewer[3] == 0 ) { + return Vector4( matrix4_transformed_direction( transform, vector4_to_vector3( viewer ) ), 0 ); + } + else + { + return Vector4( matrix4_transformed_point( transform, vector4_to_vector3( viewer ) ), viewer[3] ); + } } -inline bool viewer_test_transformed_plane(const Vector4& viewer, const Plane3& plane, const Matrix4& localToWorld) -{ +inline bool viewer_test_transformed_plane( const Vector4& viewer, const Plane3& plane, const Matrix4& localToWorld ){ #if 0 - return viewer_test_plane(viewer_from_transformed_viewer(viewer, matrix4_affine_inverse(localToWorld)), plane); + return viewer_test_plane( viewer_from_transformed_viewer( viewer, matrix4_affine_inverse( localToWorld ) ), plane ); #else - return viewer_test_plane(viewer, plane3_transformed(plane, localToWorld)); + return viewer_test_plane( viewer, plane3_transformed( plane, localToWorld ) ); #endif } -inline Vector4 viewer_from_viewproj(const Matrix4& viewproj) -{ - // get viewer pos in object coords - Vector4 viewer(matrix4_transformed_vector4(matrix4_full_inverse(viewproj), Vector4(0, 0, -1, 0))); - if(viewer[3] != 0) // non-affine matrix - { - viewer[0] /= viewer[3]; - viewer[1] /= viewer[3]; - viewer[2] /= viewer[3]; - viewer[3] /= viewer[3]; - } - return viewer; +inline Vector4 viewer_from_viewproj( const Matrix4& viewproj ){ + // get viewer pos in object coords + Vector4 viewer( matrix4_transformed_vector4( matrix4_full_inverse( viewproj ), Vector4( 0, 0, -1, 0 ) ) ); + if ( viewer[3] != 0 ) { // non-affine matrix + viewer[0] /= viewer[3]; + viewer[1] /= viewer[3]; + viewer[2] /= viewer[3]; + viewer[3] /= viewer[3]; + } + return viewer; } #endif diff --git a/libs/math/line.cpp b/libs/math/line.cpp index a0bdea1a..0f4eb811 100644 --- a/libs/math/line.cpp +++ b/libs/math/line.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "line.h" - diff --git a/libs/math/line.h b/libs/math/line.h index 26d58369..cf3bec54 100644 --- a/libs/math/line.h +++ b/libs/math/line.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_LINE_H) +#if !defined( INCLUDED_MATH_LINE_H ) #define INCLUDED_MATH_LINE_H /// \file @@ -32,120 +32,107 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class Line { public: - Vector3 start, end; - - Line() - { - } - Line(const Vector3& start_, const Vector3& end_) : start(start_), end(end_) - { - } +Vector3 start, end; + +Line(){ +} +Line( const Vector3& start_, const Vector3& end_ ) : start( start_ ), end( end_ ){ +} }; -inline Vector3 line_closest_point(const Line& line, const Vector3& point) -{ - Vector3 v = line.end - line.start; - Vector3 w = point - line.start; +inline Vector3 line_closest_point( const Line& line, const Vector3& point ){ + Vector3 v = line.end - line.start; + Vector3 w = point - line.start; - double c1 = vector3_dot(w,v); - if ( c1 <= 0 ) - return line.start; + double c1 = vector3_dot( w,v ); + if ( c1 <= 0 ) { + return line.start; + } - double c2 = vector3_dot(v,v); - if ( c2 <= c1 ) - return line.end; + double c2 = vector3_dot( v,v ); + if ( c2 <= c1 ) { + return line.end; + } - return Vector3(line.start + v * (c1 / c2)); + return Vector3( line.start + v * ( c1 / c2 ) ); } class Segment { public: - Vector3 origin, extents; - - Segment() - { - } - Segment(const Vector3& origin_, const Vector3& extents_) : - origin(origin_), extents(extents_) - { - } +Vector3 origin, extents; + +Segment(){ +} +Segment( const Vector3& origin_, const Vector3& extents_ ) : + origin( origin_ ), extents( extents_ ){ +} }; -inline Segment segment_for_startend(const Vector3& start, const Vector3& end) -{ - Segment segment; - segment.origin = vector3_mid(start, end); - segment.extents = vector3_subtracted(end, segment.origin); - return segment; +inline Segment segment_for_startend( const Vector3& start, const Vector3& end ){ + Segment segment; + segment.origin = vector3_mid( start, end ); + segment.extents = vector3_subtracted( end, segment.origin ); + return segment; } -inline unsigned int segment_classify_plane(const Segment& segment, const Plane3& plane) -{ - double distance_origin = vector3_dot(plane.normal(), segment.origin) + plane.dist(); - - if (fabs(distance_origin) < fabs(vector3_dot(plane.normal(), segment.extents))) - { - return 1; // partially inside - } - else if (distance_origin < 0) - { - return 2; // totally inside - } - return 0; // totally outside +inline unsigned int segment_classify_plane( const Segment& segment, const Plane3& plane ){ + double distance_origin = vector3_dot( plane.normal(), segment.origin ) + plane.dist(); + + if ( fabs( distance_origin ) < fabs( vector3_dot( plane.normal(), segment.extents ) ) ) { + return 1; // partially inside + } + else if ( distance_origin < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } class Ray { public: - Vector3 origin, direction; - - Ray() - { - } - Ray(const Vector3& origin_, const Vector3& direction_) : - origin(origin_), direction(direction_) - { - } +Vector3 origin, direction; + +Ray(){ +} +Ray( const Vector3& origin_, const Vector3& direction_ ) : + origin( origin_ ), direction( direction_ ){ +} }; -inline Ray ray_for_points(const Vector3& origin, const Vector3& p2) -{ - return Ray(origin, vector3_normalised(vector3_subtracted(p2, origin))); +inline Ray ray_for_points( const Vector3& origin, const Vector3& p2 ){ + return Ray( origin, vector3_normalised( vector3_subtracted( p2, origin ) ) ); } -inline void ray_transform(Ray& ray, const Matrix4& matrix) -{ - matrix4_transform_point(matrix, ray.origin); - matrix4_transform_direction(matrix, ray.direction); +inline void ray_transform( Ray& ray, const Matrix4& matrix ){ + matrix4_transform_point( matrix, ray.origin ); + matrix4_transform_direction( matrix, ray.direction ); } // closest-point-on-line -inline double ray_squared_distance_to_point(const Ray& ray, const Vector3& point) -{ - return vector3_length_squared( - vector3_subtracted( - point, - vector3_added( - ray.origin, - vector3_scaled( - ray.direction, - vector3_dot( - vector3_subtracted(point, ray.origin), - ray.direction - ) - ) - ) - ) - ); +inline double ray_squared_distance_to_point( const Ray& ray, const Vector3& point ){ + return vector3_length_squared( + vector3_subtracted( + point, + vector3_added( + ray.origin, + vector3_scaled( + ray.direction, + vector3_dot( + vector3_subtracted( point, ray.origin ), + ray.direction + ) + ) + ) + ) + ); } -inline double ray_distance_to_plane(const Ray& ray, const Plane3& plane) -{ - return -(vector3_dot(plane.normal(), ray.origin) - plane.dist()) / vector3_dot(ray.direction, plane.normal()); +inline double ray_distance_to_plane( const Ray& ray, const Plane3& plane ){ + return -( vector3_dot( plane.normal(), ray.origin ) - plane.dist() ) / vector3_dot( ray.direction, plane.normal() ); } #endif diff --git a/libs/math/matrix.cpp b/libs/math/matrix.cpp index e3831647..6ed9a7e7 100644 --- a/libs/math/matrix.cpp +++ b/libs/math/matrix.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "matrix.h" - diff --git a/libs/math/matrix.h b/libs/math/matrix.h index b28c2688..95ecfac0 100644 --- a/libs/math/matrix.h +++ b/libs/math/matrix.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_MATRIX_H) +#if !defined( INCLUDED_MATH_MATRIX_H ) #define INCLUDED_MATH_MATRIX_H /// \file @@ -30,302 +30,249 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// \brief A 4x4 matrix stored in single-precision floating-point. class Matrix4 { - float m_elements[16]; +float m_elements[16]; public: - Matrix4() - { - } - Matrix4(float xx_, float xy_, float xz_, float xw_, - float yx_, float yy_, float yz_, float yw_, - float zx_, float zy_, float zz_, float zw_, - float tx_, float ty_, float tz_, float tw_) - { - xx() = xx_; - xy() = xy_; - xz() = xz_; - xw() = xw_; - yx() = yx_; - yy() = yy_; - yz() = yz_; - yw() = yw_; - zx() = zx_; - zy() = zy_; - zz() = zz_; - zw() = zw_; - tx() = tx_; - ty() = ty_; - tz() = tz_; - tw() = tw_; - } - - float& xx() - { - return m_elements[0]; - } - const float& xx() const - { - return m_elements[0]; - } - float& xy() - { - return m_elements[1]; - } - const float& xy() const - { - return m_elements[1]; - } - float& xz() - { - return m_elements[2]; - } - const float& xz() const - { - return m_elements[2]; - } - float& xw() - { - return m_elements[3]; - } - const float& xw() const - { - return m_elements[3]; - } - float& yx() - { - return m_elements[4]; - } - const float& yx() const - { - return m_elements[4]; - } - float& yy() - { - return m_elements[5]; - } - const float& yy() const - { - return m_elements[5]; - } - float& yz() - { - return m_elements[6]; - } - const float& yz() const - { - return m_elements[6]; - } - float& yw() - { - return m_elements[7]; - } - const float& yw() const - { - return m_elements[7]; - } - float& zx() - { - return m_elements[8]; - } - const float& zx() const - { - return m_elements[8]; - } - float& zy() - { - return m_elements[9]; - } - const float& zy() const - { - return m_elements[9]; - } - float& zz() - { - return m_elements[10]; - } - const float& zz() const - { - return m_elements[10]; - } - float& zw() - { - return m_elements[11]; - } - const float& zw() const - { - return m_elements[11]; - } - float& tx() - { - return m_elements[12]; - } - const float& tx() const - { - return m_elements[12]; - } - float& ty() - { - return m_elements[13]; - } - const float& ty() const - { - return m_elements[13]; - } - float& tz() - { - return m_elements[14]; - } - const float& tz() const - { - return m_elements[14]; - } - float& tw() - { - return m_elements[15]; - } - const float& tw() const - { - return m_elements[15]; - } - - Vector4& x() - { - return reinterpret_cast(xx()); - } - const Vector4& x() const - { - return reinterpret_cast(xx()); - } - Vector4& y() - { - return reinterpret_cast(yx()); - } - const Vector4& y() const - { - return reinterpret_cast(yx()); - } - Vector4& z() - { - return reinterpret_cast(zx()); - } - const Vector4& z() const - { - return reinterpret_cast(zx()); - } - Vector4& t() - { - return reinterpret_cast(tx()); - } - const Vector4& t() const - { - return reinterpret_cast(tx()); - } - - const float& index(std::size_t i) const - { - return m_elements[i]; - } - float& index(std::size_t i) - { - return m_elements[i]; - } - const float& operator[](std::size_t i) const - { - return m_elements[i]; - } - float& operator[](std::size_t i) - { - return m_elements[i]; - } - const float& index(std::size_t r, std::size_t c) const - { - return m_elements[(r << 2) + c]; - } - float& index(std::size_t r, std::size_t c) - { - return m_elements[(r << 2) + c]; - } +Matrix4(){ +} +Matrix4( float xx_, float xy_, float xz_, float xw_, + float yx_, float yy_, float yz_, float yw_, + float zx_, float zy_, float zz_, float zw_, + float tx_, float ty_, float tz_, float tw_ ){ + xx() = xx_; + xy() = xy_; + xz() = xz_; + xw() = xw_; + yx() = yx_; + yy() = yy_; + yz() = yz_; + yw() = yw_; + zx() = zx_; + zy() = zy_; + zz() = zz_; + zw() = zw_; + tx() = tx_; + ty() = ty_; + tz() = tz_; + tw() = tw_; +} + +float& xx(){ + return m_elements[0]; +} +const float& xx() const { + return m_elements[0]; +} +float& xy(){ + return m_elements[1]; +} +const float& xy() const { + return m_elements[1]; +} +float& xz(){ + return m_elements[2]; +} +const float& xz() const { + return m_elements[2]; +} +float& xw(){ + return m_elements[3]; +} +const float& xw() const { + return m_elements[3]; +} +float& yx(){ + return m_elements[4]; +} +const float& yx() const { + return m_elements[4]; +} +float& yy(){ + return m_elements[5]; +} +const float& yy() const { + return m_elements[5]; +} +float& yz(){ + return m_elements[6]; +} +const float& yz() const { + return m_elements[6]; +} +float& yw(){ + return m_elements[7]; +} +const float& yw() const { + return m_elements[7]; +} +float& zx(){ + return m_elements[8]; +} +const float& zx() const { + return m_elements[8]; +} +float& zy(){ + return m_elements[9]; +} +const float& zy() const { + return m_elements[9]; +} +float& zz(){ + return m_elements[10]; +} +const float& zz() const { + return m_elements[10]; +} +float& zw(){ + return m_elements[11]; +} +const float& zw() const { + return m_elements[11]; +} +float& tx(){ + return m_elements[12]; +} +const float& tx() const { + return m_elements[12]; +} +float& ty(){ + return m_elements[13]; +} +const float& ty() const { + return m_elements[13]; +} +float& tz(){ + return m_elements[14]; +} +const float& tz() const { + return m_elements[14]; +} +float& tw(){ + return m_elements[15]; +} +const float& tw() const { + return m_elements[15]; +} + +Vector4& x(){ + return reinterpret_cast( xx() ); +} +const Vector4& x() const { + return reinterpret_cast( xx() ); +} +Vector4& y(){ + return reinterpret_cast( yx() ); +} +const Vector4& y() const { + return reinterpret_cast( yx() ); +} +Vector4& z(){ + return reinterpret_cast( zx() ); +} +const Vector4& z() const { + return reinterpret_cast( zx() ); +} +Vector4& t(){ + return reinterpret_cast( tx() ); +} +const Vector4& t() const { + return reinterpret_cast( tx() ); +} + +const float& index( std::size_t i ) const { + return m_elements[i]; +} +float& index( std::size_t i ){ + return m_elements[i]; +} +const float& operator[]( std::size_t i ) const { + return m_elements[i]; +} +float& operator[]( std::size_t i ){ + return m_elements[i]; +} +const float& index( std::size_t r, std::size_t c ) const { + return m_elements[( r << 2 ) + c]; +} +float& index( std::size_t r, std::size_t c ){ + return m_elements[( r << 2 ) + c]; +} }; /// \brief The 4x4 identity matrix. const Matrix4 g_matrix4_identity( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 -); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ); /// \brief Returns true if \p self and \p other are exactly element-wise equal. -inline bool operator==(const Matrix4& self, const Matrix4& other) -{ - return self.xx() == other.xx() && self.xy() == other.xy() && self.xz() == other.xz() && self.xw() == other.xw() - && self.yx() == other.yx() && self.yy() == other.yy() && self.yz() == other.yz() && self.yw() == other.yw() - && self.zx() == other.zx() && self.zy() == other.zy() && self.zz() == other.zz() && self.zw() == other.zw() - && self.tx() == other.tx() && self.ty() == other.ty() && self.tz() == other.tz() && self.tw() == other.tw(); +inline bool operator==( const Matrix4& self, const Matrix4& other ){ + return self.xx() == other.xx() && self.xy() == other.xy() && self.xz() == other.xz() && self.xw() == other.xw() + && self.yx() == other.yx() && self.yy() == other.yy() && self.yz() == other.yz() && self.yw() == other.yw() + && self.zx() == other.zx() && self.zy() == other.zy() && self.zz() == other.zz() && self.zw() == other.zw() + && self.tx() == other.tx() && self.ty() == other.ty() && self.tz() == other.tz() && self.tw() == other.tw(); } /// \brief Returns true if \p self and \p other are exactly element-wise equal. -inline bool matrix4_equal(const Matrix4& self, const Matrix4& other) -{ - return self == other; +inline bool matrix4_equal( const Matrix4& self, const Matrix4& other ){ + return self == other; } /// \brief Returns true if \p self and \p other are element-wise equal within \p epsilon. -inline bool matrix4_equal_epsilon(const Matrix4& self, const Matrix4& other, float epsilon) -{ - return float_equal_epsilon(self.xx(), other.xx(), epsilon) - && float_equal_epsilon(self.xy(), other.xy(), epsilon) - && float_equal_epsilon(self.xz(), other.xz(), epsilon) - && float_equal_epsilon(self.xw(), other.xw(), epsilon) - && float_equal_epsilon(self.yx(), other.yx(), epsilon) - && float_equal_epsilon(self.yy(), other.yy(), epsilon) - && float_equal_epsilon(self.yz(), other.yz(), epsilon) - && float_equal_epsilon(self.yw(), other.yw(), epsilon) - && float_equal_epsilon(self.zx(), other.zx(), epsilon) - && float_equal_epsilon(self.zy(), other.zy(), epsilon) - && float_equal_epsilon(self.zz(), other.zz(), epsilon) - && float_equal_epsilon(self.zw(), other.zw(), epsilon) - && float_equal_epsilon(self.tx(), other.tx(), epsilon) - && float_equal_epsilon(self.ty(), other.ty(), epsilon) - && float_equal_epsilon(self.tz(), other.tz(), epsilon) - && float_equal_epsilon(self.tw(), other.tw(), epsilon); +inline bool matrix4_equal_epsilon( const Matrix4& self, const Matrix4& other, float epsilon ){ + return float_equal_epsilon( self.xx(), other.xx(), epsilon ) + && float_equal_epsilon( self.xy(), other.xy(), epsilon ) + && float_equal_epsilon( self.xz(), other.xz(), epsilon ) + && float_equal_epsilon( self.xw(), other.xw(), epsilon ) + && float_equal_epsilon( self.yx(), other.yx(), epsilon ) + && float_equal_epsilon( self.yy(), other.yy(), epsilon ) + && float_equal_epsilon( self.yz(), other.yz(), epsilon ) + && float_equal_epsilon( self.yw(), other.yw(), epsilon ) + && float_equal_epsilon( self.zx(), other.zx(), epsilon ) + && float_equal_epsilon( self.zy(), other.zy(), epsilon ) + && float_equal_epsilon( self.zz(), other.zz(), epsilon ) + && float_equal_epsilon( self.zw(), other.zw(), epsilon ) + && float_equal_epsilon( self.tx(), other.tx(), epsilon ) + && float_equal_epsilon( self.ty(), other.ty(), epsilon ) + && float_equal_epsilon( self.tz(), other.tz(), epsilon ) + && float_equal_epsilon( self.tw(), other.tw(), epsilon ); } /// \brief Returns true if \p self and \p other are exactly element-wise equal. /// \p self and \p other must be affine. -inline bool matrix4_affine_equal(const Matrix4& self, const Matrix4& other) -{ - return self[0] == other[0] - && self[1] == other[1] - && self[2] == other[2] - && self[4] == other[4] - && self[5] == other[5] - && self[6] == other[6] - && self[8] == other[8] - && self[9] == other[9] - && self[10] == other[10] - && self[12] == other[12] - && self[13] == other[13] - && self[14] == other[14]; +inline bool matrix4_affine_equal( const Matrix4& self, const Matrix4& other ){ + return self[0] == other[0] + && self[1] == other[1] + && self[2] == other[2] + && self[4] == other[4] + && self[5] == other[5] + && self[6] == other[6] + && self[8] == other[8] + && self[9] == other[9] + && self[10] == other[10] + && self[12] == other[12] + && self[13] == other[13] + && self[14] == other[14]; } enum Matrix4Handedness { - MATRIX4_RIGHTHANDED = 0, - MATRIX4_LEFTHANDED = 1, + MATRIX4_RIGHTHANDED = 0, + MATRIX4_LEFTHANDED = 1, }; /// \brief Returns MATRIX4_RIGHTHANDED if \p self is right-handed, else returns MATRIX4_LEFTHANDED. -inline Matrix4Handedness matrix4_handedness(const Matrix4& self) -{ - return ( - vector3_dot( - vector3_cross(vector4_to_vector3(self.x()), vector4_to_vector3(self.y())), - vector4_to_vector3(self.z()) - ) - < 0.0 - ) ? MATRIX4_LEFTHANDED : MATRIX4_RIGHTHANDED; +inline Matrix4Handedness matrix4_handedness( const Matrix4& self ){ + return ( + vector3_dot( + vector3_cross( vector4_to_vector3( self.x() ), vector4_to_vector3( self.y() ) ), + vector4_to_vector3( self.z() ) + ) + < 0.0 + ) ? MATRIX4_LEFTHANDED : MATRIX4_RIGHTHANDED; } @@ -333,285 +280,266 @@ inline Matrix4Handedness matrix4_handedness(const Matrix4& self) /// \brief Returns \p self post-multiplied by \p other. -inline Matrix4 matrix4_multiplied_by_matrix4(const Matrix4& self, const Matrix4& other) -{ - return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8] + other[3] * self[12], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9] + other[3] * self[13], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10]+ other[3] * self[14], - other[0] * self[3] + other[1] * self[7] + other[2] * self[11]+ other[3] * self[15], - other[4] * self[0] + other[5] * self[4] + other[6] * self[8] + other[7] * self[12], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9] + other[7] * self[13], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10]+ other[7] * self[14], - other[4] * self[3] + other[5] * self[7] + other[6] * self[11]+ other[7] * self[15], - other[8] * self[0] + other[9] * self[4] + other[10]* self[8] + other[11]* self[12], - other[8] * self[1] + other[9] * self[5] + other[10]* self[9] + other[11]* self[13], - other[8] * self[2] + other[9] * self[6] + other[10]* self[10]+ other[11]* self[14], - other[8] * self[3] + other[9] * self[7] + other[10]* self[11]+ other[11]* self[15], - other[12]* self[0] + other[13]* self[4] + other[14]* self[8] + other[15]* self[12], - other[12]* self[1] + other[13]* self[5] + other[14]* self[9] + other[15]* self[13], - other[12]* self[2] + other[13]* self[6] + other[14]* self[10]+ other[15]* self[14], - other[12]* self[3] + other[13]* self[7] + other[14]* self[11]+ other[15]* self[15] - ); +inline Matrix4 matrix4_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ + return Matrix4( + other[0] * self[0] + other[1] * self[4] + other[2] * self[8] + other[3] * self[12], + other[0] * self[1] + other[1] * self[5] + other[2] * self[9] + other[3] * self[13], + other[0] * self[2] + other[1] * self[6] + other[2] * self[10] + other[3] * self[14], + other[0] * self[3] + other[1] * self[7] + other[2] * self[11] + other[3] * self[15], + other[4] * self[0] + other[5] * self[4] + other[6] * self[8] + other[7] * self[12], + other[4] * self[1] + other[5] * self[5] + other[6] * self[9] + other[7] * self[13], + other[4] * self[2] + other[5] * self[6] + other[6] * self[10] + other[7] * self[14], + other[4] * self[3] + other[5] * self[7] + other[6] * self[11] + other[7] * self[15], + other[8] * self[0] + other[9] * self[4] + other[10] * self[8] + other[11] * self[12], + other[8] * self[1] + other[9] * self[5] + other[10] * self[9] + other[11] * self[13], + other[8] * self[2] + other[9] * self[6] + other[10] * self[10] + other[11] * self[14], + other[8] * self[3] + other[9] * self[7] + other[10] * self[11] + other[11] * self[15], + other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + other[15] * self[12], + other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + other[15] * self[13], + other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + other[15] * self[14], + other[12] * self[3] + other[13] * self[7] + other[14] * self[11] + other[15] * self[15] + ); } /// \brief Post-multiplies \p self by \p other in-place. -inline void matrix4_multiply_by_matrix4(Matrix4& self, const Matrix4& other) -{ - self = matrix4_multiplied_by_matrix4(self, other); +inline void matrix4_multiply_by_matrix4( Matrix4& self, const Matrix4& other ){ + self = matrix4_multiplied_by_matrix4( self, other ); } /// \brief Returns \p self pre-multiplied by \p other. -inline Matrix4 matrix4_premultiplied_by_matrix4(const Matrix4& self, const Matrix4& other) -{ +inline Matrix4 matrix4_premultiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ #if 1 - return matrix4_multiplied_by_matrix4(other, self); + return matrix4_multiplied_by_matrix4( other, self ); #else - return Matrix4( - self[0] * other[0] + self[1] * other[4] + self[2] * other[8] + self[3] * other[12], - self[0] * other[1] + self[1] * other[5] + self[2] * other[9] + self[3] * other[13], - self[0] * other[2] + self[1] * other[6] + self[2] * other[10]+ self[3] * other[14], - self[0] * other[3] + self[1] * other[7] + self[2] * other[11]+ self[3] * other[15], - self[4] * other[0] + self[5] * other[4] + self[6] * other[8] + self[7] * other[12], - self[4] * other[1] + self[5] * other[5] + self[6] * other[9] + self[7] * other[13], - self[4] * other[2] + self[5] * other[6] + self[6] * other[10]+ self[7] * other[14], - self[4] * other[3] + self[5] * other[7] + self[6] * other[11]+ self[7] * other[15], - self[8] * other[0] + self[9] * other[4] + self[10]* other[8] + self[11]* other[12], - self[8] * other[1] + self[9] * other[5] + self[10]* other[9] + self[11]* other[13], - self[8] * other[2] + self[9] * other[6] + self[10]* other[10]+ self[11]* other[14], - self[8] * other[3] + self[9] * other[7] + self[10]* other[11]+ self[11]* other[15], - self[12]* other[0] + self[13]* other[4] + self[14]* other[8] + self[15]* other[12], - self[12]* other[1] + self[13]* other[5] + self[14]* other[9] + self[15]* other[13], - self[12]* other[2] + self[13]* other[6] + self[14]* other[10]+ self[15]* other[14], - self[12]* other[3] + self[13]* other[7] + self[14]* other[11]+ self[15]* other[15] - ); + return Matrix4( + self[0] * other[0] + self[1] * other[4] + self[2] * other[8] + self[3] * other[12], + self[0] * other[1] + self[1] * other[5] + self[2] * other[9] + self[3] * other[13], + self[0] * other[2] + self[1] * other[6] + self[2] * other[10] + self[3] * other[14], + self[0] * other[3] + self[1] * other[7] + self[2] * other[11] + self[3] * other[15], + self[4] * other[0] + self[5] * other[4] + self[6] * other[8] + self[7] * other[12], + self[4] * other[1] + self[5] * other[5] + self[6] * other[9] + self[7] * other[13], + self[4] * other[2] + self[5] * other[6] + self[6] * other[10] + self[7] * other[14], + self[4] * other[3] + self[5] * other[7] + self[6] * other[11] + self[7] * other[15], + self[8] * other[0] + self[9] * other[4] + self[10] * other[8] + self[11] * other[12], + self[8] * other[1] + self[9] * other[5] + self[10] * other[9] + self[11] * other[13], + self[8] * other[2] + self[9] * other[6] + self[10] * other[10] + self[11] * other[14], + self[8] * other[3] + self[9] * other[7] + self[10] * other[11] + self[11] * other[15], + self[12] * other[0] + self[13] * other[4] + self[14] * other[8] + self[15] * other[12], + self[12] * other[1] + self[13] * other[5] + self[14] * other[9] + self[15] * other[13], + self[12] * other[2] + self[13] * other[6] + self[14] * other[10] + self[15] * other[14], + self[12] * other[3] + self[13] * other[7] + self[14] * other[11] + self[15] * other[15] + ); #endif } /// \brief Pre-multiplies \p self by \p other in-place. -inline void matrix4_premultiply_by_matrix4(Matrix4& self, const Matrix4& other) -{ - self = matrix4_premultiplied_by_matrix4(self, other); +inline void matrix4_premultiply_by_matrix4( Matrix4& self, const Matrix4& other ){ + self = matrix4_premultiplied_by_matrix4( self, other ); } /// \brief returns true if \p transform is affine. -inline bool matrix4_is_affine(const Matrix4& transform) -{ - return transform[3] == 0 && transform[7] == 0 && transform[11] == 0 && transform[15] == 1; +inline bool matrix4_is_affine( const Matrix4& transform ){ + return transform[3] == 0 && transform[7] == 0 && transform[11] == 0 && transform[15] == 1; } /// \brief Returns \p self post-multiplied by \p other. /// \p self and \p other must be affine. -inline Matrix4 matrix4_affine_multiplied_by_matrix4(const Matrix4& self, const Matrix4& other) -{ - return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10], - 0, - other[4] * self[0] + other[5] * self[4] + other[6] * self[8], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10], - 0, - other[8] * self[0] + other[9] * self[4] + other[10]* self[8], - other[8] * self[1] + other[9] * self[5] + other[10]* self[9], - other[8] * self[2] + other[9] * self[6] + other[10]* self[10], - 0, - other[12]* self[0] + other[13]* self[4] + other[14]* self[8] + self[12], - other[12]* self[1] + other[13]* self[5] + other[14]* self[9] + self[13], - other[12]* self[2] + other[13]* self[6] + other[14]* self[10]+ self[14], - 1 - ); +inline Matrix4 matrix4_affine_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ + return Matrix4( + other[0] * self[0] + other[1] * self[4] + other[2] * self[8], + other[0] * self[1] + other[1] * self[5] + other[2] * self[9], + other[0] * self[2] + other[1] * self[6] + other[2] * self[10], + 0, + other[4] * self[0] + other[5] * self[4] + other[6] * self[8], + other[4] * self[1] + other[5] * self[5] + other[6] * self[9], + other[4] * self[2] + other[5] * self[6] + other[6] * self[10], + 0, + other[8] * self[0] + other[9] * self[4] + other[10] * self[8], + other[8] * self[1] + other[9] * self[5] + other[10] * self[9], + other[8] * self[2] + other[9] * self[6] + other[10] * self[10], + 0, + other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + self[12], + other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + self[13], + other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + self[14], + 1 + ); } /// \brief Post-multiplies \p self by \p other in-place. /// \p self and \p other must be affine. -inline void matrix4_affine_multiply_by_matrix4(Matrix4& self, const Matrix4& other) -{ - self = matrix4_affine_multiplied_by_matrix4(self, other); +inline void matrix4_affine_multiply_by_matrix4( Matrix4& self, const Matrix4& other ){ + self = matrix4_affine_multiplied_by_matrix4( self, other ); } /// \brief Returns \p self pre-multiplied by \p other. /// \p self and \p other must be affine. -inline Matrix4 matrix4_affine_premultiplied_by_matrix4(const Matrix4& self, const Matrix4& other) -{ +inline Matrix4 matrix4_affine_premultiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ #if 1 - return matrix4_affine_multiplied_by_matrix4(other, self); + return matrix4_affine_multiplied_by_matrix4( other, self ); #else - return Matrix4( - self[0] * other[0] + self[1] * other[4] + self[2] * other[8], - self[0] * other[1] + self[1] * other[5] + self[2] * other[9], - self[0] * other[2] + self[1] * other[6] + self[2] * other[10], - 0, - self[4] * other[0] + self[5] * other[4] + self[6] * other[8], - self[4] * other[1] + self[5] * other[5] + self[6] * other[9], - self[4] * other[2] + self[5] * other[6] + self[6] * other[10], - 0, - self[8] * other[0] + self[9] * other[4] + self[10]* other[8], - self[8] * other[1] + self[9] * other[5] + self[10]* other[9], - self[8] * other[2] + self[9] * other[6] + self[10]* other[10], - 0, - self[12]* other[0] + self[13]* other[4] + self[14]* other[8] + other[12], - self[12]* other[1] + self[13]* other[5] + self[14]* other[9] + other[13], - self[12]* other[2] + self[13]* other[6] + self[14]* other[10]+ other[14], - 1 - ) - ); + return Matrix4( + self[0] * other[0] + self[1] * other[4] + self[2] * other[8], + self[0] * other[1] + self[1] * other[5] + self[2] * other[9], + self[0] * other[2] + self[1] * other[6] + self[2] * other[10], + 0, + self[4] * other[0] + self[5] * other[4] + self[6] * other[8], + self[4] * other[1] + self[5] * other[5] + self[6] * other[9], + self[4] * other[2] + self[5] * other[6] + self[6] * other[10], + 0, + self[8] * other[0] + self[9] * other[4] + self[10] * other[8], + self[8] * other[1] + self[9] * other[5] + self[10] * other[9], + self[8] * other[2] + self[9] * other[6] + self[10] * other[10], + 0, + self[12] * other[0] + self[13] * other[4] + self[14] * other[8] + other[12], + self[12] * other[1] + self[13] * other[5] + self[14] * other[9] + other[13], + self[12] * other[2] + self[13] * other[6] + self[14] * other[10] + other[14], + 1 + ) + ); #endif } /// \brief Pre-multiplies \p self by \p other in-place. /// \p self and \p other must be affine. -inline void matrix4_affine_premultiply_by_matrix4(Matrix4& self, const Matrix4& other) -{ - self = matrix4_affine_premultiplied_by_matrix4(self, other); +inline void matrix4_affine_premultiply_by_matrix4( Matrix4& self, const Matrix4& other ){ + self = matrix4_affine_premultiplied_by_matrix4( self, other ); } /// \brief Returns \p point transformed by \p self. template -inline BasicVector3 matrix4_transformed_point(const Matrix4& self, const BasicVector3& point) -{ - return BasicVector3( - static_cast(self[0] * point[0] + self[4] * point[1] + self[8] * point[2] + self[12]), - static_cast(self[1] * point[0] + self[5] * point[1] + self[9] * point[2] + self[13]), - static_cast(self[2] * point[0] + self[6] * point[1] + self[10] * point[2] + self[14]) - ); +inline BasicVector3 matrix4_transformed_point( const Matrix4& self, const BasicVector3& point ){ + return BasicVector3( + static_cast( self[0] * point[0] + self[4] * point[1] + self[8] * point[2] + self[12] ), + static_cast( self[1] * point[0] + self[5] * point[1] + self[9] * point[2] + self[13] ), + static_cast( self[2] * point[0] + self[6] * point[1] + self[10] * point[2] + self[14] ) + ); } /// \brief Transforms \p point by \p self in-place. template -inline void matrix4_transform_point(const Matrix4& self, BasicVector3& point) -{ - point = matrix4_transformed_point(self, point); +inline void matrix4_transform_point( const Matrix4& self, BasicVector3& point ){ + point = matrix4_transformed_point( self, point ); } /// \brief Returns \p direction transformed by \p self. template -inline BasicVector3 matrix4_transformed_direction(const Matrix4& self, const BasicVector3& direction) -{ - return BasicVector3( - static_cast(self[0] * direction[0] + self[4] * direction[1] + self[8] * direction[2]), - static_cast(self[1] * direction[0] + self[5] * direction[1] + self[9] * direction[2]), - static_cast(self[2] * direction[0] + self[6] * direction[1] + self[10] * direction[2]) - ); +inline BasicVector3 matrix4_transformed_direction( const Matrix4& self, const BasicVector3& direction ){ + return BasicVector3( + static_cast( self[0] * direction[0] + self[4] * direction[1] + self[8] * direction[2] ), + static_cast( self[1] * direction[0] + self[5] * direction[1] + self[9] * direction[2] ), + static_cast( self[2] * direction[0] + self[6] * direction[1] + self[10] * direction[2] ) + ); } /// \brief Transforms \p direction by \p self in-place. template -inline void matrix4_transform_direction(const Matrix4& self, BasicVector3& normal) -{ - normal = matrix4_transformed_direction(self, normal); +inline void matrix4_transform_direction( const Matrix4& self, BasicVector3& normal ){ + normal = matrix4_transformed_direction( self, normal ); } /// \brief Returns \p vector4 transformed by \p self. -inline Vector4 matrix4_transformed_vector4(const Matrix4& self, const Vector4& vector4) -{ - return Vector4( - self[0] * vector4[0] + self[4] * vector4[1] + self[8] * vector4[2] + self[12] * vector4[3], - self[1] * vector4[0] + self[5] * vector4[1] + self[9] * vector4[2] + self[13] * vector4[3], - self[2] * vector4[0] + self[6] * vector4[1] + self[10] * vector4[2] + self[14] * vector4[3], - self[3] * vector4[0] + self[7] * vector4[1] + self[11] * vector4[2] + self[15] * vector4[3] - ); +inline Vector4 matrix4_transformed_vector4( const Matrix4& self, const Vector4& vector4 ){ + return Vector4( + self[0] * vector4[0] + self[4] * vector4[1] + self[8] * vector4[2] + self[12] * vector4[3], + self[1] * vector4[0] + self[5] * vector4[1] + self[9] * vector4[2] + self[13] * vector4[3], + self[2] * vector4[0] + self[6] * vector4[1] + self[10] * vector4[2] + self[14] * vector4[3], + self[3] * vector4[0] + self[7] * vector4[1] + self[11] * vector4[2] + self[15] * vector4[3] + ); } /// \brief Transforms \p vector4 by \p self in-place. -inline void matrix4_transform_vector4(const Matrix4& self, Vector4& vector4) -{ - vector4 = matrix4_transformed_vector4(self, vector4); +inline void matrix4_transform_vector4( const Matrix4& self, Vector4& vector4 ){ + vector4 = matrix4_transformed_vector4( self, vector4 ); } /// \brief Transposes \p self in-place. -inline void matrix4_transpose(Matrix4& self) -{ - std::swap(self.xy(), self.yx()); - std::swap(self.xz(), self.zx()); - std::swap(self.xw(), self.tx()); - std::swap(self.yz(), self.zy()); - std::swap(self.yw(), self.ty()); - std::swap(self.zw(), self.tz()); +inline void matrix4_transpose( Matrix4& self ){ + std::swap( self.xy(), self.yx() ); + std::swap( self.xz(), self.zx() ); + std::swap( self.xw(), self.tx() ); + std::swap( self.yz(), self.zy() ); + std::swap( self.yw(), self.ty() ); + std::swap( self.zw(), self.tz() ); } /// \brief Returns \p self transposed. -inline Matrix4 matrix4_transposed(const Matrix4& self) -{ - return Matrix4( - self.xx(), - self.yx(), - self.zx(), - self.tx(), - self.xy(), - self.yy(), - self.zy(), - self.ty(), - self.xz(), - self.yz(), - self.zz(), - self.tz(), - self.xw(), - self.yw(), - self.zw(), - self.tw() - ); +inline Matrix4 matrix4_transposed( const Matrix4& self ){ + return Matrix4( + self.xx(), + self.yx(), + self.zx(), + self.tx(), + self.xy(), + self.yy(), + self.zy(), + self.ty(), + self.xz(), + self.yz(), + self.zz(), + self.tz(), + self.xw(), + self.yw(), + self.zw(), + self.tw() + ); } /// \brief Inverts an affine transform in-place. /// Adapted from Graphics Gems 2. -inline Matrix4 matrix4_affine_inverse(const Matrix4& self) -{ - Matrix4 result; - - // determinant of rotation submatrix - double det - = self[0] * ( self[5]*self[10] - self[9]*self[6] ) - - self[1] * ( self[4]*self[10] - self[8]*self[6] ) - + self[2] * ( self[4]*self[9] - self[8]*self[5] ); - - // throw exception here if (det*det < 1e-25) - - // invert rotation submatrix - det = 1.0 / det; - - result[0] = static_cast( (self[5]*self[10]- self[6]*self[9] )*det); - result[1] = static_cast(- (self[1]*self[10]- self[2]*self[9] )*det); - result[2] = static_cast( (self[1]*self[6] - self[2]*self[5] )*det); - result[3] = 0; - result[4] = static_cast(- (self[4]*self[10]- self[6]*self[8] )*det); - result[5] = static_cast( (self[0]*self[10]- self[2]*self[8] )*det); - result[6] = static_cast(- (self[0]*self[6] - self[2]*self[4] )*det); - result[7] = 0; - result[8] = static_cast( (self[4]*self[9] - self[5]*self[8] )*det); - result[9] = static_cast(- (self[0]*self[9] - self[1]*self[8] )*det); - result[10]= static_cast( (self[0]*self[5] - self[1]*self[4] )*det); - result[11] = 0; - - // multiply translation part by rotation - result[12] = - (self[12] * result[0] + - self[13] * result[4] + - self[14] * result[8]); - result[13] = - (self[12] * result[1] + - self[13] * result[5] + - self[14] * result[9]); - result[14] = - (self[12] * result[2] + - self[13] * result[6] + - self[14] * result[10]); - result[15] = 1; - - return result; -} - -inline void matrix4_affine_invert(Matrix4& self) -{ - self = matrix4_affine_inverse(self); +inline Matrix4 matrix4_affine_inverse( const Matrix4& self ){ + Matrix4 result; + + // determinant of rotation submatrix + double det + = self[0] * ( self[5] * self[10] - self[9] * self[6] ) + - self[1] * ( self[4] * self[10] - self[8] * self[6] ) + + self[2] * ( self[4] * self[9] - self[8] * self[5] ); + + // throw exception here if (det*det < 1e-25) + + // invert rotation submatrix + det = 1.0 / det; + + result[0] = static_cast( ( self[5] * self[10] - self[6] * self[9] ) * det ); + result[1] = static_cast( -( self[1] * self[10] - self[2] * self[9] ) * det ); + result[2] = static_cast( ( self[1] * self[6] - self[2] * self[5] ) * det ); + result[3] = 0; + result[4] = static_cast( -( self[4] * self[10] - self[6] * self[8] ) * det ); + result[5] = static_cast( ( self[0] * self[10] - self[2] * self[8] ) * det ); + result[6] = static_cast( -( self[0] * self[6] - self[2] * self[4] ) * det ); + result[7] = 0; + result[8] = static_cast( ( self[4] * self[9] - self[5] * self[8] ) * det ); + result[9] = static_cast( -( self[0] * self[9] - self[1] * self[8] ) * det ); + result[10] = static_cast( ( self[0] * self[5] - self[1] * self[4] ) * det ); + result[11] = 0; + + // multiply translation part by rotation + result[12] = -( self[12] * result[0] + + self[13] * result[4] + + self[14] * result[8] ); + result[13] = -( self[12] * result[1] + + self[13] * result[5] + + self[14] * result[9] ); + result[14] = -( self[12] * result[2] + + self[13] * result[6] + + self[14] * result[10] ); + result[15] = 1; + + return result; +} + +inline void matrix4_affine_invert( Matrix4& self ){ + self = matrix4_affine_inverse( self ); } /// \brief A compile-time-constant integer. template struct IntegralConstant { - enum unnamed_{ VALUE = VALUE_ }; + enum unnamed_ { VALUE = VALUE_ }; }; /// \brief A compile-time-constant row/column index into a 4x4 matrix. @@ -619,9 +547,9 @@ template class Matrix4Index { public: - typedef IntegralConstant r; - typedef IntegralConstant c; - typedef IntegralConstant<(r::VALUE * 4) + c::VALUE> i; +typedef IntegralConstant r; +typedef IntegralConstant c; +typedef IntegralConstant<( r::VALUE * 4 ) + c::VALUE> i; }; /// \brief A functor which returns the cofactor of a 3x3 submatrix obtained by ignoring a given row and column of a 4x4 matrix. @@ -631,21 +559,20 @@ template class Matrix4Cofactor { public: - typedef typename Matrix4Index::i xx; - typedef typename Matrix4Index::i xy; - typedef typename Matrix4Index::i xz; - typedef typename Matrix4Index::i yx; - typedef typename Matrix4Index::i yy; - typedef typename Matrix4Index::i yz; - typedef typename Matrix4Index::i zx; - typedef typename Matrix4Index::i zy; - typedef typename Matrix4Index::i zz; - static double apply(const Matrix4& self) - { - return self[xx::VALUE] * ( self[yy::VALUE]*self[zz::VALUE] - self[zy::VALUE]*self[yz::VALUE] ) - - self[xy::VALUE] * ( self[yx::VALUE]*self[zz::VALUE] - self[zx::VALUE]*self[yz::VALUE] ) - + self[xz::VALUE] * ( self[yx::VALUE]*self[zy::VALUE] - self[zx::VALUE]*self[yy::VALUE] ); - } +typedef typename Matrix4Index::i xx; +typedef typename Matrix4Index::i xy; +typedef typename Matrix4Index::i xz; +typedef typename Matrix4Index::i yx; +typedef typename Matrix4Index::i yy; +typedef typename Matrix4Index::i yz; +typedef typename Matrix4Index::i zx; +typedef typename Matrix4Index::i zy; +typedef typename Matrix4Index::i zz; +static double apply( const Matrix4& self ){ + return self[xx::VALUE] * ( self[yy::VALUE] * self[zz::VALUE] - self[zy::VALUE] * self[yz::VALUE] ) + - self[xy::VALUE] * ( self[yx::VALUE] * self[zz::VALUE] - self[zx::VALUE] * self[yz::VALUE] ) + + self[xz::VALUE] * ( self[yx::VALUE] * self[zy::VALUE] - self[zx::VALUE] * self[yy::VALUE] ); +} }; /// \brief The cofactor element indices for a 4x4 matrix row or column. @@ -654,82 +581,75 @@ template class Cofactor4 { public: - typedef IntegralConstant<(Element <= 0) ? 1 : 0> x; - typedef IntegralConstant<(Element <= 1) ? 2 : 1> y; - typedef IntegralConstant<(Element <= 2) ? 3 : 2> z; +typedef IntegralConstant<( Element <= 0 ) ? 1 : 0> x; +typedef IntegralConstant<( Element <= 1 ) ? 2 : 1> y; +typedef IntegralConstant<( Element <= 2 ) ? 3 : 2> z; }; /// \brief Returns the determinant of \p self. -inline double matrix4_determinant(const Matrix4& self) -{ - return self.xx() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply(self) - - self.xy() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply(self) - + self.xz() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply(self) - - self.xw() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply(self); +inline double matrix4_determinant( const Matrix4& self ){ + return self.xx() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) + - self.xy() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) + + self.xz() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) + - self.xw() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ); } /// \brief Returns the inverse of \p self using the Adjoint method. /// \todo Throw an exception if the determinant is zero. -inline Matrix4 matrix4_full_inverse(const Matrix4& self) -{ - double determinant = 1.0 / matrix4_determinant(self); - - return Matrix4( - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<1>, Cofactor4<0> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<0> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<3>, Cofactor4<0> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<1> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<2>, Cofactor4<1> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<1> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<1>, Cofactor4<2> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<2> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<3>, Cofactor4<2> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<3> >::apply(self) * determinant), - static_cast(-Matrix4Cofactor< Cofactor4<2>, Cofactor4<3> >::apply(self) * determinant), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<3> >::apply(self) * determinant) - ); +inline Matrix4 matrix4_full_inverse( const Matrix4& self ){ + double determinant = 1.0 / matrix4_determinant( self ); + + return Matrix4( + static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<0> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<1> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<2> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<3> >::apply( self ) * determinant ), + static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<3> >::apply( self ) * determinant ) + ); } /// \brief Inverts \p self in-place using the Adjoint method. -inline void matrix4_full_invert(Matrix4& self) -{ - self = matrix4_full_inverse(self); +inline void matrix4_full_invert( Matrix4& self ){ + self = matrix4_full_inverse( self ); } /// \brief Constructs a pure-translation matrix from \p translation. -inline Matrix4 matrix4_translation_for_vec3(const Vector3& translation) -{ - return Matrix4( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - translation[0], translation[1], translation[2], 1 - ); +inline Matrix4 matrix4_translation_for_vec3( const Vector3& translation ){ + return Matrix4( + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + translation[0], translation[1], translation[2], 1 + ); } /// \brief Returns the translation part of \p self. -inline Vector3 matrix4_get_translation_vec3(const Matrix4& self) -{ - return vector4_to_vector3(self.t()); +inline Vector3 matrix4_get_translation_vec3( const Matrix4& self ){ + return vector4_to_vector3( self.t() ); } /// \brief Concatenates \p self with \p translation. /// The concatenated \p translation occurs before \p self. -inline void matrix4_translate_by_vec3(Matrix4& self, const Vector3& translation) -{ - matrix4_multiply_by_matrix4(self, matrix4_translation_for_vec3(translation)); +inline void matrix4_translate_by_vec3( Matrix4& self, const Vector3& translation ){ + matrix4_multiply_by_matrix4( self, matrix4_translation_for_vec3( translation ) ); } /// \brief Returns \p self Concatenated with \p translation. /// The concatenated translation occurs before \p self. -inline Matrix4 matrix4_translated_by_vec3(const Matrix4& self, const Vector3& translation) -{ - return matrix4_multiplied_by_matrix4(self, matrix4_translation_for_vec3(translation)); +inline Matrix4 matrix4_translated_by_vec3( const Matrix4& self, const Vector3& translation ){ + return matrix4_multiplied_by_matrix4( self, matrix4_translation_for_vec3( translation ) ); } @@ -737,585 +657,537 @@ inline Matrix4 matrix4_translated_by_vec3(const Matrix4& self, const Vector3& tr /// \brief Returns \p angle modulated by the range [0, 360). /// \p angle must be in the range [-360, 360). -inline float angle_modulate_degrees_range(float angle) -{ - return static_cast(float_mod_range(angle, 360.0)); +inline float angle_modulate_degrees_range( float angle ){ + return static_cast( float_mod_range( angle, 360.0 ) ); } /// \brief Returns \p euler angles converted from radians to degrees. -inline Vector3 euler_radians_to_degrees(const Vector3& euler) -{ - return Vector3( - static_cast(radians_to_degrees(euler.x())), - static_cast(radians_to_degrees(euler.y())), - static_cast(radians_to_degrees(euler.z())) - ); +inline Vector3 euler_radians_to_degrees( const Vector3& euler ){ + return Vector3( + static_cast( radians_to_degrees( euler.x() ) ), + static_cast( radians_to_degrees( euler.y() ) ), + static_cast( radians_to_degrees( euler.z() ) ) + ); } /// \brief Returns \p euler angles converted from degrees to radians. -inline Vector3 euler_degrees_to_radians(const Vector3& euler) -{ - return Vector3( - static_cast(degrees_to_radians(euler.x())), - static_cast(degrees_to_radians(euler.y())), - static_cast(degrees_to_radians(euler.z())) - ); +inline Vector3 euler_degrees_to_radians( const Vector3& euler ){ + return Vector3( + static_cast( degrees_to_radians( euler.x() ) ), + static_cast( degrees_to_radians( euler.y() ) ), + static_cast( degrees_to_radians( euler.z() ) ) + ); } /// \brief Constructs a pure-rotation matrix about the x axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_x(float s, float c) -{ - return Matrix4( - 1, 0, 0, 0, - 0, c, s, 0, - 0,-s, c, 0, - 0, 0, 0, 1 - ); +inline Matrix4 matrix4_rotation_for_sincos_x( float s, float c ){ + return Matrix4( + 1, 0, 0, 0, + 0, c, s, 0, + 0,-s, c, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the x axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_x(double x) -{ - return matrix4_rotation_for_sincos_x(static_cast(sin(x)), static_cast(cos(x))); +inline Matrix4 matrix4_rotation_for_x( double x ){ + return matrix4_rotation_for_sincos_x( static_cast( sin( x ) ), static_cast( cos( x ) ) ); } /// \brief Constructs a pure-rotation matrix about the x axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_x_degrees(float x) -{ - return matrix4_rotation_for_x(degrees_to_radians(x)); +inline Matrix4 matrix4_rotation_for_x_degrees( float x ){ + return matrix4_rotation_for_x( degrees_to_radians( x ) ); } /// \brief Constructs a pure-rotation matrix about the y axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_y(float s, float c) -{ - return Matrix4( - c, 0,-s, 0, - 0, 1, 0, 0, - s, 0, c, 0, - 0, 0, 0, 1 - ); +inline Matrix4 matrix4_rotation_for_sincos_y( float s, float c ){ + return Matrix4( + c, 0,-s, 0, + 0, 1, 0, 0, + s, 0, c, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the y axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_y(double y) -{ - return matrix4_rotation_for_sincos_y(static_cast(sin(y)), static_cast(cos(y))); +inline Matrix4 matrix4_rotation_for_y( double y ){ + return matrix4_rotation_for_sincos_y( static_cast( sin( y ) ), static_cast( cos( y ) ) ); } /// \brief Constructs a pure-rotation matrix about the y axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_y_degrees(float y) -{ - return matrix4_rotation_for_y(degrees_to_radians(y)); +inline Matrix4 matrix4_rotation_for_y_degrees( float y ){ + return matrix4_rotation_for_y( degrees_to_radians( y ) ); } /// \brief Constructs a pure-rotation matrix about the z axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_z(float s, float c) -{ - return Matrix4( - c, s, 0, 0, - -s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); +inline Matrix4 matrix4_rotation_for_sincos_z( float s, float c ){ + return Matrix4( + c, s, 0, 0, + -s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 + ); } /// \brief Constructs a pure-rotation matrix about the z axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_z(double z) -{ - return matrix4_rotation_for_sincos_z(static_cast(sin(z)), static_cast(cos(z))); +inline Matrix4 matrix4_rotation_for_z( double z ){ + return matrix4_rotation_for_sincos_z( static_cast( sin( z ) ), static_cast( cos( z ) ) ); } /// \brief Constructs a pure-rotation matrix about the z axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_z_degrees(float z) -{ - return matrix4_rotation_for_z(degrees_to_radians(z)); +inline Matrix4 matrix4_rotation_for_z_degrees( float z ){ + return matrix4_rotation_for_z( degrees_to_radians( z ) ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (x, y, z). /*! \verbatim -clockwise rotation around X, Y, Z, facing along axis - 1 0 0 cy 0 -sy cz sz 0 - 0 cx sx 0 1 0 -sz cz 0 - 0 -sx cx sy 0 cy 0 0 1 - -rows of Z by cols of Y - cy*cz -sy*cz+sz -sy*sz+cz --sz*cy -sz*sy+cz - - .. or something like that.. - -final rotation is Z * Y * X - cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz --cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz - sy -sx*cy cx*cy - -transposed -cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | -sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | --cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | -\endverbatim */ -inline Matrix4 matrix4_rotation_for_euler_xyz(const Vector3& euler) -{ + clockwise rotation around X, Y, Z, facing along axis + 1 0 0 cy 0 -sy cz sz 0 + 0 cx sx 0 1 0 -sz cz 0 + 0 -sx cx sy 0 cy 0 0 1 + + rows of Z by cols of Y + cy*cz -sy*cz+sz -sy*sz+cz + -sz*cy -sz*sy+cz + + .. or something like that.. + + final rotation is Z * Y * X + cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz + -cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz + sy -sx*cy cx*cy + + transposed + cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | + sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | + -cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | + \endverbatim */ +inline Matrix4 matrix4_rotation_for_euler_xyz( const Vector3& euler ){ #if 1 - double cx = cos(euler[0]); - double sx = sin(euler[0]); - double cy = cos(euler[1]); - double sy = sin(euler[1]); - double cz = cos(euler[2]); - double sz = sin(euler[2]); - - return Matrix4( - static_cast(cy*cz), - static_cast(cy*sz), - static_cast(-sy), - 0, - static_cast(sx*sy*cz + cx*-sz), - static_cast(sx*sy*sz + cx*cz), - static_cast(sx*cy), - 0, - static_cast(cx*sy*cz + sx*sz), - static_cast(cx*sy*sz + -sx*cz), - static_cast(cx*cy), - 0, - 0, - 0, - 0, - 1 - ); + double cx = cos( euler[0] ); + double sx = sin( euler[0] ); + double cy = cos( euler[1] ); + double sy = sin( euler[1] ); + double cz = cos( euler[2] ); + double sz = sin( euler[2] ); + + return Matrix4( + static_cast( cy * cz ), + static_cast( cy * sz ), + static_cast( -sy ), + 0, + static_cast( sx * sy * cz + cx * -sz ), + static_cast( sx * sy * sz + cx * cz ), + static_cast( sx * cy ), + 0, + static_cast( cx * sy * cz + sx * sz ), + static_cast( cx * sy * sz + -sx * cz ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_x(euler[0]), - matrix4_rotation_for_y(euler[1]) - ), - matrix4_rotation_for_z(euler[2]) - ); + return matrix4_premultiply_by_matrix4( + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_x( euler[0] ), + matrix4_rotation_for_y( euler[1] ) + ), + matrix4_rotation_for_z( euler[2] ) + ); #endif } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (x, y, z). -inline Matrix4 matrix4_rotation_for_euler_xyz_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_xyz(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_xyz_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_xyz( euler_degrees_to_radians( euler ) ); } /// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (x, y, z). /// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_xyz_degrees(Matrix4& self, const Vector3& euler) -{ - matrix4_multiply_by_matrix4(self, matrix4_rotation_for_euler_xyz_degrees(euler)); +inline void matrix4_rotate_by_euler_xyz_degrees( Matrix4& self, const Vector3& euler ){ + matrix4_multiply_by_matrix4( self, matrix4_rotation_for_euler_xyz_degrees( euler ) ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (y, z, x). -inline Matrix4 matrix4_rotation_for_euler_yzx(const Vector3& euler) -{ - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_y(euler[1]), - matrix4_rotation_for_z(euler[2]) - ), - matrix4_rotation_for_x(euler[0]) - ); +inline Matrix4 matrix4_rotation_for_euler_yzx( const Vector3& euler ){ + return matrix4_premultiplied_by_matrix4( + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_y( euler[1] ), + matrix4_rotation_for_z( euler[2] ) + ), + matrix4_rotation_for_x( euler[0] ) + ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (y, z, x). -inline Matrix4 matrix4_rotation_for_euler_yzx_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_yzx(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_yzx_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_yzx( euler_degrees_to_radians( euler ) ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (x, z, y). -inline Matrix4 matrix4_rotation_for_euler_xzy(const Vector3& euler) -{ - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_x(euler[0]), - matrix4_rotation_for_z(euler[2]) - ), - matrix4_rotation_for_y(euler[1]) - ); +inline Matrix4 matrix4_rotation_for_euler_xzy( const Vector3& euler ){ + return matrix4_premultiplied_by_matrix4( + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_x( euler[0] ), + matrix4_rotation_for_z( euler[2] ) + ), + matrix4_rotation_for_y( euler[1] ) + ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (x, z, y). -inline Matrix4 matrix4_rotation_for_euler_xzy_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_xzy(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_xzy_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_xzy( euler_degrees_to_radians( euler ) ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (y, x, z). /*! \verbatim -| cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | -| cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | -| cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | -\endverbatim */ -inline Matrix4 matrix4_rotation_for_euler_yxz(const Vector3& euler) -{ + | cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | + | cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | + | cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | + \endverbatim */ +inline Matrix4 matrix4_rotation_for_euler_yxz( const Vector3& euler ){ #if 1 - double cx = cos(euler[0]); - double sx = sin(euler[0]); - double cy = cos(euler[1]); - double sy = sin(euler[1]); - double cz = cos(euler[2]); - double sz = sin(euler[2]); - - return Matrix4( - static_cast(cy*cz + sx*sy*-sz), - static_cast(cy*sz + sx*sy*cz), - static_cast(-cx*sy), - 0, - static_cast(cx*-sz), - static_cast(cx*cz), - static_cast(sx), - 0, - static_cast(sy*cz + -sx*cy*-sz), - static_cast(sy*sz + -sx*cy*cz), - static_cast(cx*cy), - 0, - 0, - 0, - 0, - 1 - ); + double cx = cos( euler[0] ); + double sx = sin( euler[0] ); + double cy = cos( euler[1] ); + double sy = sin( euler[1] ); + double cz = cos( euler[2] ); + double sz = sin( euler[2] ); + + return Matrix4( + static_cast( cy * cz + sx * sy * -sz ), + static_cast( cy * sz + sx * sy * cz ), + static_cast( -cx * sy ), + 0, + static_cast( cx * -sz ), + static_cast( cx * cz ), + static_cast( sx ), + 0, + static_cast( sy * cz + -sx * cy * -sz ), + static_cast( sy * sz + -sx * cy * cz ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_y(euler[1]), - matrix4_rotation_for_x(euler[0]) - ), - matrix4_rotation_for_z(euler[2]) - ); + return matrix4_premultiply_by_matrix4( + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_y( euler[1] ), + matrix4_rotation_for_x( euler[0] ) + ), + matrix4_rotation_for_z( euler[2] ) + ); #endif } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (y, x, z). -inline Matrix4 matrix4_rotation_for_euler_yxz_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_yxz(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_yxz_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_yxz( euler_degrees_to_radians( euler ) ); } /// \brief Returns \p self concatenated with the rotation transform produced by \p euler angles (degrees) in the order (y, x, z). /// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_euler_yxz_degrees(const Matrix4& self, const Vector3& euler) -{ - return matrix4_multiplied_by_matrix4(self, matrix4_rotation_for_euler_yxz_degrees(euler)); +inline Matrix4 matrix4_rotated_by_euler_yxz_degrees( const Matrix4& self, const Vector3& euler ){ + return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_euler_yxz_degrees( euler ) ); } /// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (y, x, z). /// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_yxz_degrees(Matrix4& self, const Vector3& euler) -{ - self = matrix4_rotated_by_euler_yxz_degrees(self, euler); +inline void matrix4_rotate_by_euler_yxz_degrees( Matrix4& self, const Vector3& euler ){ + self = matrix4_rotated_by_euler_yxz_degrees( self, euler ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (z, x, y). -inline Matrix4 matrix4_rotation_for_euler_zxy(const Vector3& euler) -{ +inline Matrix4 matrix4_rotation_for_euler_zxy( const Vector3& euler ){ #if 1 - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_z(euler[2]), - matrix4_rotation_for_x(euler[0]) - ), - matrix4_rotation_for_y(euler[1]) - ); + return matrix4_premultiplied_by_matrix4( + matrix4_premultiplied_by_matrix4( + matrix4_rotation_for_z( euler[2] ), + matrix4_rotation_for_x( euler[0] ) + ), + matrix4_rotation_for_y( euler[1] ) + ); #else - double cx = cos(euler[0]); - double sx = sin(euler[0]); - double cy = cos(euler[1]); - double sy = sin(euler[1]); - double cz = cos(euler[2]); - double sz = sin(euler[2]); - - return Matrix4( - static_cast(cz * cy + sz * sx * sy), - static_cast(sz * cx), - static_cast(cz * -sy + sz * sx * cy), - 0, - static_cast(-sz * cy + cz * sx * sy), - static_cast(cz * cx), - static_cast(-sz * -sy + cz * cx * cy), - 0, - static_cast(cx* sy), - static_cast(-sx), - static_cast(cx* cy), - 0, - 0, - 0, - 0, - 1 - ); + double cx = cos( euler[0] ); + double sx = sin( euler[0] ); + double cy = cos( euler[1] ); + double sy = sin( euler[1] ); + double cz = cos( euler[2] ); + double sz = sin( euler[2] ); + + return Matrix4( + static_cast( cz * cy + sz * sx * sy ), + static_cast( sz * cx ), + static_cast( cz * -sy + sz * sx * cy ), + 0, + static_cast( -sz * cy + cz * sx * sy ), + static_cast( cz * cx ), + static_cast( -sz * -sy + cz * cx * cy ), + 0, + static_cast( cx * sy ), + static_cast( -sx ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #endif } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degres=es) in the order (z, x, y). -inline Matrix4 matrix4_rotation_for_euler_zxy_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_zxy(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_zxy_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_zxy( euler_degrees_to_radians( euler ) ); } /// \brief Returns \p self concatenated with the rotation transform produced by \p euler angles (degrees) in the order (z, x, y). /// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_euler_zxy_degrees(const Matrix4& self, const Vector3& euler) -{ - return matrix4_multiplied_by_matrix4(self, matrix4_rotation_for_euler_zxy_degrees(euler)); +inline Matrix4 matrix4_rotated_by_euler_zxy_degrees( const Matrix4& self, const Vector3& euler ){ + return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_euler_zxy_degrees( euler ) ); } /// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (z, x, y). /// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_zxy_degrees(Matrix4& self, const Vector3& euler) -{ - self = matrix4_rotated_by_euler_zxy_degrees(self, euler); +inline void matrix4_rotate_by_euler_zxy_degrees( Matrix4& self, const Vector3& euler ){ + self = matrix4_rotated_by_euler_zxy_degrees( self, euler ); } /// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (z, y, x). -inline Matrix4 matrix4_rotation_for_euler_zyx(const Vector3& euler) -{ +inline Matrix4 matrix4_rotation_for_euler_zyx( const Vector3& euler ){ #if 1 - double cx = cos(euler[0]); - double sx = sin(euler[0]); - double cy = cos(euler[1]); - double sy = sin(euler[1]); - double cz = cos(euler[2]); - double sz = sin(euler[2]); - - return Matrix4( - static_cast(cy*cz), - static_cast(sx*sy*cz + cx*sz), - static_cast(cx*-sy*cz + sx*sz), - 0, - static_cast(cy*-sz), - static_cast(sx*sy*-sz + cx*cz), - static_cast(cx*-sy*-sz + sx*cz), - 0, - static_cast(sy), - static_cast(-sx*cy), - static_cast(cx*cy), - 0, - 0, - 0, - 0, - 1 - ); + double cx = cos( euler[0] ); + double sx = sin( euler[0] ); + double cy = cos( euler[1] ); + double sy = sin( euler[1] ); + double cz = cos( euler[2] ); + double sz = sin( euler[2] ); + + return Matrix4( + static_cast( cy * cz ), + static_cast( sx * sy * cz + cx * sz ), + static_cast( cx * -sy * cz + sx * sz ), + 0, + static_cast( cy * -sz ), + static_cast( sx * sy * -sz + cx * cz ), + static_cast( cx * -sy * -sz + sx * cz ), + 0, + static_cast( sy ), + static_cast( -sx * cy ), + static_cast( cx * cy ), + 0, + 0, + 0, + 0, + 1 + ); #else - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_z(euler[2]), - matrix4_rotation_for_y(euler[1]) - ), - matrix4_rotation_for_x(euler[0]) - ); + return matrix4_premultiply_by_matrix4( + matrix4_premultiply_by_matrix4( + matrix4_rotation_for_z( euler[2] ), + matrix4_rotation_for_y( euler[1] ) + ), + matrix4_rotation_for_x( euler[0] ) + ); #endif } /// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (z, y, x). -inline Matrix4 matrix4_rotation_for_euler_zyx_degrees(const Vector3& euler) -{ - return matrix4_rotation_for_euler_zyx(euler_degrees_to_radians(euler)); +inline Matrix4 matrix4_rotation_for_euler_zyx_degrees( const Vector3& euler ){ + return matrix4_rotation_for_euler_zyx( euler_degrees_to_radians( euler ) ); } /// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (x, y, z). /// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_xyz(const Matrix4& self) -{ - double a = asin(-self[2]); - double ca = cos(a); - - if (fabs(ca) > 0.005) // Gimbal lock? - { - return Vector3( - static_cast(atan2(self[6] / ca, self[10] / ca)), - static_cast(a), - static_cast(atan2(self[1] / ca, self[0]/ ca)) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast(atan2(-self[9], self[5])), - static_cast(a), - 0 - ); - } +inline Vector3 matrix4_get_rotation_euler_xyz( const Matrix4& self ){ + double a = asin( -self[2] ); + double ca = cos( a ); + + if ( fabs( ca ) > 0.005 ) { // Gimbal lock? + return Vector3( + static_cast( atan2( self[6] / ca, self[10] / ca ) ), + static_cast( a ), + static_cast( atan2( self[1] / ca, self[0] / ca ) ) + ); + } + else // Gimbal lock has occurred + { + return Vector3( + static_cast( atan2( -self[9], self[5] ) ), + static_cast( a ), + 0 + ); + } } /// \brief \copydoc matrix4_get_rotation_euler_xyz(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_xyz_degrees(const Matrix4& self) -{ - return euler_radians_to_degrees(matrix4_get_rotation_euler_xyz(self)); +inline Vector3 matrix4_get_rotation_euler_xyz_degrees( const Matrix4& self ){ + return euler_radians_to_degrees( matrix4_get_rotation_euler_xyz( self ) ); } /// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (y, x, z). /// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_yxz(const Matrix4& self) -{ - double a = asin(self[6]); - double ca = cos(a); - - if (fabs(ca) > 0.005) // Gimbal lock? - { - return Vector3( - static_cast(a), - static_cast(atan2(-self[2] / ca, self[10]/ ca)), - static_cast(atan2(-self[4] / ca, self[5] / ca)) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast(a), - static_cast(atan2(self[8], self[0])), - 0 - ); - } +inline Vector3 matrix4_get_rotation_euler_yxz( const Matrix4& self ){ + double a = asin( self[6] ); + double ca = cos( a ); + + if ( fabs( ca ) > 0.005 ) { // Gimbal lock? + return Vector3( + static_cast( a ), + static_cast( atan2( -self[2] / ca, self[10] / ca ) ), + static_cast( atan2( -self[4] / ca, self[5] / ca ) ) + ); + } + else // Gimbal lock has occurred + { + return Vector3( + static_cast( a ), + static_cast( atan2( self[8], self[0] ) ), + 0 + ); + } } /// \brief \copydoc matrix4_get_rotation_euler_yxz(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_yxz_degrees(const Matrix4& self) -{ - return euler_radians_to_degrees(matrix4_get_rotation_euler_yxz(self)); +inline Vector3 matrix4_get_rotation_euler_yxz_degrees( const Matrix4& self ){ + return euler_radians_to_degrees( matrix4_get_rotation_euler_yxz( self ) ); } /// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (z, x, y). /// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_zxy(const Matrix4& self) -{ - double a = asin(-self[9]); - double ca = cos(a); - - if (fabs(ca) > 0.005) // Gimbal lock? - { - return Vector3( - static_cast(a), - static_cast(atan2(self[8] / ca, self[10] / ca)), - static_cast(atan2(self[1] / ca, self[5]/ ca)) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast(a), - 0, - static_cast(atan2(-self[4], self[0])) - ); - } +inline Vector3 matrix4_get_rotation_euler_zxy( const Matrix4& self ){ + double a = asin( -self[9] ); + double ca = cos( a ); + + if ( fabs( ca ) > 0.005 ) { // Gimbal lock? + return Vector3( + static_cast( a ), + static_cast( atan2( self[8] / ca, self[10] / ca ) ), + static_cast( atan2( self[1] / ca, self[5] / ca ) ) + ); + } + else // Gimbal lock has occurred + { + return Vector3( + static_cast( a ), + 0, + static_cast( atan2( -self[4], self[0] ) ) + ); + } } /// \brief \copydoc matrix4_get_rotation_euler_zxy(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_zxy_degrees(const Matrix4& self) -{ - return euler_radians_to_degrees(matrix4_get_rotation_euler_zxy(self)); +inline Vector3 matrix4_get_rotation_euler_zxy_degrees( const Matrix4& self ){ + return euler_radians_to_degrees( matrix4_get_rotation_euler_zxy( self ) ); } /// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (z, y, x). /// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_zyx(const Matrix4& self) -{ - double a = asin(self[8]); - double ca = cos(a); - - if (fabs(ca) > 0.005) // Gimbal lock? - { - return Vector3( - static_cast(atan2(-self[9] / ca, self[10]/ ca)), - static_cast(a), - static_cast(atan2(-self[4] / ca, self[0] / ca)) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - 0, - static_cast(a), - static_cast(atan2(self[1], self[5])) - ); - } +inline Vector3 matrix4_get_rotation_euler_zyx( const Matrix4& self ){ + double a = asin( self[8] ); + double ca = cos( a ); + + if ( fabs( ca ) > 0.005 ) { // Gimbal lock? + return Vector3( + static_cast( atan2( -self[9] / ca, self[10] / ca ) ), + static_cast( a ), + static_cast( atan2( -self[4] / ca, self[0] / ca ) ) + ); + } + else // Gimbal lock has occurred + { + return Vector3( + 0, + static_cast( a ), + static_cast( atan2( self[1], self[5] ) ) + ); + } } /// \brief \copydoc matrix4_get_rotation_euler_zyx(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_zyx_degrees(const Matrix4& self) -{ - return euler_radians_to_degrees(matrix4_get_rotation_euler_zyx(self)); +inline Vector3 matrix4_get_rotation_euler_zyx_degrees( const Matrix4& self ){ + return euler_radians_to_degrees( matrix4_get_rotation_euler_zyx( self ) ); } /// \brief Rotate \p self by \p euler angles (degrees) applied in the order (x, y, z), using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_euler_xyz_degrees(Matrix4& self, const Vector3& euler, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(self, pivotpoint); - matrix4_rotate_by_euler_xyz_degrees(self, euler); - matrix4_translate_by_vec3(self, vector3_negated(pivotpoint)); +inline void matrix4_pivoted_rotate_by_euler_xyz_degrees( Matrix4& self, const Vector3& euler, const Vector3& pivotpoint ){ + matrix4_translate_by_vec3( self, pivotpoint ); + matrix4_rotate_by_euler_xyz_degrees( self, euler ); + matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); } /// \brief Constructs a pure-scale matrix from \p scale. -inline Matrix4 matrix4_scale_for_vec3(const Vector3& scale) -{ - return Matrix4( - scale[0], 0, 0, 0, - 0, scale[1], 0, 0, - 0, 0, scale[2], 0, - 0, 0, 0, 1 - ); +inline Matrix4 matrix4_scale_for_vec3( const Vector3& scale ){ + return Matrix4( + scale[0], 0, 0, 0, + 0, scale[1], 0, 0, + 0, 0, scale[2], 0, + 0, 0, 0, 1 + ); } /// \brief Calculates and returns the (x, y, z) scale values that produce the scale component of \p self. /// \p self must be affine and orthogonal to produce a meaningful result. -inline Vector3 matrix4_get_scale_vec3(const Matrix4& self) -{ - return Vector3( - static_cast(vector3_length(vector4_to_vector3(self.x()))), - static_cast(vector3_length(vector4_to_vector3(self.y()))), - static_cast(vector3_length(vector4_to_vector3(self.z()))) - ); +inline Vector3 matrix4_get_scale_vec3( const Matrix4& self ){ + return Vector3( + static_cast( vector3_length( vector4_to_vector3( self.x() ) ) ), + static_cast( vector3_length( vector4_to_vector3( self.y() ) ) ), + static_cast( vector3_length( vector4_to_vector3( self.z() ) ) ) + ); } /// \brief Scales \p self by \p scale. -inline void matrix4_scale_by_vec3(Matrix4& self, const Vector3& scale) -{ - matrix4_multiply_by_matrix4(self, matrix4_scale_for_vec3(scale)); +inline void matrix4_scale_by_vec3( Matrix4& self, const Vector3& scale ){ + matrix4_multiply_by_matrix4( self, matrix4_scale_for_vec3( scale ) ); } /// \brief Scales \p self by \p scale, using \p pivotpoint. -inline void matrix4_pivoted_scale_by_vec3(Matrix4& self, const Vector3& scale, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(self, pivotpoint); - matrix4_scale_by_vec3(self, scale); - matrix4_translate_by_vec3(self, vector3_negated(pivotpoint)); +inline void matrix4_pivoted_scale_by_vec3( Matrix4& self, const Vector3& scale, const Vector3& pivotpoint ){ + matrix4_translate_by_vec3( self, pivotpoint ); + matrix4_scale_by_vec3( self, scale ); + matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); } /// \brief Transforms \p self by \p translation, \p euler and \p scale. /// The transforms are combined in the order: scale, rotate-z, rotate-y, rotate-x, translate. -inline void matrix4_transform_by_euler_xyz_degrees(Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale) -{ - matrix4_translate_by_vec3(self, translation); - matrix4_rotate_by_euler_xyz_degrees(self, euler); - matrix4_scale_by_vec3(self, scale); +inline void matrix4_transform_by_euler_xyz_degrees( Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale ){ + matrix4_translate_by_vec3( self, translation ); + matrix4_rotate_by_euler_xyz_degrees( self, euler ); + matrix4_scale_by_vec3( self, scale ); } /// \brief Transforms \p self by \p translation, \p euler and \p scale, using \p pivotpoint. -inline void matrix4_pivoted_transform_by_euler_xyz_degrees(Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(self, pivotpoint + translation); - matrix4_rotate_by_euler_xyz_degrees(self, euler); - matrix4_scale_by_vec3(self, scale); - matrix4_translate_by_vec3(self, vector3_negated(pivotpoint)); +inline void matrix4_pivoted_transform_by_euler_xyz_degrees( Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale, const Vector3& pivotpoint ){ + matrix4_translate_by_vec3( self, pivotpoint + translation ); + matrix4_rotate_by_euler_xyz_degrees( self, euler ); + matrix4_scale_by_vec3( self, scale ); + matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); } diff --git a/libs/math/pi.cpp b/libs/math/pi.cpp index 34930192..dd546531 100644 --- a/libs/math/pi.cpp +++ b/libs/math/pi.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "pi.h" - diff --git a/libs/math/pi.h b/libs/math/pi.h index 9cc74c1b..dde3f48b 100644 --- a/libs/math/pi.h +++ b/libs/math/pi.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_PI_H) +#if !defined( INCLUDED_MATH_PI_H ) #define INCLUDED_MATH_PI_H /// \file @@ -33,13 +33,11 @@ const double c_inv_2pi = 1 / c_2pi; const double c_DEG2RADMULT = c_pi / 180.0; const double c_RAD2DEGMULT = 180.0 / c_pi; -inline double radians_to_degrees(double radians) -{ - return radians * c_RAD2DEGMULT; +inline double radians_to_degrees( double radians ){ + return radians * c_RAD2DEGMULT; } -inline double degrees_to_radians(double degrees) -{ - return degrees * c_DEG2RADMULT; +inline double degrees_to_radians( double degrees ){ + return degrees * c_DEG2RADMULT; } #endif diff --git a/libs/math/plane.cpp b/libs/math/plane.cpp index 4182a175..7b90b5ec 100644 --- a/libs/math/plane.cpp +++ b/libs/math/plane.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "plane.h" - diff --git a/libs/math/plane.h b/libs/math/plane.h index af05db74..4027164f 100644 --- a/libs/math/plane.h +++ b/libs/math/plane.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_PLANE_H) +#if !defined( INCLUDED_MATH_PLANE_H ) #define INCLUDED_MATH_PLANE_H /// \file @@ -31,122 +31,105 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class Plane3 { public: - double a, b, c, d; - - Plane3() - { - } - Plane3(double _a, double _b, double _c, double _d) - : a(_a), b(_b), c(_c), d(_d) - { - } - template - Plane3(const BasicVector3& normal, double dist) - : a(normal.x()), b(normal.y()), c(normal.z()), d(dist) - { - } - - BasicVector3& normal() - { - return reinterpret_cast&>(*this); - } - const BasicVector3& normal() const - { - return reinterpret_cast&>(*this); - } - double& dist() - { - return d; - } - const double& dist() const - { - return d; - } +double a, b, c, d; + +Plane3(){ +} +Plane3( double _a, double _b, double _c, double _d ) + : a( _a ), b( _b ), c( _c ), d( _d ){ +} +template +Plane3( const BasicVector3& normal, double dist ) + : a( normal.x() ), b( normal.y() ), c( normal.z() ), d( dist ){ +} + +BasicVector3& normal(){ + return reinterpret_cast&>( *this ); +} +const BasicVector3& normal() const { + return reinterpret_cast&>( *this ); +} +double& dist(){ + return d; +} +const double& dist() const { + return d; +} }; -inline Plane3 plane3_normalised(const Plane3& plane) -{ - double rmagnitude = 1.0 / sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c); - return Plane3( - plane.a * rmagnitude, - plane.b * rmagnitude, - plane.c * rmagnitude, - plane.d * rmagnitude - ); +inline Plane3 plane3_normalised( const Plane3& plane ){ + double rmagnitude = 1.0 / sqrt( plane.a * plane.a + plane.b * plane.b + plane.c * plane.c ); + return Plane3( + plane.a * rmagnitude, + plane.b * rmagnitude, + plane.c * rmagnitude, + plane.d * rmagnitude + ); } -inline Plane3 plane3_translated(const Plane3& plane, const Vector3& translation) -{ - Plane3 transformed; - transformed.a = plane.a; - transformed.b = plane.b; - transformed.c = plane.c; - transformed.d = -((-plane.d * transformed.a + translation.x()) * transformed.a + - (-plane.d * transformed.b + translation.y()) * transformed.b + - (-plane.d * transformed.c + translation.z()) * transformed.c); - return transformed; +inline Plane3 plane3_translated( const Plane3& plane, const Vector3& translation ){ + Plane3 transformed; + transformed.a = plane.a; + transformed.b = plane.b; + transformed.c = plane.c; + transformed.d = -( ( -plane.d * transformed.a + translation.x() ) * transformed.a + + ( -plane.d * transformed.b + translation.y() ) * transformed.b + + ( -plane.d * transformed.c + translation.z() ) * transformed.c ); + return transformed; } -inline Plane3 plane3_transformed(const Plane3& plane, const Matrix4& transform) -{ - Plane3 transformed; - transformed.a = transform[0] * plane.a + transform[4] * plane.b + transform[8] * plane.c; - transformed.b = transform[1] * plane.a + transform[5] * plane.b + transform[9] * plane.c; - transformed.c = transform[2] * plane.a + transform[6] * plane.b + transform[10] * plane.c; - transformed.d = -((-plane.d * transformed.a + transform[12]) * transformed.a + - (-plane.d * transformed.b + transform[13]) * transformed.b + - (-plane.d * transformed.c + transform[14]) * transformed.c); - return transformed; +inline Plane3 plane3_transformed( const Plane3& plane, const Matrix4& transform ){ + Plane3 transformed; + transformed.a = transform[0] * plane.a + transform[4] * plane.b + transform[8] * plane.c; + transformed.b = transform[1] * plane.a + transform[5] * plane.b + transform[9] * plane.c; + transformed.c = transform[2] * plane.a + transform[6] * plane.b + transform[10] * plane.c; + transformed.d = -( ( -plane.d * transformed.a + transform[12] ) * transformed.a + + ( -plane.d * transformed.b + transform[13] ) * transformed.b + + ( -plane.d * transformed.c + transform[14] ) * transformed.c ); + return transformed; } -inline Plane3 plane3_inverse_transformed(const Plane3& plane, const Matrix4& transform) -{ - return Plane3 - ( - transform[ 0] * plane.a + transform[ 1] * plane.b + transform[ 2] * plane.c + transform[ 3] * plane.d, - transform[ 4] * plane.a + transform[ 5] * plane.b + transform[ 6] * plane.c + transform[ 7] * plane.d, - transform[ 8] * plane.a + transform[ 9] * plane.b + transform[10] * plane.c + transform[11] * plane.d, - transform[12] * plane.a + transform[13] * plane.b + transform[14] * plane.c + transform[15] * plane.d - ); +inline Plane3 plane3_inverse_transformed( const Plane3& plane, const Matrix4& transform ){ + return Plane3 + ( + transform[ 0] * plane.a + transform[ 1] * plane.b + transform[ 2] * plane.c + transform[ 3] * plane.d, + transform[ 4] * plane.a + transform[ 5] * plane.b + transform[ 6] * plane.c + transform[ 7] * plane.d, + transform[ 8] * plane.a + transform[ 9] * plane.b + transform[10] * plane.c + transform[11] * plane.d, + transform[12] * plane.a + transform[13] * plane.b + transform[14] * plane.c + transform[15] * plane.d + ); } -inline Plane3 plane3_flipped(const Plane3& plane) -{ - return Plane3(vector3_negated(plane.normal()), -plane.dist()); +inline Plane3 plane3_flipped( const Plane3& plane ){ + return Plane3( vector3_negated( plane.normal() ), -plane.dist() ); } const double c_PLANE_NORMAL_EPSILON = 0.0001f; const double c_PLANE_DIST_EPSILON = 0.02; -inline bool plane3_equal(const Plane3& self, const Plane3& other) -{ - return vector3_equal_epsilon(self.normal(), other.normal(), c_PLANE_NORMAL_EPSILON) - && float_equal_epsilon(self.dist(), other.dist(), c_PLANE_DIST_EPSILON); +inline bool plane3_equal( const Plane3& self, const Plane3& other ){ + return vector3_equal_epsilon( self.normal(), other.normal(), c_PLANE_NORMAL_EPSILON ) + && float_equal_epsilon( self.dist(), other.dist(), c_PLANE_DIST_EPSILON ); } -inline bool plane3_opposing(const Plane3& self, const Plane3& other) -{ - return plane3_equal(self, plane3_flipped(other)); +inline bool plane3_opposing( const Plane3& self, const Plane3& other ){ + return plane3_equal( self, plane3_flipped( other ) ); } -inline bool plane3_valid(const Plane3& self) -{ - return float_equal_epsilon(vector3_dot(self.normal(), self.normal()), 1.0, 0.01); +inline bool plane3_valid( const Plane3& self ){ + return float_equal_epsilon( vector3_dot( self.normal(), self.normal() ), 1.0, 0.01 ); } template -inline Plane3 plane3_for_points(const BasicVector3& p0, const BasicVector3& p1, const BasicVector3& p2) -{ +inline Plane3 plane3_for_points( const BasicVector3& p0, const BasicVector3& p1, const BasicVector3& p2 ){ Plane3 self; - self.normal() = vector3_normalised(vector3_cross(vector3_subtracted(p1, p0), vector3_subtracted(p2, p0))); - self.dist() = vector3_dot(p0, self.normal()); + self.normal() = vector3_normalised( vector3_cross( vector3_subtracted( p1, p0 ), vector3_subtracted( p2, p0 ) ) ); + self.dist() = vector3_dot( p0, self.normal() ); return self; } template -inline Plane3 plane3_for_points(const BasicVector3 planepts[3]) -{ - return plane3_for_points(planepts[2], planepts[1], planepts[0]); +inline Plane3 plane3_for_points( const BasicVector3 planepts[3] ){ + return plane3_for_points( planepts[2], planepts[1], planepts[0] ); } diff --git a/libs/math/quaternion.cpp b/libs/math/quaternion.cpp index 6688368e..5cef646e 100644 --- a/libs/math/quaternion.cpp +++ b/libs/math/quaternion.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "quaternion.h" - diff --git a/libs/math/quaternion.h b/libs/math/quaternion.h index d91ad62a..09520d8b 100644 --- a/libs/math/quaternion.h +++ b/libs/math/quaternion.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_QUATERNION_H) +#if !defined( INCLUDED_MATH_QUATERNION_H ) #define INCLUDED_MATH_QUATERNION_H /// \file @@ -30,297 +30,269 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// \brief A quaternion stored in single-precision floating-point. typedef Vector4 Quaternion; -const Quaternion c_quaternion_identity(0, 0, 0, 1); +const Quaternion c_quaternion_identity( 0, 0, 0, 1 ); -inline Quaternion quaternion_multiplied_by_quaternion(const Quaternion& quaternion, const Quaternion& other) -{ - return Quaternion( - quaternion[3]*other[0] + quaternion[0]*other[3] + quaternion[1]*other[2] - quaternion[2]*other[1], - quaternion[3]*other[1] + quaternion[1]*other[3] + quaternion[2]*other[0] - quaternion[0]*other[2], - quaternion[3]*other[2] + quaternion[2]*other[3] + quaternion[0]*other[1] - quaternion[1]*other[0], - quaternion[3]*other[3] - quaternion[0]*other[0] - quaternion[1]*other[1] - quaternion[2]*other[2] - ); +inline Quaternion quaternion_multiplied_by_quaternion( const Quaternion& quaternion, const Quaternion& other ){ + return Quaternion( + quaternion[3] * other[0] + quaternion[0] * other[3] + quaternion[1] * other[2] - quaternion[2] * other[1], + quaternion[3] * other[1] + quaternion[1] * other[3] + quaternion[2] * other[0] - quaternion[0] * other[2], + quaternion[3] * other[2] + quaternion[2] * other[3] + quaternion[0] * other[1] - quaternion[1] * other[0], + quaternion[3] * other[3] - quaternion[0] * other[0] - quaternion[1] * other[1] - quaternion[2] * other[2] + ); } -inline void quaternion_multiply_by_quaternion(Quaternion& quaternion, const Quaternion& other) -{ - quaternion = quaternion_multiplied_by_quaternion(quaternion, other); +inline void quaternion_multiply_by_quaternion( Quaternion& quaternion, const Quaternion& other ){ + quaternion = quaternion_multiplied_by_quaternion( quaternion, other ); } /// \brief Constructs a quaternion which rotates between two points on the unit-sphere, \p from and \p to. -inline Quaternion quaternion_for_unit_vectors(const Vector3& from, const Vector3& to) -{ - return Quaternion(vector3_cross(from, to), static_cast(vector3_dot(from, to))); +inline Quaternion quaternion_for_unit_vectors( const Vector3& from, const Vector3& to ){ + return Quaternion( vector3_cross( from, to ), static_cast( vector3_dot( from, to ) ) ); } -inline Quaternion quaternion_for_axisangle(const Vector3& axis, double angle) -{ - angle *= 0.5; - float sa = static_cast(sin(angle)); - return Quaternion(axis[0] * sa, axis[1] * sa, axis[2] * sa, static_cast(cos(angle))); +inline Quaternion quaternion_for_axisangle( const Vector3& axis, double angle ){ + angle *= 0.5; + float sa = static_cast( sin( angle ) ); + return Quaternion( axis[0] * sa, axis[1] * sa, axis[2] * sa, static_cast( cos( angle ) ) ); } -inline Quaternion quaternion_for_x(double angle) -{ - angle *= 0.5; - return Quaternion(static_cast(sin(angle)), 0, 0, static_cast(cos(angle))); +inline Quaternion quaternion_for_x( double angle ){ + angle *= 0.5; + return Quaternion( static_cast( sin( angle ) ), 0, 0, static_cast( cos( angle ) ) ); } -inline Quaternion quaternion_for_y(double angle) -{ - angle *= 0.5; - return Quaternion(0, static_cast(sin(angle)), 0, static_cast(cos(angle))); +inline Quaternion quaternion_for_y( double angle ){ + angle *= 0.5; + return Quaternion( 0, static_cast( sin( angle ) ), 0, static_cast( cos( angle ) ) ); } -inline Quaternion quaternion_for_z(double angle) -{ - angle *= 0.5; - return Quaternion(0, 0, static_cast(sin(angle)), static_cast(cos(angle))); +inline Quaternion quaternion_for_z( double angle ){ + angle *= 0.5; + return Quaternion( 0, 0, static_cast( sin( angle ) ), static_cast( cos( angle ) ) ); } -inline Quaternion quaternion_inverse(const Quaternion& quaternion) -{ - return Quaternion(vector3_negated(vector4_to_vector3(quaternion)), quaternion[3]); +inline Quaternion quaternion_inverse( const Quaternion& quaternion ){ + return Quaternion( vector3_negated( vector4_to_vector3( quaternion ) ), quaternion[3] ); } -inline void quaternion_conjugate(Quaternion& quaternion) -{ - quaternion = quaternion_inverse(quaternion); +inline void quaternion_conjugate( Quaternion& quaternion ){ + quaternion = quaternion_inverse( quaternion ); } -inline Quaternion quaternion_normalised(const Quaternion& quaternion) -{ - const double n = (1.0 / (quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] + quaternion[3] * quaternion[3])); - return Quaternion( - static_cast(quaternion[0] * n), - static_cast(quaternion[1] * n), - static_cast(quaternion[2] * n), - static_cast(quaternion[3] * n) - ); +inline Quaternion quaternion_normalised( const Quaternion& quaternion ){ + const double n = ( 1.0 / ( quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] + quaternion[3] * quaternion[3] ) ); + return Quaternion( + static_cast( quaternion[0] * n ), + static_cast( quaternion[1] * n ), + static_cast( quaternion[2] * n ), + static_cast( quaternion[3] * n ) + ); } -inline void quaternion_normalise(Quaternion& quaternion) -{ - quaternion = quaternion_normalised(quaternion); +inline void quaternion_normalise( Quaternion& quaternion ){ + quaternion = quaternion_normalised( quaternion ); } /// \brief Constructs a pure-rotation matrix from \p quaternion. -inline Matrix4 matrix4_rotation_for_quaternion(const Quaternion& quaternion) -{ +inline Matrix4 matrix4_rotation_for_quaternion( const Quaternion& quaternion ){ #if 0 - const double xx = quaternion[0] * quaternion[0]; - const double xy = quaternion[0] * quaternion[1]; - const double xz = quaternion[0] * quaternion[2]; - const double xw = quaternion[0] * quaternion[3]; - - const double yy = quaternion[1] * quaternion[1]; - const double yz = quaternion[1] * quaternion[2]; - const double yw = quaternion[1] * quaternion[3]; - - const double zz = quaternion[2] * quaternion[2]; - const double zw = quaternion[2] * quaternion[3]; - - return Matrix4( - static_cast( 1 - 2 * ( yy + zz ) ), - static_cast( 2 * ( xy + zw ) ), - static_cast( 2 * ( xz - yw ) ), - 0, - static_cast( 2 * ( xy - zw ) ), - static_cast( 1 - 2 * ( xx + zz ) ), - static_cast( 2 * ( yz + xw ) ), - 0, - static_cast( 2 * ( xz + yw ) ), - static_cast( 2 * ( yz - xw ) ), - static_cast( 1 - 2 * ( xx + yy ) ), - 0, - 0, - 0, - 0, - 1 - ); + const double xx = quaternion[0] * quaternion[0]; + const double xy = quaternion[0] * quaternion[1]; + const double xz = quaternion[0] * quaternion[2]; + const double xw = quaternion[0] * quaternion[3]; + + const double yy = quaternion[1] * quaternion[1]; + const double yz = quaternion[1] * quaternion[2]; + const double yw = quaternion[1] * quaternion[3]; + + const double zz = quaternion[2] * quaternion[2]; + const double zw = quaternion[2] * quaternion[3]; + + return Matrix4( + static_cast( 1 - 2 * ( yy + zz ) ), + static_cast( 2 * ( xy + zw ) ), + static_cast( 2 * ( xz - yw ) ), + 0, + static_cast( 2 * ( xy - zw ) ), + static_cast( 1 - 2 * ( xx + zz ) ), + static_cast( 2 * ( yz + xw ) ), + 0, + static_cast( 2 * ( xz + yw ) ), + static_cast( 2 * ( yz - xw ) ), + static_cast( 1 - 2 * ( xx + yy ) ), + 0, + 0, + 0, + 0, + 1 + ); #else - const double x2 = quaternion[0] + quaternion[0]; - const double y2 = quaternion[1] + quaternion[1]; - const double z2 = quaternion[2] + quaternion[2]; - const double xx = quaternion[0] * x2; - const double xy = quaternion[0] * y2; - const double xz = quaternion[0] * z2; - const double yy = quaternion[1] * y2; - const double yz = quaternion[1] * z2; - const double zz = quaternion[2] * z2; - const double wx = quaternion[3] * x2; - const double wy = quaternion[3] * y2; - const double wz = quaternion[3] * z2; - - return Matrix4( - static_cast( 1.0 - (yy + zz) ), - static_cast(xy + wz), - static_cast(xz - wy), - 0, - static_cast(xy - wz), - static_cast( 1.0 - (xx + zz) ), - static_cast(yz + wx), - 0, - static_cast(xz + wy), - static_cast(yz - wx), - static_cast( 1.0 - (xx + yy) ), - 0, - 0, - 0, - 0, - 1 - ); + const double x2 = quaternion[0] + quaternion[0]; + const double y2 = quaternion[1] + quaternion[1]; + const double z2 = quaternion[2] + quaternion[2]; + const double xx = quaternion[0] * x2; + const double xy = quaternion[0] * y2; + const double xz = quaternion[0] * z2; + const double yy = quaternion[1] * y2; + const double yz = quaternion[1] * z2; + const double zz = quaternion[2] * z2; + const double wx = quaternion[3] * x2; + const double wy = quaternion[3] * y2; + const double wz = quaternion[3] * z2; + + return Matrix4( + static_cast( 1.0 - ( yy + zz ) ), + static_cast( xy + wz ), + static_cast( xz - wy ), + 0, + static_cast( xy - wz ), + static_cast( 1.0 - ( xx + zz ) ), + static_cast( yz + wx ), + 0, + static_cast( xz + wy ), + static_cast( yz - wx ), + static_cast( 1.0 - ( xx + yy ) ), + 0, + 0, + 0, + 0, + 1 + ); #endif } const double c_half_sqrt2 = 0.70710678118654752440084436210485; -const float c_half_sqrt2f = static_cast(c_half_sqrt2); +const float c_half_sqrt2f = static_cast( c_half_sqrt2 ); -inline bool quaternion_component_is_90(float component) -{ - return (fabs(component) - c_half_sqrt2) < 0.001; +inline bool quaternion_component_is_90( float component ){ + return ( fabs( component ) - c_half_sqrt2 ) < 0.001; } -inline Matrix4 matrix4_rotation_for_quaternion_quantised(const Quaternion& quaternion) -{ - if(quaternion.y() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90(quaternion.x()) - && quaternion_component_is_90(quaternion.w())) - { - return matrix4_rotation_for_sincos_x((quaternion.x() > 0) ? 1.f : -1.f, 0); - } - - if(quaternion.x() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90(quaternion.y()) - && quaternion_component_is_90(quaternion.w())) - { - return matrix4_rotation_for_sincos_y((quaternion.y() > 0) ? 1.f : -1.f, 0); - } - - if(quaternion.x() == 0 - && quaternion.y() == 0 - && quaternion_component_is_90(quaternion.z()) - && quaternion_component_is_90(quaternion.w())) - { - return matrix4_rotation_for_sincos_z((quaternion.z() > 0) ? 1.f : -1.f, 0); - } - - return matrix4_rotation_for_quaternion(quaternion); +inline Matrix4 matrix4_rotation_for_quaternion_quantised( const Quaternion& quaternion ){ + if ( quaternion.y() == 0 + && quaternion.z() == 0 + && quaternion_component_is_90( quaternion.x() ) + && quaternion_component_is_90( quaternion.w() ) ) { + return matrix4_rotation_for_sincos_x( ( quaternion.x() > 0 ) ? 1.f : -1.f, 0 ); + } + + if ( quaternion.x() == 0 + && quaternion.z() == 0 + && quaternion_component_is_90( quaternion.y() ) + && quaternion_component_is_90( quaternion.w() ) ) { + return matrix4_rotation_for_sincos_y( ( quaternion.y() > 0 ) ? 1.f : -1.f, 0 ); + } + + if ( quaternion.x() == 0 + && quaternion.y() == 0 + && quaternion_component_is_90( quaternion.z() ) + && quaternion_component_is_90( quaternion.w() ) ) { + return matrix4_rotation_for_sincos_z( ( quaternion.z() > 0 ) ? 1.f : -1.f, 0 ); + } + + return matrix4_rotation_for_quaternion( quaternion ); } -inline Quaternion quaternion_for_matrix4_rotation(const Matrix4& matrix4) -{ - Matrix4 transposed = matrix4_transposed(matrix4); - - double trace = transposed[0] + transposed[5] + transposed[10] + 1.0; - - if(trace > 0.0001) - { - double S = 0.5 / sqrt(trace); - return Quaternion( - static_cast((transposed[9] - transposed[6]) * S), - static_cast((transposed[2] - transposed[8]) * S), - static_cast((transposed[4] - transposed[1]) * S), - static_cast(0.25 / S) - ); - } - - if(transposed[0] >= transposed[5] && transposed[0] >= transposed[10]) - { - double S = 2.0 * sqrt(1.0 + transposed[0] - transposed[5] - transposed[10]); - return Quaternion( - static_cast(0.25 / S), - static_cast((transposed[1] + transposed[4]) / S), - static_cast((transposed[2] + transposed[8]) / S), - static_cast((transposed[6] + transposed[9]) / S) - ); - } - - if(transposed[5] >= transposed[0] && transposed[5] >= transposed[10]) - { - double S = 2.0 * sqrt(1.0 + transposed[5] - transposed[0] - transposed[10]); - return Quaternion( - static_cast((transposed[1] + transposed[4]) / S), - static_cast(0.25 / S), - static_cast((transposed[6] + transposed[9]) / S), - static_cast((transposed[2] + transposed[8]) / S) - ); - } - - double S = 2.0 * sqrt(1.0 + transposed[10] - transposed[0] - transposed[5]); - return Quaternion( - static_cast((transposed[2] + transposed[8]) / S), - static_cast((transposed[6] + transposed[9]) / S), - static_cast(0.25 / S), - static_cast((transposed[1] + transposed[4]) / S) - ); +inline Quaternion quaternion_for_matrix4_rotation( const Matrix4& matrix4 ){ + Matrix4 transposed = matrix4_transposed( matrix4 ); + + double trace = transposed[0] + transposed[5] + transposed[10] + 1.0; + + if ( trace > 0.0001 ) { + double S = 0.5 / sqrt( trace ); + return Quaternion( + static_cast( ( transposed[9] - transposed[6] ) * S ), + static_cast( ( transposed[2] - transposed[8] ) * S ), + static_cast( ( transposed[4] - transposed[1] ) * S ), + static_cast( 0.25 / S ) + ); + } + + if ( transposed[0] >= transposed[5] && transposed[0] >= transposed[10] ) { + double S = 2.0 * sqrt( 1.0 + transposed[0] - transposed[5] - transposed[10] ); + return Quaternion( + static_cast( 0.25 / S ), + static_cast( ( transposed[1] + transposed[4] ) / S ), + static_cast( ( transposed[2] + transposed[8] ) / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ) + ); + } + + if ( transposed[5] >= transposed[0] && transposed[5] >= transposed[10] ) { + double S = 2.0 * sqrt( 1.0 + transposed[5] - transposed[0] - transposed[10] ); + return Quaternion( + static_cast( ( transposed[1] + transposed[4] ) / S ), + static_cast( 0.25 / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ), + static_cast( ( transposed[2] + transposed[8] ) / S ) + ); + } + + double S = 2.0 * sqrt( 1.0 + transposed[10] - transposed[0] - transposed[5] ); + return Quaternion( + static_cast( ( transposed[2] + transposed[8] ) / S ), + static_cast( ( transposed[6] + transposed[9] ) / S ), + static_cast( 0.25 / S ), + static_cast( ( transposed[1] + transposed[4] ) / S ) + ); } /// \brief Returns \p self concatenated with the rotation transform produced by \p rotation. /// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_quaternion(const Matrix4& self, const Quaternion& rotation) -{ - return matrix4_multiplied_by_matrix4(self, matrix4_rotation_for_quaternion(rotation)); +inline Matrix4 matrix4_rotated_by_quaternion( const Matrix4& self, const Quaternion& rotation ){ + return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_quaternion( rotation ) ); } /// \brief Concatenates \p self with the rotation transform produced by \p rotation. /// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_quaternion(Matrix4& self, const Quaternion& rotation) -{ - self = matrix4_rotated_by_quaternion(self, rotation); +inline void matrix4_rotate_by_quaternion( Matrix4& self, const Quaternion& rotation ){ + self = matrix4_rotated_by_quaternion( self, rotation ); } /// \brief Rotates \p self by \p rotation, using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_quaternion(Matrix4& self, const Quaternion& rotation, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(self, pivotpoint); - matrix4_rotate_by_quaternion(self, rotation); - matrix4_translate_by_vec3(self, vector3_negated(pivotpoint)); +inline void matrix4_pivoted_rotate_by_quaternion( Matrix4& self, const Quaternion& rotation, const Vector3& pivotpoint ){ + matrix4_translate_by_vec3( self, pivotpoint ); + matrix4_rotate_by_quaternion( self, rotation ); + matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); } -inline Vector3 quaternion_transformed_point(const Quaternion& quaternion, const Vector3& point) -{ - double xx = quaternion.x() * quaternion.x(); - double yy = quaternion.y() * quaternion.y(); - double zz = quaternion.z() * quaternion.z(); - double ww = quaternion.w() * quaternion.w(); +inline Vector3 quaternion_transformed_point( const Quaternion& quaternion, const Vector3& point ){ + double xx = quaternion.x() * quaternion.x(); + double yy = quaternion.y() * quaternion.y(); + double zz = quaternion.z() * quaternion.z(); + double ww = quaternion.w() * quaternion.w(); - double xy2 = quaternion.x() * quaternion.y() * 2; - double xz2 = quaternion.x() * quaternion.z() * 2; - double xw2 = quaternion.x() * quaternion.w() * 2; - double yz2 = quaternion.y() * quaternion.z() * 2; - double yw2 = quaternion.y() * quaternion.w() * 2; - double zw2 = quaternion.z() * quaternion.w() * 2; + double xy2 = quaternion.x() * quaternion.y() * 2; + double xz2 = quaternion.x() * quaternion.z() * 2; + double xw2 = quaternion.x() * quaternion.w() * 2; + double yz2 = quaternion.y() * quaternion.z() * 2; + double yw2 = quaternion.y() * quaternion.w() * 2; + double zw2 = quaternion.z() * quaternion.w() * 2; return Vector3( - static_cast(ww * point.x() + yw2 * point.z() - zw2 * point.y() + xx * point.x() + xy2 * point.y() + xz2 * point.z() - zz * point.x() - yy * point.x()), - static_cast(xy2 * point.x() + yy * point.y() + yz2 * point.z() + zw2 * point.x() - zz * point.y() + ww * point.y() - xw2 * point.z() - xx * point.y()), - static_cast(xz2 * point.x() + yz2 * point.y() + zz * point.z() - yw2 * point.x() - yy * point.z() + xw2 * point.y() - xx * point.z() + ww * point.z()) - ); + static_cast( ww * point.x() + yw2 * point.z() - zw2 * point.y() + xx * point.x() + xy2 * point.y() + xz2 * point.z() - zz * point.x() - yy * point.x() ), + static_cast( xy2 * point.x() + yy * point.y() + yz2 * point.z() + zw2 * point.x() - zz * point.y() + ww * point.y() - xw2 * point.z() - xx * point.y() ), + static_cast( xz2 * point.x() + yz2 * point.y() + zz * point.z() - yw2 * point.x() - yy * point.z() + xw2 * point.y() - xx * point.z() + ww * point.z() ) + ); } /// \brief Constructs a pure-rotation transform from \p axis and \p angle (radians). -inline Matrix4 matrix4_rotation_for_axisangle(const Vector3& axis, double angle) -{ - return matrix4_rotation_for_quaternion(quaternion_for_axisangle(axis, angle)); +inline Matrix4 matrix4_rotation_for_axisangle( const Vector3& axis, double angle ){ + return matrix4_rotation_for_quaternion( quaternion_for_axisangle( axis, angle ) ); } /// \brief Rotates \p self about \p axis by \p angle. -inline void matrix4_rotate_by_axisangle(Matrix4& self, const Vector3& axis, double angle) -{ - matrix4_multiply_by_matrix4(self, matrix4_rotation_for_axisangle(axis, angle)); +inline void matrix4_rotate_by_axisangle( Matrix4& self, const Vector3& axis, double angle ){ + matrix4_multiply_by_matrix4( self, matrix4_rotation_for_axisangle( axis, angle ) ); } /// \brief Rotates \p self about \p axis by \p angle using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_axisangle(Matrix4& self, const Vector3& axis, double angle, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(self, pivotpoint); - matrix4_rotate_by_axisangle(self, axis, angle); - matrix4_translate_by_vec3(self, vector3_negated(pivotpoint)); +inline void matrix4_pivoted_rotate_by_axisangle( Matrix4& self, const Vector3& axis, double angle, const Vector3& pivotpoint ){ + matrix4_translate_by_vec3( self, pivotpoint ); + matrix4_rotate_by_axisangle( self, axis, angle ); + matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); } diff --git a/libs/math/vector.cpp b/libs/math/vector.cpp index d72bd9e4..4893324e 100644 --- a/libs/math/vector.cpp +++ b/libs/math/vector.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "vector.h" - diff --git a/libs/math/vector.h b/libs/math/vector.h index 075c58fe..9ec5159f 100644 --- a/libs/math/vector.h +++ b/libs/math/vector.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MATH_VECTOR_H) +#if !defined( INCLUDED_MATH_VECTOR_H ) #define INCLUDED_MATH_VECTOR_H /// \file @@ -27,46 +27,42 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "generic/vector.h" -#if defined (_MSC_VER) +#if defined ( _MSC_VER ) -inline int lrint (double flt) -{ - int i; +inline int lrint( double flt ){ + int i; _asm { - fld flt + fld flt fistp i - }; - + }; + return i; -} +} -inline __int64 llrint(double f) -{ - return static_cast<__int64>(f + 0.5); +inline __int64 llrint( double f ){ + return static_cast<__int64>( f + 0.5 ); } -#elif defined(__FreeBSD__) +#elif defined( __FreeBSD__ ) -inline long lrint(double f) -{ - return static_cast(f + 0.5); +inline long lrint( double f ){ + return static_cast( f + 0.5 ); } -inline long long llrint(double f) -{ - return static_cast(f + 0.5); +inline long long llrint( double f ){ + return static_cast( f + 0.5 ); } -#elif defined(__GNUC__) +#elif defined( __GNUC__ ) - // lrint is part of ISO C99 -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 +// lrint is part of ISO C99 +#define _ISOC9X_SOURCE 1 +#define _ISOC99_SOURCE 1 -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 +#define __USE_ISOC9X 1 +#define __USE_ISOC99 1 #else #error "unsupported platform" @@ -81,733 +77,628 @@ inline long long llrint(double f) /// \brief Returns true if \p self is equal to other \p other within \p epsilon. template -inline bool float_equal_epsilon(const Element& self, const OtherElement& other, const Element& epsilon) -{ - return fabs(other - self) < epsilon; +inline bool float_equal_epsilon( const Element& self, const OtherElement& other, const Element& epsilon ){ + return fabs( other - self ) < epsilon; } /// \brief Returns the value midway between \p self and \p other. template -inline Element float_mid(const Element& self, const Element& other) -{ - return Element((self + other) * 0.5); +inline Element float_mid( const Element& self, const Element& other ){ + return Element( ( self + other ) * 0.5 ); } /// \brief Returns \p f rounded to the nearest integer. Note that this is not the same behaviour as casting from float to int. template -inline int float_to_integer(const Element& f) -{ - return lrint(f); +inline int float_to_integer( const Element& f ){ + return lrint( f ); } /// \brief Returns \p f rounded to the nearest multiple of \p snap. template -inline Element float_snapped(const Element& f, const OtherElement& snap) -{ - //return Element(float_to_integer(f / snap) * snap); - if(snap == 0) - return f; - return Element(llrint(f / snap) * snap); // llrint has more significant bits +inline Element float_snapped( const Element& f, const OtherElement& snap ){ + //return Element(float_to_integer(f / snap) * snap); + if ( snap == 0 ) { + return f; + } + return Element( llrint( f / snap ) * snap ); // llrint has more significant bits } /// \brief Returns true if \p f has no decimal fraction part. template -inline bool float_is_integer(const Element& f) -{ - return f == Element(float_to_integer(f)); +inline bool float_is_integer( const Element& f ){ + return f == Element( float_to_integer( f ) ); } /// \brief Returns \p self modulated by the range [0, \p modulus) /// \p self must be in the range [\p -modulus, \p modulus) template -inline Element float_mod_range(const Element& self, const ModulusElement& modulus) -{ - return Element((self < 0.0) ? self + modulus : self); +inline Element float_mod_range( const Element& self, const ModulusElement& modulus ){ + return Element( ( self < 0.0 ) ? self + modulus : self ); } /// \brief Returns \p self modulated by the range [0, \p modulus) template -inline Element float_mod(const Element& self, const ModulusElement& modulus) -{ - return float_mod_range(Element(fmod(static_cast(self), static_cast(modulus))), modulus); +inline Element float_mod( const Element& self, const ModulusElement& modulus ){ + return float_mod_range( Element( fmod( static_cast( self ), static_cast( modulus ) ) ), modulus ); } template -inline BasicVector2 vector2_added(const BasicVector2& self, const BasicVector2& other) -{ - return BasicVector2( - Element(self.x() + other.x()), - Element(self.y() + other.y()) - ); +inline BasicVector2 vector2_added( const BasicVector2& self, const BasicVector2& other ){ + return BasicVector2( + Element( self.x() + other.x() ), + Element( self.y() + other.y() ) + ); } template -inline BasicVector2 operator+(const BasicVector2& self, const BasicVector2& other) -{ - return vector2_added(self, other); +inline BasicVector2 operator+( const BasicVector2& self, const BasicVector2& other ){ + return vector2_added( self, other ); } template -inline void vector2_add(BasicVector2& self, const BasicVector2& other) -{ - self.x() += Element(other.x()); - self.y() += Element(other.y()); +inline void vector2_add( BasicVector2& self, const BasicVector2& other ){ + self.x() += Element( other.x() ); + self.y() += Element( other.y() ); } template -inline void operator+=(BasicVector2& self, const BasicVector2& other) -{ - vector2_add(self, other); +inline void operator+=( BasicVector2& self, const BasicVector2& other ){ + vector2_add( self, other ); } template -inline BasicVector2 vector2_subtracted(const BasicVector2& self, const BasicVector2& other) -{ - return BasicVector2( - Element(self.x() - other.x()), - Element(self.y() - other.y()) - ); +inline BasicVector2 vector2_subtracted( const BasicVector2& self, const BasicVector2& other ){ + return BasicVector2( + Element( self.x() - other.x() ), + Element( self.y() - other.y() ) + ); } template -inline BasicVector2 operator-(const BasicVector2& self, const BasicVector2& other) -{ - return vector2_subtracted(self, other); +inline BasicVector2 operator-( const BasicVector2& self, const BasicVector2& other ){ + return vector2_subtracted( self, other ); } template -inline void vector2_subtract(BasicVector2& self, const BasicVector2& other) -{ - self.x() -= Element(other.x()); - self.y() -= lement(other.y()); +inline void vector2_subtract( BasicVector2& self, const BasicVector2& other ){ + self.x() -= Element( other.x() ); + self.y() -= lement( other.y() ); } template -inline void operator-=(BasicVector2& self, const BasicVector2& other) -{ - vector2_subtract(self, other); +inline void operator-=( BasicVector2& self, const BasicVector2& other ){ + vector2_subtract( self, other ); } template -inline BasicVector2 vector2_scaled(const BasicVector2& self, OtherElement other) -{ - return BasicVector2( - Element(self.x() * other), - Element(self.y() * other) - ); +inline BasicVector2 vector2_scaled( const BasicVector2& self, OtherElement other ){ + return BasicVector2( + Element( self.x() * other ), + Element( self.y() * other ) + ); } template -inline BasicVector2 operator*(const BasicVector2& self, OtherElement other) -{ - return vector2_scaled(self, other); +inline BasicVector2 operator*( const BasicVector2& self, OtherElement other ){ + return vector2_scaled( self, other ); } template -inline void vector2_scale(BasicVector2& self, OtherElement other) -{ - self.x() *= Element(other); - self.y() *= Element(other); +inline void vector2_scale( BasicVector2& self, OtherElement other ){ + self.x() *= Element( other ); + self.y() *= Element( other ); } template -inline void operator*=(BasicVector2& self, OtherElement other) -{ - vector2_scale(self, other); +inline void operator*=( BasicVector2& self, OtherElement other ){ + vector2_scale( self, other ); } template -inline BasicVector2 vector2_scaled(const BasicVector2& self, const BasicVector2& other) -{ - return BasicVector2( - Element(self.x() * other.x()), - Element(self.y() * other.y()) - ); +inline BasicVector2 vector2_scaled( const BasicVector2& self, const BasicVector2& other ){ + return BasicVector2( + Element( self.x() * other.x() ), + Element( self.y() * other.y() ) + ); } template -inline BasicVector2 operator*(const BasicVector2& self, const BasicVector2& other) -{ - return vector2_scaled(self, other); +inline BasicVector2 operator*( const BasicVector2& self, const BasicVector2& other ){ + return vector2_scaled( self, other ); } template -inline void vector2_scale(BasicVector2& self, const BasicVector2& other) -{ - self.x() *= Element(other.x()); - self.y() *= Element(other.y()); +inline void vector2_scale( BasicVector2& self, const BasicVector2& other ){ + self.x() *= Element( other.x() ); + self.y() *= Element( other.y() ); } template -inline void operator*=(BasicVector2& self, const BasicVector2& other) -{ - vector2_scale(self, other); +inline void operator*=( BasicVector2& self, const BasicVector2& other ){ + vector2_scale( self, other ); } template -inline BasicVector2 vector2_divided(const BasicVector2& self, const BasicVector2& other) -{ - return BasicVector2( - Element(self.x() / other.x()), - Element(self.y() / other.y()) - ); +inline BasicVector2 vector2_divided( const BasicVector2& self, const BasicVector2& other ){ + return BasicVector2( + Element( self.x() / other.x() ), + Element( self.y() / other.y() ) + ); } template -inline BasicVector2 operator/(const BasicVector2& self, const BasicVector2& other) -{ - return vector2_divided(self, other); +inline BasicVector2 operator/( const BasicVector2& self, const BasicVector2& other ){ + return vector2_divided( self, other ); } template -inline void vector2_divide(BasicVector2& self, const BasicVector2& other) -{ - self.x() /= Element(other.x()); - self.y() /= Element(other.y()); +inline void vector2_divide( BasicVector2& self, const BasicVector2& other ){ + self.x() /= Element( other.x() ); + self.y() /= Element( other.y() ); } template -inline void operator/=(BasicVector2& self, const BasicVector2& other) -{ - vector2_divide(self, other); +inline void operator/=( BasicVector2& self, const BasicVector2& other ){ + vector2_divide( self, other ); } template -inline BasicVector2 vector2_divided(const BasicVector2& self, OtherElement other) -{ - return BasicVector2( - Element(self.x() / other), - Element(self.y() / other) - ); +inline BasicVector2 vector2_divided( const BasicVector2& self, OtherElement other ){ + return BasicVector2( + Element( self.x() / other ), + Element( self.y() / other ) + ); } template -inline BasicVector2 operator/(const BasicVector2& self, OtherElement other) -{ - return vector2_divided(self, other); +inline BasicVector2 operator/( const BasicVector2& self, OtherElement other ){ + return vector2_divided( self, other ); } template -inline void vector2_divide(BasicVector2& self, OtherElement other) -{ - self.x() /= Element(other); - self.y() /= Element(other); +inline void vector2_divide( BasicVector2& self, OtherElement other ){ + self.x() /= Element( other ); + self.y() /= Element( other ); } template -inline void operator/=(BasicVector2& self, OtherElement other) -{ - vector2_divide(self, other); +inline void operator/=( BasicVector2& self, OtherElement other ){ + vector2_divide( self, other ); } template -inline double vector2_dot(const BasicVector2& self, const BasicVector2& other) -{ - return self.x() * other.x() + self.y() * other.y(); +inline double vector2_dot( const BasicVector2& self, const BasicVector2& other ){ + return self.x() * other.x() + self.y() * other.y(); } template -inline double vector2_length_squared(const BasicVector2& self) -{ - return vector2_dot(self, self); +inline double vector2_length_squared( const BasicVector2& self ){ + return vector2_dot( self, self ); } template -inline double vector2_length(const BasicVector2& self) -{ - return sqrt(vector2_length_squared(self)); +inline double vector2_length( const BasicVector2& self ){ + return sqrt( vector2_length_squared( self ) ); } template -inline double vector2_cross(const BasicVector2& self, const BasicVector2& other) -{ - return self.x() * other.y() - self.y() * other.x(); +inline double vector2_cross( const BasicVector2& self, const BasicVector2& other ){ + return self.x() * other.y() - self.y() * other.x(); } -const Vector3 g_vector3_identity(0, 0, 0); -const Vector3 g_vector3_max = Vector3(FLT_MAX, FLT_MAX, FLT_MAX); -const Vector3 g_vector3_axis_x(1, 0, 0); -const Vector3 g_vector3_axis_y(0, 1, 0); -const Vector3 g_vector3_axis_z(0, 0, 1); +const Vector3 g_vector3_identity( 0, 0, 0 ); +const Vector3 g_vector3_max = Vector3( FLT_MAX, FLT_MAX, FLT_MAX ); +const Vector3 g_vector3_axis_x( 1, 0, 0 ); +const Vector3 g_vector3_axis_y( 0, 1, 0 ); +const Vector3 g_vector3_axis_z( 0, 0, 1 ); const Vector3 g_vector3_axes[3] = { g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z }; template -inline void vector3_swap(BasicVector3& self, BasicVector3& other) -{ - std::swap(self.x(), other.x()); - std::swap(self.y(), other.y()); - std::swap(self.z(), other.z()); +inline void vector3_swap( BasicVector3& self, BasicVector3& other ){ + std::swap( self.x(), other.x() ); + std::swap( self.y(), other.y() ); + std::swap( self.z(), other.z() ); } template -inline bool vector3_equal(const BasicVector3& self, const BasicVector3& other) -{ - return self.x() == other.x() && self.y() == other.y() && self.z() == other.z(); +inline bool vector3_equal( const BasicVector3& self, const BasicVector3& other ){ + return self.x() == other.x() && self.y() == other.y() && self.z() == other.z(); } template -inline bool operator==(const BasicVector3& self, const BasicVector3& other) -{ - return vector3_equal(self, other); +inline bool operator==( const BasicVector3& self, const BasicVector3& other ){ + return vector3_equal( self, other ); } template -inline bool operator!=(const BasicVector3& self, const BasicVector3& other) -{ - return !vector3_equal(self, other); +inline bool operator!=( const BasicVector3& self, const BasicVector3& other ){ + return !vector3_equal( self, other ); } template -inline bool vector3_equal_epsilon(const BasicVector3& self, const BasicVector3& other, Epsilon epsilon) -{ - return float_equal_epsilon(self.x(), other.x(), epsilon) - && float_equal_epsilon(self.y(), other.y(), epsilon) - && float_equal_epsilon(self.z(), other.z(), epsilon); +inline bool vector3_equal_epsilon( const BasicVector3& self, const BasicVector3& other, Epsilon epsilon ){ + return float_equal_epsilon( self.x(), other.x(), epsilon ) + && float_equal_epsilon( self.y(), other.y(), epsilon ) + && float_equal_epsilon( self.z(), other.z(), epsilon ); } template -inline BasicVector3 vector3_added(const BasicVector3& self, const BasicVector3& other) -{ - return BasicVector3( - Element(self.x() + other.x()), - Element(self.y() + other.y()), - Element(self.z() + other.z()) - ); +inline BasicVector3 vector3_added( const BasicVector3& self, const BasicVector3& other ){ + return BasicVector3( + Element( self.x() + other.x() ), + Element( self.y() + other.y() ), + Element( self.z() + other.z() ) + ); } template -inline BasicVector3 operator+(const BasicVector3& self, const BasicVector3& other) -{ - return vector3_added(self, other); +inline BasicVector3 operator+( const BasicVector3& self, const BasicVector3& other ){ + return vector3_added( self, other ); } template -inline void vector3_add(BasicVector3& self, const BasicVector3& other) -{ - self.x() += static_cast(other.x()); - self.y() += static_cast(other.y()); - self.z() += static_cast(other.z()); +inline void vector3_add( BasicVector3& self, const BasicVector3& other ){ + self.x() += static_cast( other.x() ); + self.y() += static_cast( other.y() ); + self.z() += static_cast( other.z() ); } template -inline void operator+=(BasicVector3& self, const BasicVector3& other) -{ - vector3_add(self, other); +inline void operator+=( BasicVector3& self, const BasicVector3& other ){ + vector3_add( self, other ); } template -inline BasicVector3 vector3_subtracted(const BasicVector3& self, const BasicVector3& other) -{ - return BasicVector3( - Element(self.x() - other.x()), - Element(self.y() - other.y()), - Element(self.z() - other.z()) - ); +inline BasicVector3 vector3_subtracted( const BasicVector3& self, const BasicVector3& other ){ + return BasicVector3( + Element( self.x() - other.x() ), + Element( self.y() - other.y() ), + Element( self.z() - other.z() ) + ); } template -inline BasicVector3 operator-(const BasicVector3& self, const BasicVector3& other) -{ - return vector3_subtracted(self, other); +inline BasicVector3 operator-( const BasicVector3& self, const BasicVector3& other ){ + return vector3_subtracted( self, other ); } template -inline void vector3_subtract(BasicVector3& self, const BasicVector3& other) -{ - self.x() -= static_cast(other.x()); - self.y() -= static_cast(other.y()); - self.z() -= static_cast(other.z()); +inline void vector3_subtract( BasicVector3& self, const BasicVector3& other ){ + self.x() -= static_cast( other.x() ); + self.y() -= static_cast( other.y() ); + self.z() -= static_cast( other.z() ); } template -inline void operator-=(BasicVector3& self, const BasicVector3& other) -{ - vector3_subtract(self, other); +inline void operator-=( BasicVector3& self, const BasicVector3& other ){ + vector3_subtract( self, other ); } template -inline BasicVector3 vector3_scaled(const BasicVector3& self, const BasicVector3& other) -{ - return BasicVector3( - Element(self.x() * other.x()), - Element(self.y() * other.y()), - Element(self.z() * other.z()) - ); +inline BasicVector3 vector3_scaled( const BasicVector3& self, const BasicVector3& other ){ + return BasicVector3( + Element( self.x() * other.x() ), + Element( self.y() * other.y() ), + Element( self.z() * other.z() ) + ); } template -inline BasicVector3 operator*(const BasicVector3& self, const BasicVector3& other) -{ - return vector3_scaled(self, other); +inline BasicVector3 operator*( const BasicVector3& self, const BasicVector3& other ){ + return vector3_scaled( self, other ); } template -inline void vector3_scale(BasicVector3& self, const BasicVector3& other) -{ - self.x() *= static_cast(other.x()); - self.y() *= static_cast(other.y()); - self.z() *= static_cast(other.z()); +inline void vector3_scale( BasicVector3& self, const BasicVector3& other ){ + self.x() *= static_cast( other.x() ); + self.y() *= static_cast( other.y() ); + self.z() *= static_cast( other.z() ); } template -inline void operator*=(BasicVector3& self, const BasicVector3& other) -{ - vector3_scale(self, other); +inline void operator*=( BasicVector3& self, const BasicVector3& other ){ + vector3_scale( self, other ); } template -inline BasicVector3 vector3_scaled(const BasicVector3& self, const OtherElement& scale) -{ - return BasicVector3( - Element(self.x() * scale), - Element(self.y() * scale), - Element(self.z() * scale) - ); +inline BasicVector3 vector3_scaled( const BasicVector3& self, const OtherElement& scale ){ + return BasicVector3( + Element( self.x() * scale ), + Element( self.y() * scale ), + Element( self.z() * scale ) + ); } template -inline BasicVector3 operator*(const BasicVector3& self, const OtherElement& scale) -{ - return vector3_scaled(self, scale); +inline BasicVector3 operator*( const BasicVector3& self, const OtherElement& scale ){ + return vector3_scaled( self, scale ); } template -inline void vector3_scale(BasicVector3& self, const OtherElement& scale) -{ - self.x() *= static_cast(scale); - self.y() *= static_cast(scale); - self.z() *= static_cast(scale); +inline void vector3_scale( BasicVector3& self, const OtherElement& scale ){ + self.x() *= static_cast( scale ); + self.y() *= static_cast( scale ); + self.z() *= static_cast( scale ); } template -inline void operator*=(BasicVector3& self, const OtherElement& scale) -{ - vector3_scale(self, scale); +inline void operator*=( BasicVector3& self, const OtherElement& scale ){ + vector3_scale( self, scale ); } template -inline BasicVector3 vector3_divided(const BasicVector3& self, const BasicVector3& other) -{ - return BasicVector3( - Element(self.x() / other.x()), - Element(self.y() / other.y()), - Element(self.z() / other.z()) - ); +inline BasicVector3 vector3_divided( const BasicVector3& self, const BasicVector3& other ){ + return BasicVector3( + Element( self.x() / other.x() ), + Element( self.y() / other.y() ), + Element( self.z() / other.z() ) + ); } template -inline BasicVector3 operator/(const BasicVector3& self, const BasicVector3& other) -{ - return vector3_divided(self, other); +inline BasicVector3 operator/( const BasicVector3& self, const BasicVector3& other ){ + return vector3_divided( self, other ); } template -inline void vector3_divide(BasicVector3& self, const BasicVector3& other) -{ - self.x() /= static_cast(other.x()); - self.y() /= static_cast(other.y()); - self.z() /= static_cast(other.z()); +inline void vector3_divide( BasicVector3& self, const BasicVector3& other ){ + self.x() /= static_cast( other.x() ); + self.y() /= static_cast( other.y() ); + self.z() /= static_cast( other.z() ); } template -inline void operator/=(BasicVector3& self, const BasicVector3& other) -{ - vector3_divide(self, other); +inline void operator/=( BasicVector3& self, const BasicVector3& other ){ + vector3_divide( self, other ); } template -inline BasicVector3 vector3_divided(const BasicVector3& self, const OtherElement& divisor) -{ - return BasicVector3( - Element(self.x() / divisor), - Element(self.y() / divisor), - Element(self.z() / divisor) - ); +inline BasicVector3 vector3_divided( const BasicVector3& self, const OtherElement& divisor ){ + return BasicVector3( + Element( self.x() / divisor ), + Element( self.y() / divisor ), + Element( self.z() / divisor ) + ); } template -inline BasicVector3 operator/(const BasicVector3& self, const OtherElement& divisor) -{ - return vector3_divided(self, divisor); +inline BasicVector3 operator/( const BasicVector3& self, const OtherElement& divisor ){ + return vector3_divided( self, divisor ); } template -inline void vector3_divide(BasicVector3& self, const OtherElement& divisor) -{ - self.x() /= static_cast(divisor); - self.y() /= static_cast(divisor); - self.z() /= static_cast(divisor); +inline void vector3_divide( BasicVector3& self, const OtherElement& divisor ){ + self.x() /= static_cast( divisor ); + self.y() /= static_cast( divisor ); + self.z() /= static_cast( divisor ); } template -inline void operator/=(BasicVector3& self, const OtherElement& divisor) -{ - vector3_divide(self, divisor); +inline void operator/=( BasicVector3& self, const OtherElement& divisor ){ + vector3_divide( self, divisor ); } template -inline double vector3_dot(const BasicVector3& self, const BasicVector3& other) -{ - return self.x() * other.x() + self.y() * other.y() + self.z() * other.z(); +inline double vector3_dot( const BasicVector3& self, const BasicVector3& other ){ + return self.x() * other.x() + self.y() * other.y() + self.z() * other.z(); } template -inline BasicVector3 vector3_mid(const BasicVector3& begin, const BasicVector3& end) -{ - return vector3_scaled(vector3_added(begin, end), 0.5); +inline BasicVector3 vector3_mid( const BasicVector3& begin, const BasicVector3& end ){ + return vector3_scaled( vector3_added( begin, end ), 0.5 ); } template -inline BasicVector3 vector3_cross(const BasicVector3& self, const BasicVector3& other) -{ - return BasicVector3( - Element(self.y() * other.z() - self.z() * other.y()), - Element(self.z() * other.x() - self.x() * other.z()), - Element(self.x() * other.y() - self.y() * other.x()) - ); +inline BasicVector3 vector3_cross( const BasicVector3& self, const BasicVector3& other ){ + return BasicVector3( + Element( self.y() * other.z() - self.z() * other.y() ), + Element( self.z() * other.x() - self.x() * other.z() ), + Element( self.x() * other.y() - self.y() * other.x() ) + ); } template -inline BasicVector3 vector3_negated(const BasicVector3& self) -{ - return BasicVector3(-self.x(), -self.y(), -self.z()); +inline BasicVector3 vector3_negated( const BasicVector3& self ){ + return BasicVector3( -self.x(), -self.y(), -self.z() ); } template -inline BasicVector3 operator-(const BasicVector3& self) -{ - return vector3_negated(self); +inline BasicVector3 operator-( const BasicVector3& self ){ + return vector3_negated( self ); } template -inline void vector3_negate(BasicVector3& self) -{ - self = vector3_negated(self); +inline void vector3_negate( BasicVector3& self ){ + self = vector3_negated( self ); } template -inline double vector3_length_squared(const BasicVector3& self) -{ - return vector3_dot(self, self); +inline double vector3_length_squared( const BasicVector3& self ){ + return vector3_dot( self, self ); } template -inline double vector3_length(const BasicVector3& self) -{ - return sqrt(vector3_length_squared(self)); +inline double vector3_length( const BasicVector3& self ){ + return sqrt( vector3_length_squared( self ) ); } template -inline Element float_divided(Element f, Element other) -{ - //ASSERT_MESSAGE(other != 0, "float_divided: invalid divisor"); - return f / other; +inline Element float_divided( Element f, Element other ){ + //ASSERT_MESSAGE(other != 0, "float_divided: invalid divisor"); + return f / other; } template -inline BasicVector3 vector3_normalised(const BasicVector3& self) -{ - return vector3_scaled(self, float_divided(1.0, vector3_length(self))); +inline BasicVector3 vector3_normalised( const BasicVector3& self ){ + return vector3_scaled( self, float_divided( 1.0, vector3_length( self ) ) ); } template -inline void vector3_normalise(BasicVector3& self) -{ - self = vector3_normalised(self); +inline void vector3_normalise( BasicVector3& self ){ + self = vector3_normalised( self ); } template -inline BasicVector3 vector3_snapped(const BasicVector3& self) -{ - return BasicVector3( - Element(float_to_integer(self.x())), - Element(float_to_integer(self.y())), - Element(float_to_integer(self.z())) - ); +inline BasicVector3 vector3_snapped( const BasicVector3& self ){ + return BasicVector3( + Element( float_to_integer( self.x() ) ), + Element( float_to_integer( self.y() ) ), + Element( float_to_integer( self.z() ) ) + ); } template -inline void vector3_snap(BasicVector3& self) -{ - self = vector3_snapped(self); +inline void vector3_snap( BasicVector3& self ){ + self = vector3_snapped( self ); } template -inline BasicVector3 vector3_snapped(const BasicVector3& self, const OtherElement& snap) -{ - return BasicVector3( - Element(float_snapped(self.x(), snap)), - Element(float_snapped(self.y(), snap)), - Element(float_snapped(self.z(), snap)) - ); +inline BasicVector3 vector3_snapped( const BasicVector3& self, const OtherElement& snap ){ + return BasicVector3( + Element( float_snapped( self.x(), snap ) ), + Element( float_snapped( self.y(), snap ) ), + Element( float_snapped( self.z(), snap ) ) + ); } template -inline void vector3_snap(BasicVector3& self, const OtherElement& snap) -{ - self = vector3_snapped(self, snap); +inline void vector3_snap( BasicVector3& self, const OtherElement& snap ){ + self = vector3_snapped( self, snap ); } -inline Vector3 vector3_for_spherical(double theta, double phi) -{ - return Vector3( - static_cast(cos(theta) * cos(phi)), - static_cast(sin(theta) * cos(phi)), - static_cast(sin(phi)) - ); +inline Vector3 vector3_for_spherical( double theta, double phi ){ + return Vector3( + static_cast( cos( theta ) * cos( phi ) ), + static_cast( sin( theta ) * cos( phi ) ), + static_cast( sin( phi ) ) + ); } template -inline bool vector4_equal(const BasicVector4& self, const BasicVector4& other) -{ - return self.x() == other.x() && self.y() == other.y() && self.z() == other.z() && self.w() == other.w(); +inline bool vector4_equal( const BasicVector4& self, const BasicVector4& other ){ + return self.x() == other.x() && self.y() == other.y() && self.z() == other.z() && self.w() == other.w(); } template -inline bool operator==(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_equal(self, other); +inline bool operator==( const BasicVector4& self, const BasicVector4& other ){ + return vector4_equal( self, other ); } template -inline bool operator!=(const BasicVector4& self, const BasicVector4& other) -{ - return !vector4_equal(self, other); +inline bool operator!=( const BasicVector4& self, const BasicVector4& other ){ + return !vector4_equal( self, other ); } template -inline bool vector4_equal_epsilon(const BasicVector4& self, const BasicVector4& other, Element epsilon) -{ - return float_equal_epsilon(self.x(), other.x(), epsilon) - && float_equal_epsilon(self.y(), other.y(), epsilon) - && float_equal_epsilon(self.z(), other.z(), epsilon) - && float_equal_epsilon(self.w(), other.w(), epsilon); +inline bool vector4_equal_epsilon( const BasicVector4& self, const BasicVector4& other, Element epsilon ){ + return float_equal_epsilon( self.x(), other.x(), epsilon ) + && float_equal_epsilon( self.y(), other.y(), epsilon ) + && float_equal_epsilon( self.z(), other.z(), epsilon ) + && float_equal_epsilon( self.w(), other.w(), epsilon ); } template -inline BasicVector4 vector4_added(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() + other.x()), - float(self.y() + other.y()), - float(self.z() + other.z()), - float(self.w() + other.w()) - ); +inline BasicVector4 vector4_added( const BasicVector4& self, const BasicVector4& other ){ + return BasicVector4( + float(self.x() + other.x() ), + float(self.y() + other.y() ), + float(self.z() + other.z() ), + float(self.w() + other.w() ) + ); } template -inline BasicVector4 operator+(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_added(self, other); +inline BasicVector4 operator+( const BasicVector4& self, const BasicVector4& other ){ + return vector4_added( self, other ); } template -inline void vector4_add(BasicVector4& self, const BasicVector4& other) -{ - self.x() += static_cast(other.x()); - self.y() += static_cast(other.y()); - self.z() += static_cast(other.z()); - self.w() += static_cast(other.w()); +inline void vector4_add( BasicVector4& self, const BasicVector4& other ){ + self.x() += static_cast( other.x() ); + self.y() += static_cast( other.y() ); + self.z() += static_cast( other.z() ); + self.w() += static_cast( other.w() ); } template -inline void operator+=(BasicVector4& self, const BasicVector4& other) -{ - vector4_add(self, other); +inline void operator+=( BasicVector4& self, const BasicVector4& other ){ + vector4_add( self, other ); } template -inline BasicVector4 vector4_subtracted(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() - other.x()), - float(self.y() - other.y()), - float(self.z() - other.z()), - float(self.w() - other.w()) - ); +inline BasicVector4 vector4_subtracted( const BasicVector4& self, const BasicVector4& other ){ + return BasicVector4( + float(self.x() - other.x() ), + float(self.y() - other.y() ), + float(self.z() - other.z() ), + float(self.w() - other.w() ) + ); } template -inline BasicVector4 operator-(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_subtracted(self, other); +inline BasicVector4 operator-( const BasicVector4& self, const BasicVector4& other ){ + return vector4_subtracted( self, other ); } template -inline void vector4_subtract(BasicVector4& self, const BasicVector4& other) -{ - self.x() -= static_cast(other.x()); - self.y() -= static_cast(other.y()); - self.z() -= static_cast(other.z()); - self.w() -= static_cast(other.w()); +inline void vector4_subtract( BasicVector4& self, const BasicVector4& other ){ + self.x() -= static_cast( other.x() ); + self.y() -= static_cast( other.y() ); + self.z() -= static_cast( other.z() ); + self.w() -= static_cast( other.w() ); } template -inline void operator-=(BasicVector4& self, const BasicVector4& other) -{ - vector4_subtract(self, other); +inline void operator-=( BasicVector4& self, const BasicVector4& other ){ + vector4_subtract( self, other ); } template -inline BasicVector4 vector4_scaled(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() * other.x()), - float(self.y() * other.y()), - float(self.z() * other.z()), - float(self.w() * other.w()) - ); +inline BasicVector4 vector4_scaled( const BasicVector4& self, const BasicVector4& other ){ + return BasicVector4( + float(self.x() * other.x() ), + float(self.y() * other.y() ), + float(self.z() * other.z() ), + float(self.w() * other.w() ) + ); } template -inline BasicVector4 operator*(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_scaled(self, other); +inline BasicVector4 operator*( const BasicVector4& self, const BasicVector4& other ){ + return vector4_scaled( self, other ); } template -inline void vector4_scale(BasicVector4& self, const BasicVector4& other) -{ - self.x() *= static_cast(other.x()); - self.y() *= static_cast(other.y()); - self.z() *= static_cast(other.z()); - self.w() *= static_cast(other.w()); +inline void vector4_scale( BasicVector4& self, const BasicVector4& other ){ + self.x() *= static_cast( other.x() ); + self.y() *= static_cast( other.y() ); + self.z() *= static_cast( other.z() ); + self.w() *= static_cast( other.w() ); } template -inline void operator*=(BasicVector4& self, const BasicVector4& other) -{ - vector4_scale(self, other); +inline void operator*=( BasicVector4& self, const BasicVector4& other ){ + vector4_scale( self, other ); } template -inline BasicVector4 vector4_scaled(const BasicVector4& self, OtherElement scale) -{ - return BasicVector4( - float(self.x() * scale), - float(self.y() * scale), - float(self.z() * scale), - float(self.w() * scale) - ); +inline BasicVector4 vector4_scaled( const BasicVector4& self, OtherElement scale ){ + return BasicVector4( + float(self.x() * scale), + float(self.y() * scale), + float(self.z() * scale), + float(self.w() * scale) + ); } template -inline BasicVector4 operator*(const BasicVector4& self, OtherElement scale) -{ - return vector4_scaled(self, scale); +inline BasicVector4 operator*( const BasicVector4& self, OtherElement scale ){ + return vector4_scaled( self, scale ); } template -inline void vector4_scale(BasicVector4& self, OtherElement scale) -{ - self.x() *= static_cast(scale); - self.y() *= static_cast(scale); - self.z() *= static_cast(scale); - self.w() *= static_cast(scale); +inline void vector4_scale( BasicVector4& self, OtherElement scale ){ + self.x() *= static_cast( scale ); + self.y() *= static_cast( scale ); + self.z() *= static_cast( scale ); + self.w() *= static_cast( scale ); } template -inline void operator*=(BasicVector4& self, OtherElement scale) -{ - vector4_scale(self, scale); +inline void operator*=( BasicVector4& self, OtherElement scale ){ + vector4_scale( self, scale ); } template -inline BasicVector4 vector4_divided(const BasicVector4& self, OtherElement divisor) -{ - return BasicVector4( - float(self.x() / divisor), - float(self.y() / divisor), - float(self.z() / divisor), - float(self.w() / divisor) - ); +inline BasicVector4 vector4_divided( const BasicVector4& self, OtherElement divisor ){ + return BasicVector4( + float(self.x() / divisor), + float(self.y() / divisor), + float(self.z() / divisor), + float(self.w() / divisor) + ); } template -inline BasicVector4 operator/(const BasicVector4& self, OtherElement divisor) -{ - return vector4_divided(self, divisor); +inline BasicVector4 operator/( const BasicVector4& self, OtherElement divisor ){ + return vector4_divided( self, divisor ); } template -inline void vector4_divide(BasicVector4& self, OtherElement divisor) -{ - self.x() /= divisor; - self.y() /= divisor; - self.z() /= divisor; - self.w() /= divisor; +inline void vector4_divide( BasicVector4& self, OtherElement divisor ){ + self.x() /= divisor; + self.y() /= divisor; + self.z() /= divisor; + self.w() /= divisor; } template -inline void operator/=(BasicVector4& self, OtherElement divisor) -{ - vector4_divide(self, divisor); +inline void operator/=( BasicVector4& self, OtherElement divisor ){ + vector4_divide( self, divisor ); } template -inline double vector4_dot(const BasicVector4& self, const BasicVector4& other) -{ - return self.x() * other.x() + self.y() * other.y() + self.z() * other.z() + self.w() * other.w(); +inline double vector4_dot( const BasicVector4& self, const BasicVector4& other ){ + return self.x() * other.x() + self.y() * other.y() + self.z() * other.z() + self.w() * other.w(); } template -inline BasicVector3 vector4_projected(const BasicVector4& self) -{ - return vector3_scaled(vector4_to_vector3(self), 1.0 / self[3]); +inline BasicVector3 vector4_projected( const BasicVector4& self ){ + return vector3_scaled( vector4_to_vector3( self ), 1.0 / self[3] ); } #endif diff --git a/libs/mathlib.h b/libs/mathlib.h index 382933d7..64f3f6e4 100644 --- a/libs/mathlib.h +++ b/libs/mathlib.h @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #ifndef __MATHLIB__ #define __MATHLIB__ @@ -47,19 +47,19 @@ typedef vec_t vec4_t[4]; // because for example adding VEC_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. #define VEC_SMALLEST_EPSILON_AROUND_ONE FLT_EPSILON -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 +#define SIDE_FRONT 0 +#define SIDE_ON 2 +#define SIDE_BACK 1 +#define SIDE_CROSS -2 // plane types are used to speed some tests // 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 -#define PLANE_NON_AXIAL 3 +#define PLANE_X 0 +#define PLANE_Y 1 +#define PLANE_Z 2 +#define PLANE_NON_AXIAL 3 -#define Q_PI 3.14159265358979323846f +#define Q_PI 3.14159265358979323846f extern const vec3_t vec3_origin; @@ -67,105 +67,105 @@ extern const vec3_t g_vec3_axis_x; extern const vec3_t g_vec3_axis_y; extern const vec3_t g_vec3_axis_z; -#define EQUAL_EPSILON 0.001 +#define EQUAL_EPSILON 0.001 -#define DotProduct(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]+(x)[2]*(y)[2]) -#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2]) -#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2]) -#define VectorIncrement(a,b) ((b)[0]+=(a)[0],(b)[1]+=(a)[1],(b)[2]+=(a)[2]) -#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2]) -#define VectorSet(v, a, b, c) ((v)[0]=(a),(v)[1]=(b),(v)[2]=(c)) -#define VectorScale(a,b,c) ((c)[0]=(b)*(a)[0],(c)[1]=(b)*(a)[1],(c)[2]=(b)*(a)[2]) -#define VectorMid(a,b,c) ((c)[0]=((a)[0]+(b)[0])*0.5f,(c)[1]=((a)[1]+(b)[1])*0.5f,(c)[2]=((a)[2]+(b)[2])*0.5f) -#define VectorNegate(a,b) ((b)[0]=-(a)[0],(b)[1]=-(a)[1],(b)[2]=-(a)[2]) -#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0]) -#define VectorClear(x) ((x)[0]=(x)[1]=(x)[2]=0) +#define DotProduct( x,y ) ( ( x )[0] * ( y )[0] + ( x )[1] * ( y )[1] + ( x )[2] * ( y )[2] ) +#define VectorSubtract( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2] ) +#define VectorAdd( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2] ) +#define VectorIncrement( a,b ) ( ( b )[0] += ( a )[0],( b )[1] += ( a )[1],( b )[2] += ( a )[2] ) +#define VectorCopy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2] ) +#define VectorSet( v, a, b, c ) ( ( v )[0] = ( a ),( v )[1] = ( b ),( v )[2] = ( c ) ) +#define VectorScale( a,b,c ) ( ( c )[0] = ( b ) * ( a )[0],( c )[1] = ( b ) * ( a )[1],( c )[2] = ( b ) * ( a )[2] ) +#define VectorMid( a,b,c ) ( ( c )[0] = ( ( a )[0] + ( b )[0] ) * 0.5f,( c )[1] = ( ( a )[1] + ( b )[1] ) * 0.5f,( c )[2] = ( ( a )[2] + ( b )[2] ) * 0.5f ) +#define VectorNegate( a,b ) ( ( b )[0] = -( a )[0],( b )[1] = -( a )[1],( b )[2] = -( a )[2] ) +#define CrossProduct( a,b,c ) ( ( c )[0] = ( a )[1] * ( b )[2] - ( a )[2] * ( b )[1],( c )[1] = ( a )[2] * ( b )[0] - ( a )[0] * ( b )[2],( c )[2] = ( a )[0] * ( b )[1] - ( a )[1] * ( b )[0] ) +#define VectorClear( x ) ( ( x )[0] = ( x )[1] = ( x )[2] = 0 ) -#define FLOAT_SNAP(f,snap) ( (float)( floor( (f) / (snap) + 0.5 ) * (snap) ) ) -#define FLOAT_TO_INTEGER(f) ( (float)( floor( (f) + 0.5 ) ) ) +#define FLOAT_SNAP( f,snap ) ( (float)( floor( ( f ) / ( snap ) + 0.5 ) * ( snap ) ) ) +#define FLOAT_TO_INTEGER( f ) ( (float)( floor( ( f ) + 0.5 ) ) ) -#define RGBTOGRAY(x) ( (float)((x)[0]) * 0.2989f + (float)((x)[1]) * 0.5870f + (float)((x)[2]) * 0.1140f ) +#define RGBTOGRAY( x ) ( (float)( ( x )[0] ) * 0.2989f + (float)( ( x )[1] ) * 0.5870f + (float)( ( x )[2] ) * 0.1140f ) -#define Q_rint(in) ((vec_t)floor(in+0.5)) +#define Q_rint( in ) ( (vec_t)floor( in + 0.5 ) ) -qboolean VectorCompare (const vec3_t v1, const vec3_t v2); +qboolean VectorCompare( const vec3_t v1, const vec3_t v2 ); -qboolean VectorIsOnAxis(vec3_t v); -qboolean VectorIsOnAxialPlane(vec3_t v); +qboolean VectorIsOnAxis( vec3_t v ); +qboolean VectorIsOnAxialPlane( vec3_t v ); -vec_t VectorLength(const vec3_t v); +vec_t VectorLength( const vec3_t v ); void VectorMA( const vec3_t va, vec_t scale, const vec3_t vb, vec3_t vc ); -void _CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); +void _CrossProduct( vec3_t v1, vec3_t v2, vec3_t cross ); // I need this define in order to test some of the regression tests from time to time. // This define affect the precision of VectorNormalize() function only. #define MATHLIB_VECTOR_NORMALIZE_PRECISION_FIX 1 -vec_t VectorNormalize (const vec3_t in, vec3_t out); +vec_t VectorNormalize( const vec3_t in, vec3_t out ); vec_t ColorNormalize( const vec3_t in, vec3_t out ); -void VectorInverse (vec3_t v); -void VectorPolar(vec3_t v, float radius, float theta, float phi); +void VectorInverse( vec3_t v ); +void VectorPolar( vec3_t v, float radius, float theta, float phi ); // default snapping, to 1 -void VectorSnap(vec3_t v); +void VectorSnap( vec3_t v ); // integer snapping -void VectorISnap(vec3_t point, int snap); +void VectorISnap( vec3_t point, int snap ); // Gef: added snap to float for sub-integer grid sizes // TTimo: we still use the int version of VectorSnap when possible // to avoid potential rounding issues // TTimo: renaming to VectorFSnap for C implementation -void VectorFSnap(vec3_t point, float snap); +void VectorFSnap( vec3_t point, float snap ); // NOTE: added these from Ritual's Q3Radiant -void ClearBounds (vec3_t mins, vec3_t maxs); -void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs); +void ClearBounds( vec3_t mins, vec3_t maxs ); +void AddPointToBounds( vec3_t v, vec3_t mins, vec3_t maxs ); -#define PITCH 0 // up / down -#define YAW 1 // left / right -#define ROLL 2 // fall over +#define PITCH 0 // up / down +#define YAW 1 // left / right +#define ROLL 2 // fall over -void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up); +void AngleVectors( vec3_t angles, vec3_t forward, vec3_t right, vec3_t up ); void VectorToAngles( vec3_t vec, vec3_t angles ); #define ZERO_EPSILON 1.0E-6 #define RAD2DEGMULT 57.29577951308232f #define DEG2RADMULT 0.01745329251994329f -#define RAD2DEG( a ) ( (a) * RAD2DEGMULT ) -#define DEG2RAD( a ) ( (a) * DEG2RADMULT ) +#define RAD2DEG( a ) ( ( a ) * RAD2DEGMULT ) +#define DEG2RAD( a ) ( ( a ) * DEG2RADMULT ) -void VectorRotate (vec3_t vIn, vec3_t vRotation, vec3_t out); -void VectorRotateOrigin (vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out); +void VectorRotate( vec3_t vIn, vec3_t vRotation, vec3_t out ); +void VectorRotateOrigin( vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out ); // some function merged from tools mathlib code qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ); void NormalToLatLong( const vec3_t normal, byte bytes[2] ); -int PlaneTypeForNormal (vec3_t normal); +int PlaneTypeForNormal( vec3_t normal ); void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees ); /*! -\todo -FIXME test calls such as intersect tests should be named test_ -*/ + \todo + FIXME test calls such as intersect tests should be named test_ + */ typedef vec_t m3x3_t[9]; -/*!NOTE -m4x4 looks like this.. +/*!NOTE + m4x4 looks like this.. x y z -x axis ( 0 1 2) -y axis ( 4 5 6) -z axis ( 8 9 10) -translation (12 13 14) -scale ( 0 5 10) -*/ + x axis ( 0 1 2) + y axis ( 4 5 6) + z axis ( 8 9 10) + translation (12 13 14) + scale ( 0 5 10) + */ typedef vec_t m4x4_t[16]; -#define M4X4_INDEX(m,row,col) (m[(col<<2)+row]) +#define M4X4_INDEX( m,row,col ) ( m[( col << 2 ) + row] ) typedef enum { eXYZ, eYZX, eZXY, eXZY, eYXZ, eZYX } eulerOrder_t; @@ -181,255 +181,255 @@ typedef unsigned char clipmask_t; extern const m4x4_t g_m4x4_identity; -#define M4X4_COPY(dst,src) (\ -(dst)[0]=(src)[0],\ -(dst)[1]=(src)[1],\ -(dst)[2]=(src)[2],\ -(dst)[3]=(src)[3],\ -(dst)[4]=(src)[4],\ -(dst)[5]=(src)[5],\ -(dst)[6]=(src)[6],\ -(dst)[7]=(src)[7],\ -(dst)[8]=(src)[8],\ -(dst)[9]=(src)[9],\ -(dst)[10]=(src)[10],\ -(dst)[11]=(src)[11],\ -(dst)[12]=(src)[12],\ -(dst)[13]=(src)[13],\ -(dst)[14]=(src)[14],\ -(dst)[15]=(src)[15]) +#define M4X4_COPY( dst,src ) ( \ + ( dst )[0] = ( src )[0], \ + ( dst )[1] = ( src )[1], \ + ( dst )[2] = ( src )[2], \ + ( dst )[3] = ( src )[3], \ + ( dst )[4] = ( src )[4], \ + ( dst )[5] = ( src )[5], \ + ( dst )[6] = ( src )[6], \ + ( dst )[7] = ( src )[7], \ + ( dst )[8] = ( src )[8], \ + ( dst )[9] = ( src )[9], \ + ( dst )[10] = ( src )[10], \ + ( dst )[11] = ( src )[11], \ + ( dst )[12] = ( src )[12], \ + ( dst )[13] = ( src )[13], \ + ( dst )[14] = ( src )[14], \ + ( dst )[15] = ( src )[15] ) typedef enum { - eRightHanded = 0, - eLeftHanded = 1, -} + eRightHanded = 0, + eLeftHanded = 1, +} m4x4Handedness_t; -m4x4Handedness_t m4x4_handedness(const m4x4_t matrix); +m4x4Handedness_t m4x4_handedness( const m4x4_t matrix ); /*! assign other m4x4 to this m4x4 */ -void m4x4_assign(m4x4_t matrix, const m4x4_t other); +void m4x4_assign( m4x4_t matrix, const m4x4_t other ); // constructors /*! create m4x4 as identity matrix */ -void m4x4_identity(m4x4_t matrix); +void m4x4_identity( m4x4_t matrix ); /*! create m4x4 as a translation matrix, for a translation vec3 */ -void m4x4_translation_for_vec3(m4x4_t matrix, const vec3_t translation); +void m4x4_translation_for_vec3( m4x4_t matrix, const vec3_t translation ); /*! create m4x4 as a rotation matrix, for an euler angles (degrees) vec3 */ -void m4x4_rotation_for_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order); +void m4x4_rotation_for_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ); /*! create m4x4 as a scaling matrix, for a scale vec3 */ -void m4x4_scale_for_vec3(m4x4_t matrix, const vec3_t scale); +void m4x4_scale_for_vec3( m4x4_t matrix, const vec3_t scale ); /*! create m4x4 as a rotation matrix, for a quaternion vec4 */ -void m4x4_rotation_for_quat(m4x4_t matrix, const vec4_t rotation); +void m4x4_rotation_for_quat( m4x4_t matrix, const vec4_t rotation ); /*! create m4x4 as a rotation matrix, for an axis vec3 and an angle (radians) */ -void m4x4_rotation_for_axisangle(m4x4_t matrix, const vec3_t axis, double angle); +void m4x4_rotation_for_axisangle( m4x4_t matrix, const vec3_t axis, double angle ); /*! generate a perspective matrix by specifying the view frustum */ -void m4x4_frustum(m4x4_t matrix, vec_t left, vec_t right, vec_t bottom, vec_t top, vec_t nearval, vec_t farval); +void m4x4_frustum( m4x4_t matrix, vec_t left, vec_t right, vec_t bottom, vec_t top, vec_t nearval, vec_t farval ); // a valid m4x4 to access is always first argument /*! extract translation vec3 from matrix */ -void m4x4_get_translation_vec3(const m4x4_t matrix, vec3_t translation); +void m4x4_get_translation_vec3( const m4x4_t matrix, vec3_t translation ); /*! extract euler rotation angles from a rotation-only matrix */ -void m4x4_get_rotation_vec3(const m4x4_t matrix, vec3_t euler, eulerOrder_t order); +void m4x4_get_rotation_vec3( const m4x4_t matrix, vec3_t euler, eulerOrder_t order ); /*! extract scale vec3 from matrix */ -void m4x4_get_scale_vec3(const m4x4_t matrix, vec3_t scale); +void m4x4_get_scale_vec3( const m4x4_t matrix, vec3_t scale ); /*! extract translation/euler/scale from an orthogonal matrix. NOTE: requires right-handed axis-base */ -void m4x4_get_transform_vec3(const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale); +void m4x4_get_transform_vec3( const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale ); // a valid m4x4 to be modified is always first argument /*! translate m4x4 by a translation vec3 */ -void m4x4_translate_by_vec3(m4x4_t matrix, const vec3_t translation); +void m4x4_translate_by_vec3( m4x4_t matrix, const vec3_t translation ); /*! rotate m4x4 by a euler (degrees) vec3 */ -void m4x4_rotate_by_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order); +void m4x4_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ); /*! scale m4x4 by a scaling vec3 */ -void m4x4_scale_by_vec3(m4x4_t matrix, const vec3_t scale); +void m4x4_scale_by_vec3( m4x4_t matrix, const vec3_t scale ); /*! rotate m4x4 by a quaternion vec4 */ -void m4x4_rotate_by_quat(m4x4_t matrix, const vec4_t rotation); +void m4x4_rotate_by_quat( m4x4_t matrix, const vec4_t rotation ); /*! rotate m4x4 by an axis vec3 and an angle (radians) */ -void m4x4_rotate_by_axisangle(m4x4_t matrix, const vec3_t axis, double angle); +void m4x4_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle ); /*! transform m4x4 by translation/eulerZYX/scaling vec3 (transform = scale * eulerZ * eulerY * eulerX * translation) */ -void m4x4_transform_by_vec3(m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale); +void m4x4_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale ); /*! rotate m4x4 around a pivot point by eulerZYX vec3 */ -void m4x4_pivoted_rotate_by_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint); +void m4x4_pivoted_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint ); /*! scale m4x4 around a pivot point by scaling vec3 */ -void m4x4_pivoted_scale_by_vec3(m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint); +void m4x4_pivoted_scale_by_vec3( m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint ); /*! transform m4x4 around a pivot point by translation/eulerZYX/scaling vec3 */ -void m4x4_pivoted_transform_by_vec3(m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint); +void m4x4_pivoted_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint ); /*! transform m4x4 around a pivot point by translation/rotation/scaling vec3 */ -void m4x4_pivoted_transform_by_rotation(m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint); +void m4x4_pivoted_transform_by_rotation( m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint ); /*! rotate m4x4 around a pivot point by quaternion vec4 */ -void m4x4_pivoted_rotate_by_quat(m4x4_t matrix, const vec4_t quat, const vec3_t pivotpoint); +void m4x4_pivoted_rotate_by_quat( m4x4_t matrix, const vec4_t quat, const vec3_t pivotpoint ); /*! rotate m4x4 around a pivot point by axis vec3 and angle (radians) */ -void m4x4_pivoted_rotate_by_axisangle(m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint); +void m4x4_pivoted_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint ); /*! postmultiply m4x4 by another m4x4 */ -void m4x4_multiply_by_m4x4(m4x4_t matrix, const m4x4_t matrix_src); +void m4x4_multiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); /*! premultiply m4x4 by another m4x4 */ -void m4x4_premultiply_by_m4x4(m4x4_t matrix, const m4x4_t matrix_src); +void m4x4_premultiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); /*! postmultiply orthogonal m4x4 by another orthogonal m4x4 */ -void m4x4_orthogonal_multiply_by_m4x4(m4x4_t matrix, const m4x4_t matrix_src); +void m4x4_orthogonal_multiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); /*! premultiply orthogonal m4x4 by another orthogonal m4x4 */ -void m4x4_orthogonal_premultiply_by_m4x4(m4x4_t matrix, const m4x4_t matrix_src); +void m4x4_orthogonal_premultiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); /*! multiply a point (x,y,z,1) by matrix */ -void m4x4_transform_point(const m4x4_t matrix, vec3_t point); +void m4x4_transform_point( const m4x4_t matrix, vec3_t point ); /*! multiply a normal (x,y,z,0) by matrix */ -void m4x4_transform_normal(const m4x4_t matrix, vec3_t normal); +void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ); /*! multiply a vec4 (x,y,z,w) by matrix */ -void m4x4_transform_vec4(const m4x4_t matrix, vec4_t vector); +void m4x4_transform_vec4( const m4x4_t matrix, vec4_t vector ); /*! multiply a point (x,y,z,1) by matrix */ -void m4x4_transform_point(const m4x4_t matrix, vec3_t point); +void m4x4_transform_point( const m4x4_t matrix, vec3_t point ); /*! multiply a normal (x,y,z,0) by matrix */ -void m4x4_transform_normal(const m4x4_t matrix, vec3_t normal); +void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ); /*! transpose a m4x4 */ -void m4x4_transpose(m4x4_t matrix); +void m4x4_transpose( m4x4_t matrix ); /*! invert an orthogonal 4x3 subset of a 4x4 matrix */ -int m4x4_orthogonal_invert(m4x4_t matrix); +int m4x4_orthogonal_invert( m4x4_t matrix ); /*! m4_det */ float m4_det( m4x4_t mr ); /*! invert any m4x4 using Kramer's rule.. return 1 if matrix is singular, else return 0 */ -int m4x4_invert(m4x4_t matrix); +int m4x4_invert( m4x4_t matrix ); /*! clip a point (x,y,z,1) by canonical matrix */ -clipmask_t m4x4_clip_point(const m4x4_t matrix, const vec3_t point, vec4_t clipped); +clipmask_t m4x4_clip_point( const m4x4_t matrix, const vec3_t point, vec4_t clipped ); /*! device-space polygon for clipped triangle */ -unsigned int m4x4_clip_triangle(const m4x4_t matrix, const vec3_t p0, const vec3_t p1, const vec3_t p2, vec4_t clipped[9]); +unsigned int m4x4_clip_triangle( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, const vec3_t p2, vec4_t clipped[9] ); /*! device-space line for clipped line */ -unsigned int m4x4_clip_line(const m4x4_t matrix, const vec3_t p0, const vec3_t p1, vec4_t clipped[2]); +unsigned int m4x4_clip_line( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, vec4_t clipped[2] ); //! quaternion identity -void quat_identity(vec4_t quat); +void quat_identity( vec4_t quat ); //! quaternion from two unit vectors -void quat_for_unit_vectors(vec4_t quat, const vec3_t from, const vec3_t to); +void quat_for_unit_vectors( vec4_t quat, const vec3_t from, const vec3_t to ); //! quaternion from axis and angle (radians) -void quat_for_axisangle(vec4_t quat, const vec3_t axis, double angle); +void quat_for_axisangle( vec4_t quat, const vec3_t axis, double angle ); //! concatenates two rotations.. equivalent to m4x4_multiply_by_m4x4 .. postmultiply.. the right-hand side is the first rotation performed -void quat_multiply_by_quat(vec4_t quat, const vec4_t other); +void quat_multiply_by_quat( vec4_t quat, const vec4_t other ); //! negate a quaternion -void quat_conjugate(vec4_t quat); +void quat_conjugate( vec4_t quat ); //! normalise a quaternion -void quat_normalise(vec4_t quat); +void quat_normalise( vec4_t quat ); /*! -\todo object/ray intersection functions should maybe return a point rather than a distance? -*/ + \todo object/ray intersection functions should maybe return a point rather than a distance? + */ /*! -aabb_t - "axis-aligned" bounding box... - origin: centre of bounding box... - extents: +/- extents of box from origin... -*/ + aabb_t - "axis-aligned" bounding box... + origin: centre of bounding box... + extents: +/- extents of box from origin... + */ typedef struct aabb_s { - vec3_t origin; - vec3_t extents; + vec3_t origin; + vec3_t extents; } aabb_t; extern const aabb_t g_aabb_null; /*! -bbox_t - oriented bounding box... - aabb: axis-aligned bounding box... - axes: orientation axes... -*/ + bbox_t - oriented bounding box... + aabb: axis-aligned bounding box... + axes: orientation axes... + */ typedef struct bbox_s { - aabb_t aabb; - vec3_t axes[3]; - vec_t radius; + aabb_t aabb; + vec3_t axes[3]; + vec_t radius; } bbox_t; /*! -ray_t - origin point and direction unit-vector -*/ + ray_t - origin point and direction unit-vector + */ typedef struct ray_s { - vec3_t origin; - vec3_t direction; + vec3_t origin; + vec3_t direction; } ray_t; /*! -line_t - centre point and displacement of end point from centre -*/ + line_t - centre point and displacement of end point from centre + */ typedef struct line_s { - vec3_t origin; - vec3_t extents; + vec3_t origin; + vec3_t extents; } line_t; /*! Generate line from start/end points. */ -void line_construct_for_vec3(line_t* line, const vec3_t start, const vec3_t end); +void line_construct_for_vec3( line_t* line, const vec3_t start, const vec3_t end ); /*! Return 2 if line is behind plane, else return 1 if line intersects plane, else return 0. */ -int line_test_plane(const line_t* line, const vec4_t plane); +int line_test_plane( const line_t* line, const vec4_t plane ); /*! Generate AABB from min/max. */ -void aabb_construct_for_vec3(aabb_t* aabb, const vec3_t min, const vec3_t max); +void aabb_construct_for_vec3( aabb_t* aabb, const vec3_t min, const vec3_t max ); /*! Initialise AABB to negative size. */ -void aabb_clear(aabb_t* aabb); +void aabb_clear( aabb_t* aabb ); /*! Extend AABB to include point. */ -void aabb_extend_by_point(aabb_t* aabb, const vec3_t point); +void aabb_extend_by_point( aabb_t* aabb, const vec3_t point ); /*! Extend AABB to include aabb_src. */ -void aabb_extend_by_aabb(aabb_t* aabb, const aabb_t* aabb_src); +void aabb_extend_by_aabb( aabb_t* aabb, const aabb_t* aabb_src ); /*! Extend AABB by +/- extension vector. */ -void aabb_extend_by_vec3(aabb_t* aabb, vec3_t extension); +void aabb_extend_by_vec3( aabb_t* aabb, vec3_t extension ); /*! Return 2 if point is inside, else 1 if point is on surface, else 0. */ -int aabb_test_point(const aabb_t* aabb, const vec3_t point); +int aabb_test_point( const aabb_t* aabb, const vec3_t point ); /*! Return 2 if aabb_src intersects, else 1 if aabb_src touches exactly, else 0. */ -int aabb_test_aabb(const aabb_t* aabb, const aabb_t* aabb_src); +int aabb_test_aabb( const aabb_t* aabb, const aabb_t* aabb_src ); /*! Return 2 if aabb is behind plane, else 1 if aabb intersects plane, else 0. */ -int aabb_test_plane(const aabb_t* aabb, const float* plane); +int aabb_test_plane( const aabb_t* aabb, const float* plane ); /*! Return 1 if aabb intersects ray, else 0... dist = closest intersection. */ -int aabb_intersect_ray(const aabb_t* aabb, const ray_t* ray, vec3_t intersection); +int aabb_intersect_ray( const aabb_t* aabb, const ray_t* ray, vec3_t intersection ); /*! Return 1 if aabb intersects ray, else 0. Faster, but does not provide point of intersection */ -int aabb_test_ray(const aabb_t* aabb, const ray_t* ray); +int aabb_test_ray( const aabb_t* aabb, const ray_t* ray ); /*! Return 2 if oriented aabb is behind plane, else 1 if aabb intersects plane, else 0. */ -int aabb_oriented_intersect_plane(const aabb_t* aabb, const m4x4_t transform, const vec_t* plane); +int aabb_oriented_intersect_plane( const aabb_t* aabb, const m4x4_t transform, const vec_t* plane ); /*! Calculate the corners of the aabb. */ -void aabb_corners(const aabb_t* aabb, vec3_t corners[8]); +void aabb_corners( const aabb_t * aabb, vec3_t corners[8] ); /*! (deprecated) Generate AABB from oriented bounding box. */ -void aabb_for_bbox(aabb_t* aabb, const bbox_t* bbox); +void aabb_for_bbox( aabb_t* aabb, const bbox_t* bbox ); /*! (deprecated) Generate AABB from 2-dimensions of min/max, specified by axis. */ -void aabb_for_area(aabb_t* aabb, vec3_t area_tl, vec3_t area_br, int axis); +void aabb_for_area( aabb_t* aabb, vec3_t area_tl, vec3_t area_br, int axis ); /*! Generate AABB to contain src* transform. NOTE: transform must be orthogonal */ -void aabb_for_transformed_aabb(aabb_t* dst, const aabb_t* src, const m4x4_t transform); +void aabb_for_transformed_aabb( aabb_t* dst, const aabb_t* src, const m4x4_t transform ); /*! Update bounding-sphere radius. */ -void bbox_update_radius(bbox_t* bbox); +void bbox_update_radius( bbox_t* bbox ); /*! Generate oriented bounding box from AABB and transformation matrix. */ /*!\todo Remove need to specify eulerZYX/scale. */ -void bbox_for_oriented_aabb(bbox_t* bbox, const aabb_t* aabb, - const m4x4_t matrix, const vec3_t eulerZYX, const vec3_t scale); +void bbox_for_oriented_aabb( bbox_t* bbox, const aabb_t* aabb, + const m4x4_t matrix, const vec3_t eulerZYX, const vec3_t scale ); /*! Return 2 if bbox is behind plane, else return 1 if bbox intersects plane, else return 0. */ -int bbox_intersect_plane(const bbox_t* bbox, const vec_t* plane); +int bbox_intersect_plane( const bbox_t* bbox, const vec_t* plane ); /*! Generate a ray from an origin point and a direction unit-vector */ -void ray_construct_for_vec3(ray_t* ray, const vec3_t origin, const vec3_t direction); - +void ray_construct_for_vec3( ray_t* ray, const vec3_t origin, const vec3_t direction ); + /*! Transform a ray */ -void ray_transform(ray_t* ray, const m4x4_t matrix); +void ray_transform( ray_t* ray, const m4x4_t matrix ); /*! distance from ray origin in ray direction to point. FLT_MAX if no intersection. */ -vec_t ray_intersect_point(const ray_t* ray, const vec3_t point, vec_t epsilon, vec_t divergence); +vec_t ray_intersect_point( const ray_t* ray, const vec3_t point, vec_t epsilon, vec_t divergence ); /*! distance from ray origin in ray direction to triangle. FLT_MAX if no intersection. */ -vec_t ray_intersect_triangle(const ray_t* ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2); +vec_t ray_intersect_triangle( const ray_t* ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2 ); /*! distance from ray origin in ray direction to plane. */ -vec_t ray_intersect_plane(const ray_t* ray, const vec3_t normal, vec_t dist); +vec_t ray_intersect_plane( const ray_t* ray, const vec3_t normal, vec_t dist ); -int plane_intersect_planes(const vec4_t plane1, const vec4_t plane2, const vec4_t plane3, vec3_t intersection); +int plane_intersect_planes( const vec4_t plane1, const vec4_t plane2, const vec4_t plane3, vec3_t intersection ); @@ -449,7 +449,7 @@ typedef vec_accu_t vec3_accu_t[3]; // because for example adding VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. #define VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE DBL_EPSILON -vec_accu_t VectorLengthAccu(const vec3_accu_t v); +vec_accu_t VectorLengthAccu( const vec3_accu_t v ); // I have a feeling it may be safer to break these #define functions out into actual functions // in order to avoid accidental loss of precision. For example, say you call @@ -464,17 +464,17 @@ vec_accu_t VectorLengthAccu(const vec3_accu_t v); //#define CrossProductAccu(a, b, c) ((c)[0] = (a)[1] * (b)[2] - (a)[2] * (b)[1], (c)[1] = (a)[2] * (b)[0] - (a)[0] * (b)[2], (c)[2] = (a)[0] * (b)[1] - (a)[1] * (b)[0]) //#define Q_rintAccu(in) ((vec_accu_t) floor(in + 0.5)) -vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b); -void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out); -void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out); -void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -vec_accu_t Q_rintAccu(vec_accu_t val); - -void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out); -void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out); -vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out); +vec_accu_t DotProductAccu( const vec3_accu_t a, const vec3_accu_t b ); +void VectorSubtractAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ); +void VectorAddAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ); +void VectorCopyAccu( const vec3_accu_t in, vec3_accu_t out ); +void VectorScaleAccu( const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out ); +void CrossProductAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ); +vec_accu_t Q_rintAccu( vec_accu_t val ); + +void VectorCopyAccuToRegular( const vec3_accu_t in, vec3_t out ); +void VectorCopyRegularToAccu( const vec3_t in, vec3_accu_t out ); +vec_accu_t VectorNormalizeAccu( const vec3_accu_t in, vec3_accu_t out ); #ifdef __cplusplus } diff --git a/libs/mathlib/bbox.c b/libs/mathlib/bbox.c index e8dc8657..fc9c1e33 100644 --- a/libs/mathlib/bbox.c +++ b/libs/mathlib/bbox.c @@ -1,462 +1,456 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include #include "mathlib.h" const aabb_t g_aabb_null = { - { 0, 0, 0, }, - { -FLT_MAX, -FLT_MAX, -FLT_MAX, }, + { 0, 0, 0, }, + { -FLT_MAX, -FLT_MAX, -FLT_MAX, }, }; -void aabb_construct_for_vec3(aabb_t *aabb, const vec3_t min, const vec3_t max) -{ - VectorMid(min, max, aabb->origin); - VectorSubtract(max, aabb->origin, aabb->extents); +void aabb_construct_for_vec3( aabb_t *aabb, const vec3_t min, const vec3_t max ){ + VectorMid( min, max, aabb->origin ); + VectorSubtract( max, aabb->origin, aabb->extents ); } -void aabb_clear(aabb_t *aabb) -{ - VectorCopy(g_aabb_null.origin, aabb->origin); - VectorCopy(g_aabb_null.extents, aabb->extents); +void aabb_clear( aabb_t *aabb ){ + VectorCopy( g_aabb_null.origin, aabb->origin ); + VectorCopy( g_aabb_null.extents, aabb->extents ); } -void aabb_extend_by_point(aabb_t *aabb, const vec3_t point) -{ +void aabb_extend_by_point( aabb_t *aabb, const vec3_t point ){ #if 1 - int i; - vec_t min, max, displacement; - for(i=0; i<3; i++) - { - displacement = point[i] - aabb->origin[i]; - if(fabs(displacement) > aabb->extents[i]) - { - if(aabb->extents[i] < 0) // degenerate - { - min = max = point[i]; - } - else if(displacement > 0) - { - min = aabb->origin[i] - aabb->extents[i]; - max = aabb->origin[i] + displacement; - } - else - { - max = aabb->origin[i] + aabb->extents[i]; - min = aabb->origin[i] + displacement; - } - aabb->origin[i] = (min + max) * 0.5f; - aabb->extents[i] = max - aabb->origin[i]; - } - } + int i; + vec_t min, max, displacement; + for ( i = 0; i < 3; i++ ) + { + displacement = point[i] - aabb->origin[i]; + if ( fabs( displacement ) > aabb->extents[i] ) { + if ( aabb->extents[i] < 0 ) { // degenerate + min = max = point[i]; + } + else if ( displacement > 0 ) { + min = aabb->origin[i] - aabb->extents[i]; + max = aabb->origin[i] + displacement; + } + else + { + max = aabb->origin[i] + aabb->extents[i]; + min = aabb->origin[i] + displacement; + } + aabb->origin[i] = ( min + max ) * 0.5f; + aabb->extents[i] = max - aabb->origin[i]; + } + } #else - unsigned int i; - for(i=0; i<3; ++i) - { - if(aabb->extents[i] < 0) // degenerate - { - aabb->origin[i] = point[i]; - aabb->extents[i] = 0; - } - else - { - vec_t displacement = point[i] - aabb->origin[i]; - vec_t increment = (vec_t)fabs(displacement) - aabb->extents[i]; - if(increment > 0) - { - increment *= (vec_t)((displacement > 0) ? 0.5 : -0.5); - aabb->extents[i] += increment; - aabb->origin[i] += increment; - } - } - } + unsigned int i; + for ( i = 0; i < 3; ++i ) + { + if ( aabb->extents[i] < 0 ) { // degenerate + aabb->origin[i] = point[i]; + aabb->extents[i] = 0; + } + else + { + vec_t displacement = point[i] - aabb->origin[i]; + vec_t increment = (vec_t)fabs( displacement ) - aabb->extents[i]; + if ( increment > 0 ) { + increment *= (vec_t)( ( displacement > 0 ) ? 0.5 : -0.5 ); + aabb->extents[i] += increment; + aabb->origin[i] += increment; + } + } + } #endif } -void aabb_extend_by_aabb(aabb_t *aabb, const aabb_t *aabb_src) -{ - int i; - vec_t min, max, displacement, difference; - for(i=0; i<3; i++) - { - displacement = aabb_src->origin[i] - aabb->origin[i]; - difference = aabb_src->extents[i] - aabb->extents[i]; - if(aabb->extents[i] < 0 - || difference >= fabs(displacement)) - { - // 2nd contains 1st - aabb->extents[i] = aabb_src->extents[i]; - aabb->origin[i] = aabb_src->origin[i]; - } - else if(aabb_src->extents[i] < 0 - || -difference >= fabs(displacement)) - { - // 1st contains 2nd - continue; - } - else - { - // not contained - if(displacement > 0) - { - min = aabb->origin[i] - aabb->extents[i]; - max = aabb_src->origin[i] + aabb_src->extents[i]; - } - else - { - min = aabb_src->origin[i] - aabb_src->extents[i]; - max = aabb->origin[i] + aabb->extents[i]; - } - aabb->origin[i] = (min + max) * 0.5f; - aabb->extents[i] = max - aabb->origin[i]; - } - } +void aabb_extend_by_aabb( aabb_t *aabb, const aabb_t *aabb_src ){ + int i; + vec_t min, max, displacement, difference; + for ( i = 0; i < 3; i++ ) + { + displacement = aabb_src->origin[i] - aabb->origin[i]; + difference = aabb_src->extents[i] - aabb->extents[i]; + if ( aabb->extents[i] < 0 + || difference >= fabs( displacement ) ) { + // 2nd contains 1st + aabb->extents[i] = aabb_src->extents[i]; + aabb->origin[i] = aabb_src->origin[i]; + } + else if ( aabb_src->extents[i] < 0 + || -difference >= fabs( displacement ) ) { + // 1st contains 2nd + continue; + } + else + { + // not contained + if ( displacement > 0 ) { + min = aabb->origin[i] - aabb->extents[i]; + max = aabb_src->origin[i] + aabb_src->extents[i]; + } + else + { + min = aabb_src->origin[i] - aabb_src->extents[i]; + max = aabb->origin[i] + aabb->extents[i]; + } + aabb->origin[i] = ( min + max ) * 0.5f; + aabb->extents[i] = max - aabb->origin[i]; + } + } } -void aabb_extend_by_vec3(aabb_t *aabb, vec3_t extension) -{ - VectorAdd(aabb->extents, extension, aabb->extents); +void aabb_extend_by_vec3( aabb_t *aabb, vec3_t extension ){ + VectorAdd( aabb->extents, extension, aabb->extents ); } -int aabb_test_point(const aabb_t *aabb, const vec3_t point) -{ - int i; - for(i=0; i<3; i++) - if(fabs(point[i] - aabb->origin[i]) >= aabb->extents[i]) - return 0; - return 1; +int aabb_test_point( const aabb_t *aabb, const vec3_t point ){ + int i; + for ( i = 0; i < 3; i++ ) + if ( fabs( point[i] - aabb->origin[i] ) >= aabb->extents[i] ) { + return 0; + } + return 1; } -int aabb_test_aabb(const aabb_t *aabb, const aabb_t *aabb_src) -{ - int i; - for (i=0; i<3; i++) - if ( fabs(aabb_src->origin[i] - aabb->origin[i]) > (fabs(aabb->extents[i]) + fabs(aabb_src->extents[i])) ) - return 0; - return 1; +int aabb_test_aabb( const aabb_t *aabb, const aabb_t *aabb_src ){ + int i; + for ( i = 0; i < 3; i++ ) + if ( fabs( aabb_src->origin[i] - aabb->origin[i] ) > ( fabs( aabb->extents[i] ) + fabs( aabb_src->extents[i] ) ) ) { + return 0; + } + return 1; } -int aabb_test_plane(const aabb_t *aabb, const float *plane) -{ - float fDist, fIntersect; - - // calc distance of origin from plane - fDist = DotProduct(plane, aabb->origin) + plane[3]; - - // calc extents distance relative to plane normal - fIntersect = (vec_t)(fabs(plane[0] * aabb->extents[0]) + fabs(plane[1] * aabb->extents[1]) + fabs(plane[2] * aabb->extents[2])); - // accept if origin is less than or equal to this distance - if (fabs(fDist) < fIntersect) return 1; // partially inside - else if (fDist < 0) return 2; // totally inside - return 0; // totally outside +int aabb_test_plane( const aabb_t *aabb, const float *plane ){ + float fDist, fIntersect; + + // calc distance of origin from plane + fDist = DotProduct( plane, aabb->origin ) + plane[3]; + + // calc extents distance relative to plane normal + fIntersect = (vec_t)( fabs( plane[0] * aabb->extents[0] ) + fabs( plane[1] * aabb->extents[1] ) + fabs( plane[2] * aabb->extents[2] ) ); + // accept if origin is less than or equal to this distance + if ( fabs( fDist ) < fIntersect ) { + return 1; // partially inside + } + else if ( fDist < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } -/* -Fast Ray-Box Intersection -by Andrew Woo -from "Graphics Gems", Academic Press, 1990 -*/ +/* + Fast Ray-Box Intersection + by Andrew Woo + from "Graphics Gems", Academic Press, 1990 + */ -#define NUMDIM 3 -#define RIGHT 0 -#define LEFT 1 -#define MIDDLE 2 +#define NUMDIM 3 +#define RIGHT 0 +#define LEFT 1 +#define MIDDLE 2 -int aabb_intersect_ray(const aabb_t *aabb, const ray_t *ray, vec3_t intersection) -{ +int aabb_intersect_ray( const aabb_t *aabb, const ray_t *ray, vec3_t intersection ){ int inside = 1; char quadrant[NUMDIM]; register int i; int whichPlane; double maxT[NUMDIM]; double candidatePlane[NUMDIM]; - - const float *origin = ray->origin; - const float *direction = ray->direction; + + const float *origin = ray->origin; + const float *direction = ray->direction; /* Find candidate planes; this loop can be avoided if - rays cast all from the eye(assume perpsective view) */ - for (i=0; iorigin[i] - aabb->extents[i])) - { + rays cast all from the eye(assume perpsective view) */ + for ( i = 0; i < NUMDIM; i++ ) + { + if ( origin[i] < ( aabb->origin[i] - aabb->extents[i] ) ) { quadrant[i] = LEFT; - candidatePlane[i] = (aabb->origin[i] - aabb->extents[i]); + candidatePlane[i] = ( aabb->origin[i] - aabb->extents[i] ); inside = 0; } - else if (origin[i] > (aabb->origin[i] + aabb->extents[i])) - { + else if ( origin[i] > ( aabb->origin[i] + aabb->extents[i] ) ) { quadrant[i] = RIGHT; - candidatePlane[i] = (aabb->origin[i] + aabb->extents[i]); + candidatePlane[i] = ( aabb->origin[i] + aabb->extents[i] ); inside = 0; } - else - { + else + { quadrant[i] = MIDDLE; - } - } + } + } /* Ray origin inside bounding box */ - if(inside == 1) - { - VectorCopy(ray->origin, intersection); + if ( inside == 1 ) { + VectorCopy( ray->origin, intersection ); return 1; } /* Calculate T distances to candidate planes */ - for (i = 0; i < NUMDIM; i++) - { - if (quadrant[i] != MIDDLE && direction[i] !=0.) - maxT[i] = (candidatePlane[i] - origin[i]) / direction[i]; - else + for ( i = 0; i < NUMDIM; i++ ) + { + if ( quadrant[i] != MIDDLE && direction[i] != 0. ) { + maxT[i] = ( candidatePlane[i] - origin[i] ) / direction[i]; + } + else{ maxT[i] = -1.; - } + } + } /* Get largest of the maxT's for final choice of intersection */ whichPlane = 0; - for (i = 1; i < NUMDIM; i++) - if (maxT[whichPlane] < maxT[i]) + for ( i = 1; i < NUMDIM; i++ ) + if ( maxT[whichPlane] < maxT[i] ) { whichPlane = i; + } /* Check final candidate actually inside box */ - if (maxT[whichPlane] < 0.) - return 0; - for (i = 0; i < NUMDIM; i++) - { - if (whichPlane != i) - { - intersection[i] = (vec_t)(origin[i] + maxT[whichPlane] * direction[i]); - if (fabs(intersection[i] - aabb->origin[i]) > aabb->extents[i]) + if ( maxT[whichPlane] < 0. ) { + return 0; + } + for ( i = 0; i < NUMDIM; i++ ) + { + if ( whichPlane != i ) { + intersection[i] = (vec_t)( origin[i] + maxT[whichPlane] * direction[i] ); + if ( fabs( intersection[i] - aabb->origin[i] ) > aabb->extents[i] ) { return 0; + } } - else - { + else + { intersection[i] = (vec_t)candidatePlane[i]; } - } + } - return 1; /* ray hits box */ + return 1; /* ray hits box */ } -int aabb_test_ray(const aabb_t* aabb, const ray_t* ray) -{ - vec3_t displacement, ray_absolute; - vec_t f; - - displacement[0] = ray->origin[0] - aabb->origin[0]; - if(fabs(displacement[0]) > aabb->extents[0] && displacement[0] * ray->direction[0] >= 0.0f) - return 0; - - displacement[1] = ray->origin[1] - aabb->origin[1]; - if(fabs(displacement[1]) > aabb->extents[1] && displacement[1] * ray->direction[1] >= 0.0f) - return 0; - - displacement[2] = ray->origin[2] - aabb->origin[2]; - if(fabs(displacement[2]) > aabb->extents[2] && displacement[2] * ray->direction[2] >= 0.0f) - return 0; - - ray_absolute[0] = (float)fabs(ray->direction[0]); - ray_absolute[1] = (float)fabs(ray->direction[1]); - ray_absolute[2] = (float)fabs(ray->direction[2]); - - f = ray->direction[1] * displacement[2] - ray->direction[2] * displacement[1]; - if((float)fabs(f) > aabb->extents[1] * ray_absolute[2] + aabb->extents[2] * ray_absolute[1]) - return 0; - - f = ray->direction[2] * displacement[0] - ray->direction[0] * displacement[2]; - if((float)fabs(f) > aabb->extents[0] * ray_absolute[2] + aabb->extents[2] * ray_absolute[0]) - return 0; - - f = ray->direction[0] * displacement[1] - ray->direction[1] * displacement[0]; - if((float)fabs(f) > aabb->extents[0] * ray_absolute[1] + aabb->extents[1] * ray_absolute[0]) - return 0; - - return 1; +int aabb_test_ray( const aabb_t* aabb, const ray_t* ray ){ + vec3_t displacement, ray_absolute; + vec_t f; + + displacement[0] = ray->origin[0] - aabb->origin[0]; + if ( fabs( displacement[0] ) > aabb->extents[0] && displacement[0] * ray->direction[0] >= 0.0f ) { + return 0; + } + + displacement[1] = ray->origin[1] - aabb->origin[1]; + if ( fabs( displacement[1] ) > aabb->extents[1] && displacement[1] * ray->direction[1] >= 0.0f ) { + return 0; + } + + displacement[2] = ray->origin[2] - aabb->origin[2]; + if ( fabs( displacement[2] ) > aabb->extents[2] && displacement[2] * ray->direction[2] >= 0.0f ) { + return 0; + } + + ray_absolute[0] = (float)fabs( ray->direction[0] ); + ray_absolute[1] = (float)fabs( ray->direction[1] ); + ray_absolute[2] = (float)fabs( ray->direction[2] ); + + f = ray->direction[1] * displacement[2] - ray->direction[2] * displacement[1]; + if ( (float)fabs( f ) > aabb->extents[1] * ray_absolute[2] + aabb->extents[2] * ray_absolute[1] ) { + return 0; + } + + f = ray->direction[2] * displacement[0] - ray->direction[0] * displacement[2]; + if ( (float)fabs( f ) > aabb->extents[0] * ray_absolute[2] + aabb->extents[2] * ray_absolute[0] ) { + return 0; + } + + f = ray->direction[0] * displacement[1] - ray->direction[1] * displacement[0]; + if ( (float)fabs( f ) > aabb->extents[0] * ray_absolute[1] + aabb->extents[1] * ray_absolute[0] ) { + return 0; + } + + return 1; } -void aabb_orthogonal_transform(aabb_t* dst, const aabb_t* src, const m4x4_t transform) -{ - VectorCopy(src->origin, dst->origin); - m4x4_transform_point(transform, dst->origin); - - dst->extents[0] = (vec_t)(fabs(transform[0] * src->extents[0]) - + fabs(transform[4] * src->extents[1]) - + fabs(transform[8] * src->extents[2])); - dst->extents[1] = (vec_t)(fabs(transform[1] * src->extents[0]) - + fabs(transform[5] * src->extents[1]) - + fabs(transform[9] * src->extents[2])); - dst->extents[2] = (vec_t)(fabs(transform[2] * src->extents[0]) - + fabs(transform[6] * src->extents[1]) - + fabs(transform[10] * src->extents[2])); +void aabb_orthogonal_transform( aabb_t* dst, const aabb_t* src, const m4x4_t transform ){ + VectorCopy( src->origin, dst->origin ); + m4x4_transform_point( transform, dst->origin ); + + dst->extents[0] = (vec_t)( fabs( transform[0] * src->extents[0] ) + + fabs( transform[4] * src->extents[1] ) + + fabs( transform[8] * src->extents[2] ) ); + dst->extents[1] = (vec_t)( fabs( transform[1] * src->extents[0] ) + + fabs( transform[5] * src->extents[1] ) + + fabs( transform[9] * src->extents[2] ) ); + dst->extents[2] = (vec_t)( fabs( transform[2] * src->extents[0] ) + + fabs( transform[6] * src->extents[1] ) + + fabs( transform[10] * src->extents[2] ) ); } -void aabb_for_bbox(aabb_t *aabb, const bbox_t *bbox) -{ +void aabb_for_bbox( aabb_t *aabb, const bbox_t *bbox ){ int i; vec3_t temp[3]; - VectorCopy(bbox->aabb.origin, aabb->origin); + VectorCopy( bbox->aabb.origin, aabb->origin ); // calculate the AABB extents in local coord space from the OBB extents and axes - VectorScale(bbox->axes[0], bbox->aabb.extents[0], temp[0]); - VectorScale(bbox->axes[1], bbox->aabb.extents[1], temp[1]); - VectorScale(bbox->axes[2], bbox->aabb.extents[2], temp[2]); - for(i=0;i<3;i++) aabb->extents[i] = (vec_t)(fabs(temp[0][i]) + fabs(temp[1][i]) + fabs(temp[2][i])); + VectorScale( bbox->axes[0], bbox->aabb.extents[0], temp[0] ); + VectorScale( bbox->axes[1], bbox->aabb.extents[1], temp[1] ); + VectorScale( bbox->axes[2], bbox->aabb.extents[2], temp[2] ); + for ( i = 0; i < 3; i++ ) aabb->extents[i] = (vec_t)( fabs( temp[0][i] ) + fabs( temp[1][i] ) + fabs( temp[2][i] ) ); } -void aabb_for_area(aabb_t *aabb, vec3_t area_tl, vec3_t area_br, int axis) -{ - aabb_clear(aabb); - aabb->extents[axis] = FLT_MAX; - aabb_extend_by_point(aabb, area_tl); - aabb_extend_by_point(aabb, area_br); +void aabb_for_area( aabb_t *aabb, vec3_t area_tl, vec3_t area_br, int axis ){ + aabb_clear( aabb ); + aabb->extents[axis] = FLT_MAX; + aabb_extend_by_point( aabb, area_tl ); + aabb_extend_by_point( aabb, area_br ); } -int aabb_oriented_intersect_plane(const aabb_t *aabb, const m4x4_t transform, const vec_t* plane) -{ - vec_t fDist, fIntersect; - - // calc distance of origin from plane - fDist = DotProduct(plane, aabb->origin) + plane[3]; - - // calc extents distance relative to plane normal - fIntersect = (vec_t)(fabs(aabb->extents[0] * DotProduct(plane, transform)) - + fabs(aabb->extents[1] * DotProduct(plane, transform+4)) - + fabs(aabb->extents[2] * DotProduct(plane, transform+8))); - // accept if origin is less than this distance - if (fabs(fDist) < fIntersect) return 1; // partially inside - else if (fDist < 0) return 2; // totally inside - return 0; // totally outside +int aabb_oriented_intersect_plane( const aabb_t *aabb, const m4x4_t transform, const vec_t* plane ){ + vec_t fDist, fIntersect; + + // calc distance of origin from plane + fDist = DotProduct( plane, aabb->origin ) + plane[3]; + + // calc extents distance relative to plane normal + fIntersect = (vec_t)( fabs( aabb->extents[0] * DotProduct( plane, transform ) ) + + fabs( aabb->extents[1] * DotProduct( plane, transform + 4 ) ) + + fabs( aabb->extents[2] * DotProduct( plane, transform + 8 ) ) ); + // accept if origin is less than this distance + if ( fabs( fDist ) < fIntersect ) { + return 1; // partially inside + } + else if ( fDist < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } -void aabb_corners(const aabb_t* aabb, vec3_t corners[8]) -{ - vec3_t min, max; - VectorSubtract(aabb->origin, aabb->extents, min); - VectorAdd(aabb->origin, aabb->extents, max); - VectorSet(corners[0], min[0], max[1], max[2]); - VectorSet(corners[1], max[0], max[1], max[2]); - VectorSet(corners[2], max[0], min[1], max[2]); - VectorSet(corners[3], min[0], min[1], max[2]); - VectorSet(corners[4], min[0], max[1], min[2]); - VectorSet(corners[5], max[0], max[1], min[2]); - VectorSet(corners[6], max[0], min[1], min[2]); - VectorSet(corners[7], min[0], min[1], min[2]); +void aabb_corners( const aabb_t* aabb, vec3_t corners[8] ){ + vec3_t min, max; + VectorSubtract( aabb->origin, aabb->extents, min ); + VectorAdd( aabb->origin, aabb->extents, max ); + VectorSet( corners[0], min[0], max[1], max[2] ); + VectorSet( corners[1], max[0], max[1], max[2] ); + VectorSet( corners[2], max[0], min[1], max[2] ); + VectorSet( corners[3], min[0], min[1], max[2] ); + VectorSet( corners[4], min[0], max[1], min[2] ); + VectorSet( corners[5], max[0], max[1], min[2] ); + VectorSet( corners[6], max[0], min[1], min[2] ); + VectorSet( corners[7], min[0], min[1], min[2] ); } -void bbox_update_radius(bbox_t *bbox) -{ - bbox->radius = VectorLength(bbox->aabb.extents); +void bbox_update_radius( bbox_t *bbox ){ + bbox->radius = VectorLength( bbox->aabb.extents ); } -void aabb_for_transformed_aabb(aabb_t* dst, const aabb_t* src, const m4x4_t transform) -{ - if(src->extents[0] < 0 - || src->extents[1] < 0 - || src->extents[2] < 0) - { - aabb_clear(dst); - return; - } - - VectorCopy(src->origin, dst->origin); - m4x4_transform_point(transform, dst->origin); - - dst->extents[0] = (vec_t)(fabs(transform[0] * src->extents[0]) - + fabs(transform[4] * src->extents[1]) - + fabs(transform[8] * src->extents[2])); - dst->extents[1] = (vec_t)(fabs(transform[1] * src->extents[0]) - + fabs(transform[5] * src->extents[1]) - + fabs(transform[9] * src->extents[2])); - dst->extents[2] = (vec_t)(fabs(transform[2] * src->extents[0]) - + fabs(transform[6] * src->extents[1]) - + fabs(transform[10] * src->extents[2])); +void aabb_for_transformed_aabb( aabb_t* dst, const aabb_t* src, const m4x4_t transform ){ + if ( src->extents[0] < 0 + || src->extents[1] < 0 + || src->extents[2] < 0 ) { + aabb_clear( dst ); + return; + } + + VectorCopy( src->origin, dst->origin ); + m4x4_transform_point( transform, dst->origin ); + + dst->extents[0] = (vec_t)( fabs( transform[0] * src->extents[0] ) + + fabs( transform[4] * src->extents[1] ) + + fabs( transform[8] * src->extents[2] ) ); + dst->extents[1] = (vec_t)( fabs( transform[1] * src->extents[0] ) + + fabs( transform[5] * src->extents[1] ) + + fabs( transform[9] * src->extents[2] ) ); + dst->extents[2] = (vec_t)( fabs( transform[2] * src->extents[0] ) + + fabs( transform[6] * src->extents[1] ) + + fabs( transform[10] * src->extents[2] ) ); } -void bbox_for_oriented_aabb(bbox_t *bbox, const aabb_t *aabb, const m4x4_t matrix, const vec3_t euler, const vec3_t scale) -{ +void bbox_for_oriented_aabb( bbox_t *bbox, const aabb_t *aabb, const m4x4_t matrix, const vec3_t euler, const vec3_t scale ){ double rad[3]; double pi_180 = Q_PI / 180; - double A, B, C, D, E, F, AD, BD; - - VectorCopy(aabb->origin, bbox->aabb.origin); - - m4x4_transform_point(matrix, bbox->aabb.origin); + double A, B, C, D, E, F, AD, BD; + + VectorCopy( aabb->origin, bbox->aabb.origin ); + + m4x4_transform_point( matrix, bbox->aabb.origin ); bbox->aabb.extents[0] = aabb->extents[0] * scale[0]; bbox->aabb.extents[1] = aabb->extents[1] * scale[1]; bbox->aabb.extents[2] = aabb->extents[2] * scale[2]; - rad[0] = euler[0] * pi_180; + rad[0] = euler[0] * pi_180; rad[1] = euler[1] * pi_180; rad[2] = euler[2] * pi_180; - A = cos(rad[0]); - B = sin(rad[0]); - C = cos(rad[1]); - D = sin(rad[1]); - E = cos(rad[2]); - F = sin(rad[2]); - - AD = A * -D; - BD = B * -D; - - bbox->axes[0][0] = (vec_t)(C*E); - bbox->axes[0][1] = (vec_t)(-BD*E + A*F); - bbox->axes[0][2] = (vec_t)(AD*E + B*F); - bbox->axes[1][0] = (vec_t)(-C*F); - bbox->axes[1][1] = (vec_t)(BD*F + A*E); - bbox->axes[1][2] = (vec_t)(-AD*F + B*E); + A = cos( rad[0] ); + B = sin( rad[0] ); + C = cos( rad[1] ); + D = sin( rad[1] ); + E = cos( rad[2] ); + F = sin( rad[2] ); + + AD = A * -D; + BD = B * -D; + + bbox->axes[0][0] = (vec_t)( C * E ); + bbox->axes[0][1] = (vec_t)( -BD * E + A * F ); + bbox->axes[0][2] = (vec_t)( AD * E + B * F ); + bbox->axes[1][0] = (vec_t)( -C * F ); + bbox->axes[1][1] = (vec_t)( BD * F + A * E ); + bbox->axes[1][2] = (vec_t)( -AD * F + B * E ); bbox->axes[2][0] = (vec_t)D; - bbox->axes[2][1] = (vec_t)(-B*C); - bbox->axes[2][2] = (vec_t)(A*C); + bbox->axes[2][1] = (vec_t)( -B * C ); + bbox->axes[2][2] = (vec_t)( A * C ); - bbox_update_radius(bbox); + bbox_update_radius( bbox ); } -int bbox_intersect_plane(const bbox_t *bbox, const vec_t* plane) -{ - vec_t fDist, fIntersect; +int bbox_intersect_plane( const bbox_t *bbox, const vec_t* plane ){ + vec_t fDist, fIntersect; - // calc distance of origin from plane - fDist = DotProduct(plane, bbox->aabb.origin) + plane[3]; + // calc distance of origin from plane + fDist = DotProduct( plane, bbox->aabb.origin ) + plane[3]; // trivial accept/reject using bounding sphere - if (fabs(fDist) > bbox->radius) - { - if (fDist < 0) + if ( fabs( fDist ) > bbox->radius ) { + if ( fDist < 0 ) { return 2; // totally inside - else + } + else{ return 0; // totally outside + } } - // calc extents distance relative to plane normal - fIntersect = (vec_t)(fabs(bbox->aabb.extents[0] * DotProduct(plane, bbox->axes[0])) - + fabs(bbox->aabb.extents[1] * DotProduct(plane, bbox->axes[1])) - + fabs(bbox->aabb.extents[2] * DotProduct(plane, bbox->axes[2]))); - // accept if origin is less than this distance - if (fabs(fDist) < fIntersect) return 1; // partially inside - else if (fDist < 0) return 2; // totally inside - return 0; // totally outside + // calc extents distance relative to plane normal + fIntersect = (vec_t)( fabs( bbox->aabb.extents[0] * DotProduct( plane, bbox->axes[0] ) ) + + fabs( bbox->aabb.extents[1] * DotProduct( plane, bbox->axes[1] ) ) + + fabs( bbox->aabb.extents[2] * DotProduct( plane, bbox->axes[2] ) ) ); + // accept if origin is less than this distance + if ( fabs( fDist ) < fIntersect ) { + return 1; // partially inside + } + else if ( fDist < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } diff --git a/libs/mathlib/line.c b/libs/mathlib/line.c index 41b868fb..a50337fb 100644 --- a/libs/mathlib/line.c +++ b/libs/mathlib/line.c @@ -1,41 +1,43 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "mathlib.h" -void line_construct_for_vec3(line_t *line, const vec3_t start, const vec3_t end) -{ - VectorMid(start, end, line->origin); - VectorSubtract(end, line->origin, line->extents); +void line_construct_for_vec3( line_t *line, const vec3_t start, const vec3_t end ){ + VectorMid( start, end, line->origin ); + VectorSubtract( end, line->origin, line->extents ); } -int line_test_plane(const line_t* line, const vec4_t plane) -{ - float fDist; - - // calc distance of origin from plane - fDist = DotProduct(plane, line->origin) + plane[3]; - - // accept if origin is less than or equal to this distance - if (fabs(fDist) < fabs(DotProduct(plane, line->extents))) return 1; // partially inside - else if (fDist < 0) return 2; // totally inside - return 0; // totally outside +int line_test_plane( const line_t* line, const vec4_t plane ){ + float fDist; + + // calc distance of origin from plane + fDist = DotProduct( plane, line->origin ) + plane[3]; + + // accept if origin is less than or equal to this distance + if ( fabs( fDist ) < fabs( DotProduct( plane, line->extents ) ) ) { + return 1; // partially inside + } + else if ( fDist < 0 ) { + return 2; // totally inside + } + return 0; // totally outside } diff --git a/libs/mathlib/m4x4.c b/libs/mathlib/m4x4.c index 3b114610..cb1ad87e 100644 --- a/libs/mathlib/m4x4.c +++ b/libs/mathlib/m4x4.c @@ -1,676 +1,652 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "mathlib.h" const m4x4_t g_m4x4_identity = { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1, + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1, }; -void m4x4_identity(m4x4_t matrix) -{ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = - matrix[12] = matrix[13] = matrix[14] = 0; +void m4x4_identity( m4x4_t matrix ){ + matrix[1] = matrix[2] = matrix[3] = + matrix[4] = matrix[6] = matrix[7] = + matrix[8] = matrix[9] = matrix[11] = + matrix[12] = matrix[13] = matrix[14] = 0; - matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; + matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; } -m4x4Handedness_t m4x4_handedness(const m4x4_t matrix) -{ - vec3_t cross; - CrossProduct(matrix+0, matrix+4, cross); - return (DotProduct(matrix+8, cross) < 0) ? eLeftHanded : eRightHanded; +m4x4Handedness_t m4x4_handedness( const m4x4_t matrix ){ + vec3_t cross; + CrossProduct( matrix + 0, matrix + 4, cross ); + return ( DotProduct( matrix + 8, cross ) < 0 ) ? eLeftHanded : eRightHanded; } -void m4x4_assign(m4x4_t matrix, const m4x4_t other) -{ - M4X4_COPY(matrix, other); +void m4x4_assign( m4x4_t matrix, const m4x4_t other ){ + M4X4_COPY( matrix, other ); } -void m4x4_translation_for_vec3(m4x4_t matrix, const vec3_t translation) -{ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = 0; +void m4x4_translation_for_vec3( m4x4_t matrix, const vec3_t translation ){ + matrix[1] = matrix[2] = matrix[3] = + matrix[4] = matrix[6] = matrix[7] = + matrix[8] = matrix[9] = matrix[11] = 0; - matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; + matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; - matrix[12] = translation[0]; - matrix[13] = translation[1]; - matrix[14] = translation[2]; + matrix[12] = translation[0]; + matrix[13] = translation[1]; + matrix[14] = translation[2]; } /* -clockwise rotation around X, Y, Z, facing along axis - 1 0 0 cy 0 sy cz sz 0 - 0 cx sx 0 1 0 -sz cz 0 - 0 -sx cx -sy 0 cy 0 0 1 + clockwise rotation around X, Y, Z, facing along axis + 1 0 0 cy 0 sy cz sz 0 + 0 cx sx 0 1 0 -sz cz 0 + 0 -sx cx -sy 0 cy 0 0 1 -rows of Z by cols of Y - cy*cz -sy*cz+sz -sy*sz+cz --sz*cy -sz*sy+cz + rows of Z by cols of Y + cy*cz -sy*cz+sz -sy*sz+cz + -sz*cy -sz*sy+cz - .. or something like that.. + .. or something like that.. -final rotation is Z * Y * X - cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz --cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz - sy -sx*cy cx*cy -*/ + final rotation is Z * Y * X + cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz + -cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz + sy -sx*cy cx*cy + */ /* transposed -| cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | -| sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | -| -cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | -*/ -void m4x4_rotation_for_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order) -{ - double cx, sx, cy, sy, cz, sz; - - cx = cos(DEG2RAD(euler[0])); - sx = sin(DEG2RAD(euler[0])); - cy = cos(DEG2RAD(euler[1])); - sy = sin(DEG2RAD(euler[1])); - cz = cos(DEG2RAD(euler[2])); - sz = sin(DEG2RAD(euler[2])); - - switch(order) - { - case eXYZ: + | cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | + | sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | + | -cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | + */ +void m4x4_rotation_for_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ){ + double cx, sx, cy, sy, cz, sz; + + cx = cos( DEG2RAD( euler[0] ) ); + sx = sin( DEG2RAD( euler[0] ) ); + cy = cos( DEG2RAD( euler[1] ) ); + sy = sin( DEG2RAD( euler[1] ) ); + cz = cos( DEG2RAD( euler[2] ) ); + sz = sin( DEG2RAD( euler[2] ) ); + + switch ( order ) + { + case eXYZ: #if 1 - { - matrix[0] = (vec_t)(cy*cz); - matrix[1] = (vec_t)(cy*sz); - matrix[2] = (vec_t)-sy; - matrix[4] = (vec_t)(sx*sy*cz + cx*-sz); - matrix[5] = (vec_t)(sx*sy*sz + cx*cz); - matrix[6] = (vec_t)(sx*cy); - matrix[8] = (vec_t)(cx*sy*cz + sx*sz); - matrix[9] = (vec_t)(cx*sy*sz + -sx*cz); - matrix[10] = (vec_t)(cx*cy); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; + { + matrix[0] = (vec_t)( cy * cz ); + matrix[1] = (vec_t)( cy * sz ); + matrix[2] = (vec_t)-sy; + matrix[4] = (vec_t)( sx * sy * cz + cx * -sz ); + matrix[5] = (vec_t)( sx * sy * sz + cx * cz ); + matrix[6] = (vec_t)( sx * cy ); + matrix[8] = (vec_t)( cx * sy * cz + sx * sz ); + matrix[9] = (vec_t)( cx * sy * sz + -sx * cz ); + matrix[10] = (vec_t)( cx * cy ); + } + + matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; + matrix[15] = 1; #else - m4x4_identity(matrix); - matrix[5] =(vec_t) cx; matrix[6] =(vec_t) sx; - matrix[9] =(vec_t)-sx; matrix[10]=(vec_t) cx; - - { - m4x4_t temp; - m4x4_identity(temp); - temp[0] =(vec_t) cy; temp[2] =(vec_t)-sy; - temp[8] =(vec_t) sy; temp[10]=(vec_t) cy; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[0] =(vec_t) cz; temp[1] =(vec_t) sz; - temp[4] =(vec_t)-sz; temp[5] =(vec_t) cz; - m4x4_premultiply_by_m4x4(matrix, temp); - } + m4x4_identity( matrix ); + matrix[5] = (vec_t) cx; matrix[6] = (vec_t) sx; + matrix[9] = (vec_t)-sx; matrix[10] = (vec_t) cx; + + { + m4x4_t temp; + m4x4_identity( temp ); + temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; + temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; + temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; + m4x4_premultiply_by_m4x4( matrix, temp ); + } #endif - break; - - case eYZX: - m4x4_identity(matrix); - matrix[0] =(vec_t) cy; matrix[2] =(vec_t)-sy; - matrix[8] =(vec_t) sy; matrix[10]=(vec_t) cy; - - { - m4x4_t temp; - m4x4_identity(temp); - temp[5] =(vec_t) cx; temp[6] =(vec_t) sx; - temp[9] =(vec_t)-sx; temp[10]=(vec_t) cx; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[0] =(vec_t) cz; temp[1] =(vec_t) sz; - temp[4] =(vec_t)-sz; temp[5] =(vec_t) cz; - m4x4_premultiply_by_m4x4(matrix, temp); - } - break; - - case eZXY: - m4x4_identity(matrix); - matrix[0] =(vec_t) cz; matrix[1] =(vec_t) sz; - matrix[4] =(vec_t)-sz; matrix[5] =(vec_t) cz; - - { - m4x4_t temp; - m4x4_identity(temp); - temp[5] =(vec_t) cx; temp[6] =(vec_t) sx; - temp[9] =(vec_t)-sx; temp[10]=(vec_t) cx; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[0] =(vec_t) cy; temp[2] =(vec_t)-sy; - temp[8] =(vec_t) sy; temp[10]=(vec_t) cy; - m4x4_premultiply_by_m4x4(matrix, temp); - } - break; - - case eXZY: - m4x4_identity(matrix); - matrix[5] =(vec_t) cx; matrix[6] =(vec_t) sx; - matrix[9] =(vec_t)-sx; matrix[10]=(vec_t) cx; - - { - m4x4_t temp; - m4x4_identity(temp); - temp[0] =(vec_t) cz; temp[1] =(vec_t) sz; - temp[4] =(vec_t)-sz; temp[5] =(vec_t) cz; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[0] =(vec_t) cy; temp[2] =(vec_t)-sy; - temp[8] =(vec_t) sy; temp[10]=(vec_t) cy; - m4x4_premultiply_by_m4x4(matrix, temp); - } - break; - - case eYXZ: + break; + + case eYZX: + m4x4_identity( matrix ); + matrix[0] = (vec_t) cy; matrix[2] = (vec_t)-sy; + matrix[8] = (vec_t) sy; matrix[10] = (vec_t) cy; + + { + m4x4_t temp; + m4x4_identity( temp ); + temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; + temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; + temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; + m4x4_premultiply_by_m4x4( matrix, temp ); + } + break; + + case eZXY: + m4x4_identity( matrix ); + matrix[0] = (vec_t) cz; matrix[1] = (vec_t) sz; + matrix[4] = (vec_t)-sz; matrix[5] = (vec_t) cz; + + { + m4x4_t temp; + m4x4_identity( temp ); + temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; + temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; + temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; + m4x4_premultiply_by_m4x4( matrix, temp ); + } + break; + + case eXZY: + m4x4_identity( matrix ); + matrix[5] = (vec_t) cx; matrix[6] = (vec_t) sx; + matrix[9] = (vec_t)-sx; matrix[10] = (vec_t) cx; + + { + m4x4_t temp; + m4x4_identity( temp ); + temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; + temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; + temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; + m4x4_premultiply_by_m4x4( matrix, temp ); + } + break; + + case eYXZ: /* transposed -| cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | -| cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | -| cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | -*/ + | cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | + | cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | + | cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | + */ #if 1 - { - matrix[0] = (vec_t)(cy*cz + sx*sy*-sz); - matrix[1] = (vec_t)(cy*sz + sx*sy*cz); - matrix[2] = (vec_t)(-cx*sy); - matrix[4] = (vec_t)(cx*-sz); - matrix[5] = (vec_t)(cx*cz); - matrix[6] = (vec_t)(sx); - matrix[8] = (vec_t)(sy*cz + -sx*cy*-sz); - matrix[9] = (vec_t)(sy*sz + -sx*cy*cz); - matrix[10] = (vec_t)(cx*cy); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; + { + matrix[0] = (vec_t)( cy * cz + sx * sy * -sz ); + matrix[1] = (vec_t)( cy * sz + sx * sy * cz ); + matrix[2] = (vec_t)( -cx * sy ); + matrix[4] = (vec_t)( cx * -sz ); + matrix[5] = (vec_t)( cx * cz ); + matrix[6] = (vec_t)( sx ); + matrix[8] = (vec_t)( sy * cz + -sx * cy * -sz ); + matrix[9] = (vec_t)( sy * sz + -sx * cy * cz ); + matrix[10] = (vec_t)( cx * cy ); + } + + matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; + matrix[15] = 1; #else - m4x4_identity(matrix); - matrix[0] =(vec_t) cy; matrix[2] =(vec_t)-sy; - matrix[8] =(vec_t) sy; matrix[10]=(vec_t) cy; - - { - m4x4_t temp; - m4x4_identity(temp); - temp[5] =(vec_t) cx; temp[6] =(vec_t) sx; - temp[9] =(vec_t)-sx; temp[10]=(vec_t) cx; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[0] =(vec_t) cz; temp[1] =(vec_t) sz; - temp[4] =(vec_t)-sz; temp[5] =(vec_t) cz; - m4x4_premultiply_by_m4x4(matrix, temp); - } + m4x4_identity( matrix ); + matrix[0] = (vec_t) cy; matrix[2] = (vec_t)-sy; + matrix[8] = (vec_t) sy; matrix[10] = (vec_t) cy; + + { + m4x4_t temp; + m4x4_identity( temp ); + temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; + temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; + temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; + m4x4_premultiply_by_m4x4( matrix, temp ); + } #endif - break; + break; - case eZYX: + case eZYX: #if 1 - { - matrix[0] = (vec_t)(cy*cz); - matrix[4] = (vec_t)(cy*-sz); - matrix[8] = (vec_t)sy; - matrix[1] = (vec_t)(sx*sy*cz + cx*sz); - matrix[5] = (vec_t)(sx*sy*-sz + cx*cz); - matrix[9] = (vec_t)(-sx*cy); - matrix[2] = (vec_t)(cx*-sy*cz + sx*sz); - matrix[6] = (vec_t)(cx*-sy*-sz + sx*cz); - matrix[10] = (vec_t)(cx*cy); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; + { + matrix[0] = (vec_t)( cy * cz ); + matrix[4] = (vec_t)( cy * -sz ); + matrix[8] = (vec_t)sy; + matrix[1] = (vec_t)( sx * sy * cz + cx * sz ); + matrix[5] = (vec_t)( sx * sy * -sz + cx * cz ); + matrix[9] = (vec_t)( -sx * cy ); + matrix[2] = (vec_t)( cx * -sy * cz + sx * sz ); + matrix[6] = (vec_t)( cx * -sy * -sz + sx * cz ); + matrix[10] = (vec_t)( cx * cy ); + } + + matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; + matrix[15] = 1; #else - m4x4_identity(matrix); - matrix[0] =(vec_t) cz; matrix[1] =(vec_t) sz; - matrix[4] =(vec_t)-sz; matrix[5] =(vec_t) cz; - { - m4x4_t temp; - m4x4_identity(temp); - temp[0] =(vec_t) cy; temp[2] =(vec_t)-sy; - temp[8] =(vec_t) sy; temp[10]=(vec_t) cy; - m4x4_premultiply_by_m4x4(matrix, temp); - m4x4_identity(temp); - temp[5] =(vec_t) cx; temp[6] =(vec_t) sx; - temp[9] =(vec_t)-sx; temp[10]=(vec_t) cx; - m4x4_premultiply_by_m4x4(matrix, temp); - } + m4x4_identity( matrix ); + matrix[0] = (vec_t) cz; matrix[1] = (vec_t) sz; + matrix[4] = (vec_t)-sz; matrix[5] = (vec_t) cz; + { + m4x4_t temp; + m4x4_identity( temp ); + temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; + temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; + m4x4_premultiply_by_m4x4( matrix, temp ); + m4x4_identity( temp ); + temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; + temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; + m4x4_premultiply_by_m4x4( matrix, temp ); + } #endif - break; + break; - } + } } -void m4x4_scale_for_vec3(m4x4_t matrix, const vec3_t scale) -{ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = - matrix[12] = matrix[13] = matrix[14] = 0; +void m4x4_scale_for_vec3( m4x4_t matrix, const vec3_t scale ){ + matrix[1] = matrix[2] = matrix[3] = + matrix[4] = matrix[6] = matrix[7] = + matrix[8] = matrix[9] = matrix[11] = + matrix[12] = matrix[13] = matrix[14] = 0; - matrix[15] = 1; + matrix[15] = 1; - matrix[0] = scale[0]; - matrix[5] = scale[1]; - matrix[10] = scale[2]; + matrix[0] = scale[0]; + matrix[5] = scale[1]; + matrix[10] = scale[2]; } -void m4x4_rotation_for_quat(m4x4_t matrix, const vec4_t quat) -{ +void m4x4_rotation_for_quat( m4x4_t matrix, const vec4_t quat ){ #if 0 - const double xx = quat[0] * quat[0]; - const double xy = quat[0] * quat[1]; - const double xz = quat[0] * quat[2]; - const double xw = quat[0] * quat[3]; + const double xx = quat[0] * quat[0]; + const double xy = quat[0] * quat[1]; + const double xz = quat[0] * quat[2]; + const double xw = quat[0] * quat[3]; - const double yy = quat[1] * quat[1]; - const double yz = quat[1] * quat[2]; - const double yw = quat[1] * quat[3]; + const double yy = quat[1] * quat[1]; + const double yz = quat[1] * quat[2]; + const double yw = quat[1] * quat[3]; - const double zz = quat[2] * quat[2]; - const double zw = quat[2] * quat[3]; + const double zz = quat[2] * quat[2]; + const double zw = quat[2] * quat[3]; - matrix[0] = 1 - 2 * ( yy + zz ); - matrix[4] = 2 * ( xy - zw ); - matrix[8] = 2 * ( xz + yw ); + matrix[0] = 1 - 2 * ( yy + zz ); + matrix[4] = 2 * ( xy - zw ); + matrix[8] = 2 * ( xz + yw ); - matrix[1] = 2 * ( xy + zw ); - matrix[5] = 1 - 2 * ( xx + zz ); - matrix[9] = 2 * ( yz - xw ); + matrix[1] = 2 * ( xy + zw ); + matrix[5] = 1 - 2 * ( xx + zz ); + matrix[9] = 2 * ( yz - xw ); - matrix[2] = 2 * ( xz - yw ); - matrix[6] = 2 * ( yz + xw ); - matrix[10] = 1 - 2 * ( xx + yy ); + matrix[2] = 2 * ( xz - yw ); + matrix[6] = 2 * ( yz + xw ); + matrix[10] = 1 - 2 * ( xx + yy ); #else - const double x2 = quat[0] + quat[0]; - const double y2 = quat[1] + quat[1]; - const double z2 = quat[2] + quat[2]; - const double xx = quat[0] * x2; - const double xy = quat[0] * y2; - const double xz = quat[0] * z2; - const double yy = quat[1] * y2; - const double yz = quat[1] * z2; - const double zz = quat[2] * z2; - const double wx = quat[3] * x2; - const double wy = quat[3] * y2; - const double wz = quat[3] * z2; - - matrix[0] = (vec_t)( 1.0 - (yy + zz) ); - matrix[4] = (vec_t)(xy - wz); - matrix[8] = (vec_t)(xz + wy); - - matrix[1] = (vec_t)(xy + wz); - matrix[5] = (vec_t)( 1.0 - (xx + zz) ); - matrix[9] = (vec_t)(yz - wx); - - matrix[2] = (vec_t)(xz - wy); - matrix[6] = (vec_t)(yz + wx); - matrix[10] = (vec_t)( 1.0 - (xx + yy) ); + const double x2 = quat[0] + quat[0]; + const double y2 = quat[1] + quat[1]; + const double z2 = quat[2] + quat[2]; + const double xx = quat[0] * x2; + const double xy = quat[0] * y2; + const double xz = quat[0] * z2; + const double yy = quat[1] * y2; + const double yz = quat[1] * z2; + const double zz = quat[2] * z2; + const double wx = quat[3] * x2; + const double wy = quat[3] * y2; + const double wz = quat[3] * z2; + + matrix[0] = (vec_t)( 1.0 - ( yy + zz ) ); + matrix[4] = (vec_t)( xy - wz ); + matrix[8] = (vec_t)( xz + wy ); + + matrix[1] = (vec_t)( xy + wz ); + matrix[5] = (vec_t)( 1.0 - ( xx + zz ) ); + matrix[9] = (vec_t)( yz - wx ); + + matrix[2] = (vec_t)( xz - wy ); + matrix[6] = (vec_t)( yz + wx ); + matrix[10] = (vec_t)( 1.0 - ( xx + yy ) ); #endif - matrix[3] = matrix[7] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; - matrix[15] = 1; + matrix[3] = matrix[7] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; + matrix[15] = 1; } -void m4x4_rotation_for_axisangle(m4x4_t matrix, const vec3_t axis, double angle) -{ - vec4_t quat; - quat_for_axisangle(quat, axis, angle); - m4x4_rotation_for_quat(matrix, quat); +void m4x4_rotation_for_axisangle( m4x4_t matrix, const vec3_t axis, double angle ){ + vec4_t quat; + quat_for_axisangle( quat, axis, angle ); + m4x4_rotation_for_quat( matrix, quat ); } -void m4x4_frustum(m4x4_t matrix, - vec_t left, vec_t right, - vec_t bottom, vec_t top, - vec_t nearval, vec_t farval) -{ - matrix[0] = (vec_t)( (2*nearval) / (right-left) ); - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - - matrix[4] = 0; - matrix[5] = (vec_t)( (2*nearval) / (top-bottom) ); - matrix[6] = 0; - matrix[7] = 0; - - matrix[8] = (vec_t)( (right+left) / (right-left) ); - matrix[9] = (vec_t)( (top+bottom) / (top-bottom) ); - matrix[10] = (vec_t)( -(farval+nearval) / (farval-nearval) ); - matrix[11] =-1; - - matrix[12] = 0; - matrix[13] = 0; - matrix[14] = (vec_t)( -(2*farval*nearval) / (farval-nearval) ); - matrix[15] = 0; +void m4x4_frustum( m4x4_t matrix, + vec_t left, vec_t right, + vec_t bottom, vec_t top, + vec_t nearval, vec_t farval ){ + matrix[0] = (vec_t)( ( 2 * nearval ) / ( right - left ) ); + matrix[1] = 0; + matrix[2] = 0; + matrix[3] = 0; + + matrix[4] = 0; + matrix[5] = (vec_t)( ( 2 * nearval ) / ( top - bottom ) ); + matrix[6] = 0; + matrix[7] = 0; + + matrix[8] = (vec_t)( ( right + left ) / ( right - left ) ); + matrix[9] = (vec_t)( ( top + bottom ) / ( top - bottom ) ); + matrix[10] = (vec_t)( -( farval + nearval ) / ( farval - nearval ) ); + matrix[11] = -1; + + matrix[12] = 0; + matrix[13] = 0; + matrix[14] = (vec_t)( -( 2 * farval * nearval ) / ( farval - nearval ) ); + matrix[15] = 0; } -void m4x4_get_translation_vec3(const m4x4_t matrix, vec3_t translation) -{ - translation[0] = matrix[12]; +void m4x4_get_translation_vec3( const m4x4_t matrix, vec3_t translation ){ + translation[0] = matrix[12]; translation[1] = matrix[13]; translation[2] = matrix[14]; } -void m4x4_get_rotation_vec3(const m4x4_t matrix, vec3_t euler, eulerOrder_t order) -{ - double a, ca; - - switch(order) - { - case eXYZ: - a = asin(-matrix[2]); - ca = cos(a); - euler[1] = (vec_t)RAD2DEG(a); /* Calculate Y-axis angle */ - - if (fabs(ca) > 0.005) /* Gimbal lock? */ - { - /* No, so get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG(atan2(matrix[1] / ca, matrix[0]/ ca)); - - /* Get X-axis angle */ - euler[0] = (vec_t)RAD2DEG(atan2(matrix[6] / ca, matrix[10] / ca)); - } - else /* Gimbal lock has occurred */ - { - /* Set Z-axis angle to zero */ - euler[2] = 0; - - /* And calculate X-axis angle */ - euler[0] = (vec_t)RAD2DEG(atan2(-matrix[9], matrix[5])); - } - break; - case eYZX: - /* NOT IMPLEMENTED */ - break; - case eZXY: - /* NOT IMPLEMENTED */ - break; - case eXZY: - /* NOT IMPLEMENTED */ - break; - case eYXZ: - a = asin(matrix[6]); - ca = cos(a); - euler[0] = (vec_t)RAD2DEG(a); /* Calculate X-axis angle */ - - if (fabs(ca) > 0.005) /* Gimbal lock? */ - { - /* No, so get Y-axis angle */ - euler[1] = (vec_t)RAD2DEG(atan2(-matrix[2] / ca, matrix[10]/ ca)); - - /* Get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG(atan2(-matrix[4] / ca, matrix[5] / ca)); - } - else /* Gimbal lock has occurred */ - { - /* Set Z-axis angle to zero */ - euler[2] = 0; - - /* And calculate Y-axis angle */ - euler[1] = (vec_t)RAD2DEG(atan2(matrix[8], matrix[0])); - } - break; - case eZYX: - a = asin(matrix[8]); - ca = cos(a); - euler[1] = (vec_t)RAD2DEG(a); /* Calculate Y-axis angle */ - - if (fabs(ca) > 0.005) /* Gimbal lock? */ - { - /* No, so get X-axis angle */ - euler[0] = (vec_t)RAD2DEG(atan2(-matrix[9] / ca, matrix[10]/ ca)); - - /* Get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG(atan2(-matrix[4] / ca, matrix[0] / ca)); - } - else /* Gimbal lock has occurred */ - { - /* Set X-axis angle to zero */ - euler[0] = 0; - - /* And calculate Z-axis angle */ - euler[2] = (vec_t)RAD2DEG(atan2(matrix[1], matrix[5])); - } - break; - } - - /* return only positive angles in [0,360] */ - if (euler[0] < 0) euler[0] += 360; - if (euler[1] < 0) euler[1] += 360; - if (euler[2] < 0) euler[2] += 360; +void m4x4_get_rotation_vec3( const m4x4_t matrix, vec3_t euler, eulerOrder_t order ){ + double a, ca; + + switch ( order ) + { + case eXYZ: + a = asin( -matrix[2] ); + ca = cos( a ); + euler[1] = (vec_t)RAD2DEG( a ); /* Calculate Y-axis angle */ + + if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ + /* No, so get Z-axis angle */ + euler[2] = (vec_t)RAD2DEG( atan2( matrix[1] / ca, matrix[0] / ca ) ); + + /* Get X-axis angle */ + euler[0] = (vec_t)RAD2DEG( atan2( matrix[6] / ca, matrix[10] / ca ) ); + } + else /* Gimbal lock has occurred */ + { + /* Set Z-axis angle to zero */ + euler[2] = 0; + + /* And calculate X-axis angle */ + euler[0] = (vec_t)RAD2DEG( atan2( -matrix[9], matrix[5] ) ); + } + break; + case eYZX: + /* NOT IMPLEMENTED */ + break; + case eZXY: + /* NOT IMPLEMENTED */ + break; + case eXZY: + /* NOT IMPLEMENTED */ + break; + case eYXZ: + a = asin( matrix[6] ); + ca = cos( a ); + euler[0] = (vec_t)RAD2DEG( a ); /* Calculate X-axis angle */ + + if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ + /* No, so get Y-axis angle */ + euler[1] = (vec_t)RAD2DEG( atan2( -matrix[2] / ca, matrix[10] / ca ) ); + + /* Get Z-axis angle */ + euler[2] = (vec_t)RAD2DEG( atan2( -matrix[4] / ca, matrix[5] / ca ) ); + } + else /* Gimbal lock has occurred */ + { + /* Set Z-axis angle to zero */ + euler[2] = 0; + + /* And calculate Y-axis angle */ + euler[1] = (vec_t)RAD2DEG( atan2( matrix[8], matrix[0] ) ); + } + break; + case eZYX: + a = asin( matrix[8] ); + ca = cos( a ); + euler[1] = (vec_t)RAD2DEG( a ); /* Calculate Y-axis angle */ + + if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ + /* No, so get X-axis angle */ + euler[0] = (vec_t)RAD2DEG( atan2( -matrix[9] / ca, matrix[10] / ca ) ); + + /* Get Z-axis angle */ + euler[2] = (vec_t)RAD2DEG( atan2( -matrix[4] / ca, matrix[0] / ca ) ); + } + else /* Gimbal lock has occurred */ + { + /* Set X-axis angle to zero */ + euler[0] = 0; + + /* And calculate Z-axis angle */ + euler[2] = (vec_t)RAD2DEG( atan2( matrix[1], matrix[5] ) ); + } + break; + } + + /* return only positive angles in [0,360] */ + if ( euler[0] < 0 ) { + euler[0] += 360; + } + if ( euler[1] < 0 ) { + euler[1] += 360; + } + if ( euler[2] < 0 ) { + euler[2] += 360; + } } -void m4x4_get_scale_vec3(const m4x4_t matrix, vec3_t scale) -{ - scale[0] = VectorLength(matrix+0); - scale[1] = VectorLength(matrix+4); - scale[2] = VectorLength(matrix+8); +void m4x4_get_scale_vec3( const m4x4_t matrix, vec3_t scale ){ + scale[0] = VectorLength( matrix + 0 ); + scale[1] = VectorLength( matrix + 4 ); + scale[2] = VectorLength( matrix + 8 ); } -void m4x4_get_transform_vec3(const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale) -{ - m4x4_t normalised; - m4x4_assign(normalised, matrix); - scale[0] = VectorNormalize(normalised+0, normalised+0); - scale[1] = VectorNormalize(normalised+4, normalised+4); - scale[2] = VectorNormalize(normalised+8, normalised+8); - if(m4x4_handedness(normalised) == eLeftHanded) - { - VectorNegate(normalised+0, normalised+0); - VectorNegate(normalised+4, normalised+4); - VectorNegate(normalised+8, normalised+8); - scale[0] = -scale[0]; - scale[1] = -scale[1]; - scale[2] = -scale[2]; - } - m4x4_get_rotation_vec3(normalised, euler, order); - m4x4_get_translation_vec3(matrix, translation); +void m4x4_get_transform_vec3( const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale ){ + m4x4_t normalised; + m4x4_assign( normalised, matrix ); + scale[0] = VectorNormalize( normalised + 0, normalised + 0 ); + scale[1] = VectorNormalize( normalised + 4, normalised + 4 ); + scale[2] = VectorNormalize( normalised + 8, normalised + 8 ); + if ( m4x4_handedness( normalised ) == eLeftHanded ) { + VectorNegate( normalised + 0, normalised + 0 ); + VectorNegate( normalised + 4, normalised + 4 ); + VectorNegate( normalised + 8, normalised + 8 ); + scale[0] = -scale[0]; + scale[1] = -scale[1]; + scale[2] = -scale[2]; + } + m4x4_get_rotation_vec3( normalised, euler, order ); + m4x4_get_translation_vec3( matrix, translation ); } -void m4x4_translate_by_vec3(m4x4_t matrix, const vec3_t translation) -{ - m4x4_t temp; - m4x4_translation_for_vec3(temp, translation); - m4x4_multiply_by_m4x4(matrix, temp); +void m4x4_translate_by_vec3( m4x4_t matrix, const vec3_t translation ){ + m4x4_t temp; + m4x4_translation_for_vec3( temp, translation ); + m4x4_multiply_by_m4x4( matrix, temp ); } -void m4x4_rotate_by_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order) -{ - m4x4_t temp; - m4x4_rotation_for_vec3(temp, euler, order); - m4x4_multiply_by_m4x4(matrix, temp); +void m4x4_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ){ + m4x4_t temp; + m4x4_rotation_for_vec3( temp, euler, order ); + m4x4_multiply_by_m4x4( matrix, temp ); } -void m4x4_scale_by_vec3(m4x4_t matrix, const vec3_t scale) -{ - m4x4_t temp; - m4x4_scale_for_vec3(temp, scale); - m4x4_multiply_by_m4x4(matrix, temp); +void m4x4_scale_by_vec3( m4x4_t matrix, const vec3_t scale ){ + m4x4_t temp; + m4x4_scale_for_vec3( temp, scale ); + m4x4_multiply_by_m4x4( matrix, temp ); } -void m4x4_rotate_by_quat(m4x4_t matrix, const vec4_t rotation) -{ - m4x4_t temp; - m4x4_rotation_for_quat(temp, rotation); - m4x4_multiply_by_m4x4(matrix, temp); +void m4x4_rotate_by_quat( m4x4_t matrix, const vec4_t rotation ){ + m4x4_t temp; + m4x4_rotation_for_quat( temp, rotation ); + m4x4_multiply_by_m4x4( matrix, temp ); } -void m4x4_rotate_by_axisangle(m4x4_t matrix, const vec3_t axis, double angle) -{ - m4x4_t temp; - m4x4_rotation_for_axisangle(temp, axis, angle); - m4x4_multiply_by_m4x4(matrix, temp); +void m4x4_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle ){ + m4x4_t temp; + m4x4_rotation_for_axisangle( temp, axis, angle ); + m4x4_multiply_by_m4x4( matrix, temp ); } -void m4x4_transform_by_vec3(m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale) -{ - m4x4_translate_by_vec3(matrix, translation); - m4x4_rotate_by_vec3(matrix, euler, order); - m4x4_scale_by_vec3(matrix, scale); +void m4x4_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale ){ + m4x4_translate_by_vec3( matrix, translation ); + m4x4_rotate_by_vec3( matrix, euler, order ); + m4x4_scale_by_vec3( matrix, scale ); } -void m4x4_pivoted_rotate_by_vec3(m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - VectorNegate(pivotpoint, vec3_temp); +void m4x4_pivoted_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3(matrix, pivotpoint); - m4x4_rotate_by_vec3(matrix, euler, order); - m4x4_translate_by_vec3(matrix, vec3_temp); + m4x4_translate_by_vec3( matrix, pivotpoint ); + m4x4_rotate_by_vec3( matrix, euler, order ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } -void m4x4_pivoted_scale_by_vec3(m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - VectorNegate(pivotpoint, vec3_temp); +void m4x4_pivoted_scale_by_vec3( m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3(matrix, pivotpoint); - m4x4_scale_by_vec3(matrix, scale); - m4x4_translate_by_vec3(matrix, vec3_temp); + m4x4_translate_by_vec3( matrix, pivotpoint ); + m4x4_scale_by_vec3( matrix, scale ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } -void m4x4_pivoted_transform_by_vec3(m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - - VectorAdd(pivotpoint, translation, vec3_temp); - m4x4_translate_by_vec3(matrix, vec3_temp); - m4x4_rotate_by_vec3(matrix, euler, order); - m4x4_scale_by_vec3(matrix, scale); - VectorNegate(pivotpoint, vec3_temp); - m4x4_translate_by_vec3(matrix, vec3_temp); +void m4x4_pivoted_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + + VectorAdd( pivotpoint, translation, vec3_temp ); + m4x4_translate_by_vec3( matrix, vec3_temp ); + m4x4_rotate_by_vec3( matrix, euler, order ); + m4x4_scale_by_vec3( matrix, scale ); + VectorNegate( pivotpoint, vec3_temp ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } -void m4x4_pivoted_transform_by_rotation(m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - - VectorAdd(pivotpoint, translation, vec3_temp); - m4x4_translate_by_vec3(matrix, vec3_temp); - m4x4_multiply_by_m4x4(matrix, rotation); - m4x4_scale_by_vec3(matrix, scale); - VectorNegate(pivotpoint, vec3_temp); - m4x4_translate_by_vec3(matrix, vec3_temp); +void m4x4_pivoted_transform_by_rotation( m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + + VectorAdd( pivotpoint, translation, vec3_temp ); + m4x4_translate_by_vec3( matrix, vec3_temp ); + m4x4_multiply_by_m4x4( matrix, rotation ); + m4x4_scale_by_vec3( matrix, scale ); + VectorNegate( pivotpoint, vec3_temp ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } -void m4x4_pivoted_rotate_by_quat(m4x4_t matrix, const vec4_t rotation, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - VectorNegate(pivotpoint, vec3_temp); +void m4x4_pivoted_rotate_by_quat( m4x4_t matrix, const vec4_t rotation, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3(matrix, pivotpoint); - m4x4_rotate_by_quat(matrix, rotation); - m4x4_translate_by_vec3(matrix, vec3_temp); + m4x4_translate_by_vec3( matrix, pivotpoint ); + m4x4_rotate_by_quat( matrix, rotation ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } -void m4x4_pivoted_rotate_by_axisangle(m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint) -{ - vec3_t vec3_temp; - VectorNegate(pivotpoint, vec3_temp); +void m4x4_pivoted_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint ){ + vec3_t vec3_temp; + VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3(matrix, pivotpoint); - m4x4_rotate_by_axisangle(matrix, axis, angle); - m4x4_translate_by_vec3(matrix, vec3_temp); + m4x4_translate_by_vec3( matrix, pivotpoint ); + m4x4_rotate_by_axisangle( matrix, axis, angle ); + m4x4_translate_by_vec3( matrix, vec3_temp ); } /* -A = A.B - -A0 = B0 * A0 + B1 * A4 + B2 * A8 + B3 * A12 -A4 = B4 * A0 + B5 * A4 + B6 * A8 + B7 * A12 -A8 = B8 * A0 + B9 * A4 + B10* A8 + B11* A12 -A12= B12* A0 + B13* A4 + B14* A8 + B15* A12 - -A1 = B0 * A1 + B1 * A5 + B2 * A9 + B3 * A13 -A5 = B4 * A1 + B5 * A5 + B6 * A9 + B7 * A13 -A9 = B8 * A1 + B9 * A5 + B10* A9 + B11* A13 -A13= B12* A1 + B13* A5 + B14* A9 + B15* A13 - -A2 = B0 * A2 + B1 * A6 + B2 * A10+ B3 * A14 -A6 = B4 * A2 + B5 * A6 + B6 * A10+ B7 * A14 -A10= B8 * A2 + B9 * A6 + B10* A10+ B11* A14 -A14= B12* A2 + B13* A6 + B14* A10+ B15* A14 - -A3 = B0 * A3 + B1 * A7 + B2 * A11+ B3 * A15 -A7 = B4 * A3 + B5 * A7 + B6 * A11+ B7 * A15 -A11= B8 * A3 + B9 * A7 + B10* A11+ B11* A15 -A15= B12* A3 + B13* A7 + B14* A11+ B15* A15 -*/ - -void m4x4_multiply_by_m4x4(m4x4_t dst, const m4x4_t src) -{ + A = A.B + + A0 = B0 * A0 + B1 * A4 + B2 * A8 + B3 * A12 + A4 = B4 * A0 + B5 * A4 + B6 * A8 + B7 * A12 + A8 = B8 * A0 + B9 * A4 + B10* A8 + B11* A12 + A12= B12* A0 + B13* A4 + B14* A8 + B15* A12 + + A1 = B0 * A1 + B1 * A5 + B2 * A9 + B3 * A13 + A5 = B4 * A1 + B5 * A5 + B6 * A9 + B7 * A13 + A9 = B8 * A1 + B9 * A5 + B10* A9 + B11* A13 + A13= B12* A1 + B13* A5 + B14* A9 + B15* A13 + + A2 = B0 * A2 + B1 * A6 + B2 * A10+ B3 * A14 + A6 = B4 * A2 + B5 * A6 + B6 * A10+ B7 * A14 + A10= B8 * A2 + B9 * A6 + B10* A10+ B11* A14 + A14= B12* A2 + B13* A6 + B14* A10+ B15* A14 + + A3 = B0 * A3 + B1 * A7 + B2 * A11+ B3 * A15 + A7 = B4 * A3 + B5 * A7 + B6 * A11+ B7 * A15 + A11= B8 * A3 + B9 * A7 + B10* A11+ B11* A15 + A15= B12* A3 + B13* A7 + B14* A11+ B15* A15 + */ + +void m4x4_multiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ vec_t dst0, dst1, dst2, dst3; #if 1 - dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8] + src[3] * dst[12]; - dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8] + src[7] * dst[12]; - dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10]* dst[8] + src[11]* dst[12]; - dst3 = src[12]* dst[0] + src[13]* dst[4] + src[14]* dst[8] + src[15]* dst[12]; - dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12]= dst3; - - dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9] + src[3] * dst[13]; - dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9] + src[7] * dst[13]; - dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10]* dst[9] + src[11]* dst[13]; - dst3 = src[12]* dst[1] + src[13]* dst[5] + src[14]* dst[9] + src[15]* dst[13]; - dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13]= dst3; - - dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10]+ src[3] * dst[14]; - dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10]+ src[7] * dst[14]; - dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10]* dst[10]+ src[11]* dst[14]; - dst3 = src[12]* dst[2] + src[13]* dst[6] + src[14]* dst[10]+ src[15]* dst[14]; - dst[2] = dst0; dst[6] = dst1; dst[10]= dst2; dst[14]= dst3; - - dst0 = src[0] * dst[3] + src[1] * dst[7] + src[2] * dst[11]+ src[3] * dst[15]; - dst1 = src[4] * dst[3] + src[5] * dst[7] + src[6] * dst[11]+ src[7] * dst[15]; - dst2 = src[8] * dst[3] + src[9] * dst[7] + src[10]* dst[11]+ src[11]* dst[15]; - dst3 = src[12]* dst[3] + src[13]* dst[7] + src[14]* dst[11]+ src[15]* dst[15]; - dst[3] = dst0; dst[7] = dst1; dst[11]= dst2; dst[15]= dst3; + dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8] + src[3] * dst[12]; + dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8] + src[7] * dst[12]; + dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10] * dst[8] + src[11] * dst[12]; + dst3 = src[12] * dst[0] + src[13] * dst[4] + src[14] * dst[8] + src[15] * dst[12]; + dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12] = dst3; + + dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9] + src[3] * dst[13]; + dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9] + src[7] * dst[13]; + dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10] * dst[9] + src[11] * dst[13]; + dst3 = src[12] * dst[1] + src[13] * dst[5] + src[14] * dst[9] + src[15] * dst[13]; + dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13] = dst3; + + dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10] + src[3] * dst[14]; + dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10] + src[7] * dst[14]; + dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10] * dst[10] + src[11] * dst[14]; + dst3 = src[12] * dst[2] + src[13] * dst[6] + src[14] * dst[10] + src[15] * dst[14]; + dst[2] = dst0; dst[6] = dst1; dst[10] = dst2; dst[14] = dst3; + + dst0 = src[0] * dst[3] + src[1] * dst[7] + src[2] * dst[11] + src[3] * dst[15]; + dst1 = src[4] * dst[3] + src[5] * dst[7] + src[6] * dst[11] + src[7] * dst[15]; + dst2 = src[8] * dst[3] + src[9] * dst[7] + src[10] * dst[11] + src[11] * dst[15]; + dst3 = src[12] * dst[3] + src[13] * dst[7] + src[14] * dst[11] + src[15] * dst[15]; + dst[3] = dst0; dst[7] = dst1; dst[11] = dst2; dst[15] = dst3; #else - vec_t * p = dst; - for(int i=0;i<4;i++) + vec_t * p = dst; + for ( int i = 0; i < 4; i++ ) { dst1 = src[0] * p[0]; dst1 += src[1] * p[4]; @@ -693,70 +669,69 @@ void m4x4_multiply_by_m4x4(m4x4_t dst, const m4x4_t src) p[4] = dst2; p[8] = dst3; p[12] = dst4; - p++; + p++; } #endif } /* -A = B.A - -A0 = A0 * B0 + A1 * B4 + A2 * B8 + A3 * B12 -A1 = A0 * B1 + A1 * B5 + A2 * B9 + A3 * B13 -A2 = A0 * B2 + A1 * B6 + A2 * B10+ A3 * B14 -A3 = A0 * B3 + A1 * B7 + A2 * B11+ A3 * B15 - -A4 = A4 * B0 + A5 * B4 + A6 * B8 + A7 * B12 -A5 = A4 * B1 + A5 * B5 + A6 * B9 + A7 * B13 -A6 = A4 * B2 + A5 * B6 + A6 * B10+ A7 * B14 -A7 = A4 * B3 + A5 * B7 + A6 * B11+ A7 * B15 - -A8 = A8 * B0 + A9 * B4 + A10* B8 + A11* B12 -A9 = A8 * B1 + A9 * B5 + A10* B9 + A11* B13 -A10= A8 * B2 + A9 * B6 + A10* B10+ A11* B14 -A11= A8 * B3 + A9 * B7 + A10* B11+ A11* B15 - -A12= A12* B0 + A13* B4 + A14* B8 + A15* B12 -A13= A12* B1 + A13* B5 + A14* B9 + A15* B13 -A14= A12* B2 + A13* B6 + A14* B10+ A15* B14 -A15= A12* B3 + A13* B7 + A14* B11+ A15* B15 -*/ - -void m4x4_premultiply_by_m4x4(m4x4_t dst, const m4x4_t src) -{ + A = B.A + + A0 = A0 * B0 + A1 * B4 + A2 * B8 + A3 * B12 + A1 = A0 * B1 + A1 * B5 + A2 * B9 + A3 * B13 + A2 = A0 * B2 + A1 * B6 + A2 * B10+ A3 * B14 + A3 = A0 * B3 + A1 * B7 + A2 * B11+ A3 * B15 + + A4 = A4 * B0 + A5 * B4 + A6 * B8 + A7 * B12 + A5 = A4 * B1 + A5 * B5 + A6 * B9 + A7 * B13 + A6 = A4 * B2 + A5 * B6 + A6 * B10+ A7 * B14 + A7 = A4 * B3 + A5 * B7 + A6 * B11+ A7 * B15 + + A8 = A8 * B0 + A9 * B4 + A10* B8 + A11* B12 + A9 = A8 * B1 + A9 * B5 + A10* B9 + A11* B13 + A10= A8 * B2 + A9 * B6 + A10* B10+ A11* B14 + A11= A8 * B3 + A9 * B7 + A10* B11+ A11* B15 + + A12= A12* B0 + A13* B4 + A14* B8 + A15* B12 + A13= A12* B1 + A13* B5 + A14* B9 + A15* B13 + A14= A12* B2 + A13* B6 + A14* B10+ A15* B14 + A15= A12* B3 + A13* B7 + A14* B11+ A15* B15 + */ + +void m4x4_premultiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ vec_t dst0, dst1, dst2, dst3; #if 1 - dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8] + dst[3] * src[12]; - dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9] + dst[3] * src[13]; - dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10]+ dst[3] * src[14]; - dst3 = dst[0] * src[3] + dst[1] * src[7] + dst[2] * src[11]+ dst[3] * src[15]; - dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; dst[3]= dst3; - - dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8] + dst[7] * src[12]; - dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9] + dst[7] * src[13]; - dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10]+ dst[7] * src[14]; - dst3 = dst[4] * src[3] + dst[5] * src[7] + dst[6] * src[11]+ dst[7] * src[15]; - dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; dst[7]= dst3; - - dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10]* src[8] + dst[11]* src[12]; - dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10]* src[9] + dst[11]* src[13]; - dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10]* src[10]+ dst[11]* src[14]; - dst3 = dst[8] * src[3] + dst[9] * src[7] + dst[10]* src[11]+ dst[11]* src[15]; - dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; dst[11]= dst3; - - dst0 = dst[12]* src[0] + dst[13]* src[4] + dst[14]* src[8] + dst[15]* src[12]; - dst1 = dst[12]* src[1] + dst[13]* src[5] + dst[14]* src[9] + dst[15]* src[13]; - dst2 = dst[12]* src[2] + dst[13]* src[6] + dst[14]* src[10]+ dst[15]* src[14]; - dst3 = dst[12]* src[3] + dst[13]* src[7] + dst[14]* src[11]+ dst[15]* src[15]; - dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; dst[15]= dst3; + dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8] + dst[3] * src[12]; + dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9] + dst[3] * src[13]; + dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10] + dst[3] * src[14]; + dst3 = dst[0] * src[3] + dst[1] * src[7] + dst[2] * src[11] + dst[3] * src[15]; + dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; dst[3] = dst3; + + dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8] + dst[7] * src[12]; + dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9] + dst[7] * src[13]; + dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10] + dst[7] * src[14]; + dst3 = dst[4] * src[3] + dst[5] * src[7] + dst[6] * src[11] + dst[7] * src[15]; + dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; dst[7] = dst3; + + dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10] * src[8] + dst[11] * src[12]; + dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10] * src[9] + dst[11] * src[13]; + dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10] * src[10] + dst[11] * src[14]; + dst3 = dst[8] * src[3] + dst[9] * src[7] + dst[10] * src[11] + dst[11] * src[15]; + dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; dst[11] = dst3; + + dst0 = dst[12] * src[0] + dst[13] * src[4] + dst[14] * src[8] + dst[15] * src[12]; + dst1 = dst[12] * src[1] + dst[13] * src[5] + dst[14] * src[9] + dst[15] * src[13]; + dst2 = dst[12] * src[2] + dst[13] * src[6] + dst[14] * src[10] + dst[15] * src[14]; + dst3 = dst[12] * src[3] + dst[13] * src[7] + dst[14] * src[11] + dst[15] * src[15]; + dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; dst[15] = dst3; #else - vec_t* p = dst; - for(int i=0;i<4;i++) + vec_t* p = dst; + for ( int i = 0; i < 4; i++ ) { dst1 = src[0] * p[0]; dst2 = src[1] * p[0]; @@ -784,57 +759,54 @@ void m4x4_premultiply_by_m4x4(m4x4_t dst, const m4x4_t src) #endif } -void m4x4_orthogonal_multiply_by_m4x4(m4x4_t dst, const m4x4_t src) -{ +void m4x4_orthogonal_multiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ vec_t dst0, dst1, dst2, dst3; - dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8]; - dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8]; - dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10]* dst[8]; - dst3 = src[12]* dst[0] + src[13]* dst[4] + src[14]* dst[8] + dst[12]; - dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12]= dst3; - - dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9]; - dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9]; - dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10]* dst[9]; - dst3 = src[12]* dst[1] + src[13]* dst[5] + src[14]* dst[9] + dst[13]; - dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13]= dst3; - - dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10]; - dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10]; - dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10]* dst[10]; - dst3 = src[12]* dst[2] + src[13]* dst[6] + src[14]* dst[10]+ dst[14]; - dst[2] = dst0; dst[6] = dst1; dst[10]= dst2; dst[14]= dst3; + dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8]; + dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8]; + dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10] * dst[8]; + dst3 = src[12] * dst[0] + src[13] * dst[4] + src[14] * dst[8] + dst[12]; + dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12] = dst3; + + dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9]; + dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9]; + dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10] * dst[9]; + dst3 = src[12] * dst[1] + src[13] * dst[5] + src[14] * dst[9] + dst[13]; + dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13] = dst3; + + dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10]; + dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10]; + dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10] * dst[10]; + dst3 = src[12] * dst[2] + src[13] * dst[6] + src[14] * dst[10] + dst[14]; + dst[2] = dst0; dst[6] = dst1; dst[10] = dst2; dst[14] = dst3; } -void m4x4_orthogonal_premultiply_by_m4x4(m4x4_t dst, const m4x4_t src) -{ +void m4x4_orthogonal_premultiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ vec_t dst0, dst1, dst2; - dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8]; - dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9]; - dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10]; - dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; - - dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8]; - dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9]; - dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10]; - dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; - - dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10]* src[8]; - dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10]* src[9]; - dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10]* src[10]; - dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; - - dst0 = dst[12]* src[0] + dst[13]* src[4] + dst[14]* src[8] + dst[15]* src[12]; - dst1 = dst[12]* src[1] + dst[13]* src[5] + dst[14]* src[9] + dst[15]* src[13]; - dst2 = dst[12]* src[2] + dst[13]* src[6] + dst[14]* src[10]+ dst[15]* src[14]; - dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; + dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8]; + dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9]; + dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10]; + dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; + + dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8]; + dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9]; + dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10]; + dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; + + dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10] * src[8]; + dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10] * src[9]; + dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10] * src[10]; + dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; + + dst0 = dst[12] * src[0] + dst[13] * src[4] + dst[14] * src[8] + dst[15] * src[12]; + dst1 = dst[12] * src[1] + dst[13] * src[5] + dst[14] * src[9] + dst[15] * src[13]; + dst2 = dst[12] * src[2] + dst[13] * src[6] + dst[14] * src[10] + dst[15] * src[14]; + dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; } -void m4x4_transform_point(const m4x4_t matrix, vec3_t point) -{ - float out1, out2, out3; +void m4x4_transform_point( const m4x4_t matrix, vec3_t point ){ + float out1, out2, out3; out1 = matrix[0] * point[0] + matrix[4] * point[1] + matrix[8] * point[2] + matrix[12]; out2 = matrix[1] * point[0] + matrix[5] * point[1] + matrix[9] * point[2] + matrix[13]; @@ -845,9 +817,8 @@ void m4x4_transform_point(const m4x4_t matrix, vec3_t point) point[2] = out3; } -void m4x4_transform_normal(const m4x4_t matrix, vec3_t normal) -{ - float out1, out2, out3; +void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ){ + float out1, out2, out3; out1 = matrix[0] * normal[0] + matrix[4] * normal[1] + matrix[8] * normal[2]; out2 = matrix[1] * normal[0] + matrix[5] * normal[1] + matrix[9] * normal[2]; @@ -858,9 +829,8 @@ void m4x4_transform_normal(const m4x4_t matrix, vec3_t normal) normal[2] = out3; } -void m4x4_transform_vec4(const m4x4_t matrix, vec4_t vector) -{ - float out1, out2, out3, out4; +void m4x4_transform_vec4( const m4x4_t matrix, vec4_t vector ){ + float out1, out2, out3, out4; out1 = matrix[0] * vector[0] + matrix[4] * vector[1] + matrix[8] * vector[2] + matrix[12] * vector[3]; out2 = matrix[1] * vector[0] + matrix[5] * vector[1] + matrix[9] * vector[2] + matrix[13] * vector[3]; @@ -870,680 +840,686 @@ void m4x4_transform_vec4(const m4x4_t matrix, vec4_t vector) vector[0] = out1; vector[1] = out2; vector[2] = out3; - vector[3] = out4; + vector[3] = out4; } -#define CLIP_X_LT_W(p) ((p)[0] < (p)[3]) -#define CLIP_X_GT_W(p) ((p)[0] > -(p)[3]) -#define CLIP_Y_LT_W(p) ((p)[1] < (p)[3]) -#define CLIP_Y_GT_W(p) ((p)[1] > -(p)[3]) -#define CLIP_Z_LT_W(p) ((p)[2] < (p)[3]) -#define CLIP_Z_GT_W(p) ((p)[2] > -(p)[3]) - -clipmask_t homogenous_clip_point(const vec4_t clipped) -{ - clipmask_t result = CLIP_FAIL; - if(CLIP_X_LT_W(clipped)) result &= ~CLIP_LT_X; // X < W - if(CLIP_X_GT_W(clipped)) result &= ~CLIP_GT_X; // X > -W - if(CLIP_Y_LT_W(clipped)) result &= ~CLIP_LT_Y; // Y < W - if(CLIP_Y_GT_W(clipped)) result &= ~CLIP_GT_Y; // Y > -W - if(CLIP_Z_LT_W(clipped)) result &= ~CLIP_LT_Z; // Z < W - if(CLIP_Z_GT_W(clipped)) result &= ~CLIP_GT_Z; // Z > -W - return result; +#define CLIP_X_LT_W( p ) ( ( p )[0] < ( p )[3] ) +#define CLIP_X_GT_W( p ) ( ( p )[0] > -( p )[3] ) +#define CLIP_Y_LT_W( p ) ( ( p )[1] < ( p )[3] ) +#define CLIP_Y_GT_W( p ) ( ( p )[1] > -( p )[3] ) +#define CLIP_Z_LT_W( p ) ( ( p )[2] < ( p )[3] ) +#define CLIP_Z_GT_W( p ) ( ( p )[2] > -( p )[3] ) + +clipmask_t homogenous_clip_point( const vec4_t clipped ){ + clipmask_t result = CLIP_FAIL; + if ( CLIP_X_LT_W( clipped ) ) { + result &= ~CLIP_LT_X; // X < W + } + if ( CLIP_X_GT_W( clipped ) ) { + result &= ~CLIP_GT_X; // X > -W + } + if ( CLIP_Y_LT_W( clipped ) ) { + result &= ~CLIP_LT_Y; // Y < W + } + if ( CLIP_Y_GT_W( clipped ) ) { + result &= ~CLIP_GT_Y; // Y > -W + } + if ( CLIP_Z_LT_W( clipped ) ) { + result &= ~CLIP_LT_Z; // Z < W + } + if ( CLIP_Z_GT_W( clipped ) ) { + result &= ~CLIP_GT_Z; // Z > -W + } + return result; } -clipmask_t m4x4_clip_point(const m4x4_t matrix, const vec3_t point, vec4_t clipped) -{ - clipped[0] = point[0]; - clipped[1] = point[1]; - clipped[2] = point[2]; - clipped[3] = 1; - m4x4_transform_vec4(matrix, clipped); - return homogenous_clip_point(clipped); +clipmask_t m4x4_clip_point( const m4x4_t matrix, const vec3_t point, vec4_t clipped ){ + clipped[0] = point[0]; + clipped[1] = point[1]; + clipped[2] = point[2]; + clipped[3] = 1; + m4x4_transform_vec4( matrix, clipped ); + return homogenous_clip_point( clipped ); } -unsigned int homogenous_clip_triangle(vec4_t clipped[9]) -{ - vec4_t buffer[9]; - unsigned int rcount = 3; - unsigned int wcount = 0; - vec_t const* rptr = clipped[0]; - vec_t* wptr = buffer[0]; - const vec_t* p0; - const vec_t* p1; - unsigned char b0, b1; - - unsigned int i; - double scale; - - p0 = rptr; - b0 = CLIP_X_LT_W(p0); - for(i=0; i= 0.0) pos += det; else neg += det; - - det = src[1] * src[6] * src[8]; - if (det >= 0.0) pos += det; else neg += det; - - det = src[2] * src[4] * src[9]; - if (det >= 0.0) pos += det; else neg += det; - - det = -src[2] * src[5] * src[8]; - if (det >= 0.0) pos += det; else neg += det; - - det = -src[1] * src[4] * src[10]; - if (det >= 0.0) pos += det; else neg += det; - - det = -src[0] * src[6] * src[9]; - if (det >= 0.0) pos += det; else neg += det; - - det = pos + neg; + float pos = 0.0f; + float neg = 0.0f; + float det = src[0] * src[5] * src[10]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = src[1] * src[6] * src[8]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = src[2] * src[4] * src[9]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = -src[2] * src[5] * src[8]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = -src[1] * src[4] * src[10]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = -src[0] * src[6] * src[9]; + if ( det >= 0.0 ) { + pos += det; + } + else{ neg += det; } + + det = pos + neg; #elif 0 - float det - = (src[0] * src[5] * src[10]) - + (src[1] * src[6] * src[8]) - + (src[2] * src[4] * src[9]) - - (src[2] * src[5] * src[8]) - - (src[1] * src[4] * src[10]) - - (src[0] * src[6] * src[9]); + float det + = ( src[0] * src[5] * src[10] ) + + ( src[1] * src[6] * src[8] ) + + ( src[2] * src[4] * src[9] ) + - ( src[2] * src[5] * src[8] ) + - ( src[1] * src[4] * src[10] ) + - ( src[0] * src[6] * src[9] ); #else - float det - = src[0] * ( src[5]*src[10] - src[9]*src[6] ) - - src[1] * ( src[4]*src[10] - src[8]*src[6] ) - + src[2] * ( src[4]*src[9] - src[8]*src[5] ); + float det + = src[0] * ( src[5] * src[10] - src[9] * src[6] ) + - src[1] * ( src[4] * src[10] - src[8] * src[6] ) + + src[2] * ( src[4] * src[9] - src[8] * src[5] ); #endif - - if (det*det < 1e-25) - return 1; - - det = 1.0f / det; - matrix[0] = ( (src[5]*src[10]- src[6]*src[9] )*det); - matrix[1] = (- (src[1]*src[10]- src[2]*src[9] )*det); - matrix[2] = ( (src[1]*src[6] - src[2]*src[5] )*det); - matrix[4] = (- (src[4]*src[10]- src[6]*src[8] )*det); - matrix[5] = ( (src[0]*src[10]- src[2]*src[8] )*det); - matrix[6] = (- (src[0]*src[6] - src[2]*src[4] )*det); - matrix[8] = ( (src[4]*src[9] - src[5]*src[8] )*det); - matrix[9] = (- (src[0]*src[9] - src[1]*src[8] )*det); - matrix[10]= ( (src[0]*src[5] - src[1]*src[4] )*det); - } - - /* Do the translation part */ - matrix[12] = - (src[12] * matrix[0] + - src[13] * matrix[4] + - src[14] * matrix[8]); - matrix[13] = - (src[12] * matrix[1] + - src[13] * matrix[5] + - src[14] * matrix[9]); - matrix[14] = - (src[12] * matrix[2] + - src[13] * matrix[6] + - src[14] * matrix[10]); - - return 0; + + if ( det * det < 1e-25 ) { + return 1; + } + + det = 1.0f / det; + matrix[0] = ( ( src[5] * src[10] - src[6] * src[9] ) * det ); + matrix[1] = ( -( src[1] * src[10] - src[2] * src[9] ) * det ); + matrix[2] = ( ( src[1] * src[6] - src[2] * src[5] ) * det ); + matrix[4] = ( -( src[4] * src[10] - src[6] * src[8] ) * det ); + matrix[5] = ( ( src[0] * src[10] - src[2] * src[8] ) * det ); + matrix[6] = ( -( src[0] * src[6] - src[2] * src[4] ) * det ); + matrix[8] = ( ( src[4] * src[9] - src[5] * src[8] ) * det ); + matrix[9] = ( -( src[0] * src[9] - src[1] * src[8] ) * det ); + matrix[10] = ( ( src[0] * src[5] - src[1] * src[4] ) * det ); + } + + /* Do the translation part */ + matrix[12] = -( src[12] * matrix[0] + + src[13] * matrix[4] + + src[14] * matrix[8] ); + matrix[13] = -( src[12] * matrix[1] + + src[13] * matrix[5] + + src[14] * matrix[9] ); + matrix[14] = -( src[12] * matrix[2] + + src[13] * matrix[6] + + src[14] * matrix[10] ); + + return 0; } -void quat_identity(vec4_t quat) -{ - quat[0] = quat[1] = quat[2] = 0; - quat[3] = 1; +void quat_identity( vec4_t quat ){ + quat[0] = quat[1] = quat[2] = 0; + quat[3] = 1; } -void quat_multiply_by_quat(vec4_t quat, const vec4_t other) -{ - const vec_t x = quat[3]*other[0] + quat[0]*other[3] + quat[1]*other[2] - quat[2]*other[1]; - const vec_t y = quat[3]*other[1] + quat[1]*other[3] + quat[2]*other[0] - quat[0]*other[2]; - const vec_t z = quat[3]*other[2] + quat[2]*other[3] + quat[0]*other[1] - quat[1]*other[0]; - const vec_t w = quat[3]*other[3] - quat[0]*other[0] - quat[1]*other[1] - quat[2]*other[2]; - quat[0] = x; - quat[1] = y; - quat[2] = z; - quat[3] = w; +void quat_multiply_by_quat( vec4_t quat, const vec4_t other ){ + const vec_t x = quat[3] * other[0] + quat[0] * other[3] + quat[1] * other[2] - quat[2] * other[1]; + const vec_t y = quat[3] * other[1] + quat[1] * other[3] + quat[2] * other[0] - quat[0] * other[2]; + const vec_t z = quat[3] * other[2] + quat[2] * other[3] + quat[0] * other[1] - quat[1] * other[0]; + const vec_t w = quat[3] * other[3] - quat[0] * other[0] - quat[1] * other[1] - quat[2] * other[2]; + quat[0] = x; + quat[1] = y; + quat[2] = z; + quat[3] = w; } -void quat_conjugate(vec4_t quat) -{ - VectorNegate(quat, quat); +void quat_conjugate( vec4_t quat ){ + VectorNegate( quat, quat ); } //! quaternion from two unit vectors -void quat_for_unit_vectors(vec4_t quat, const vec3_t from, const vec3_t to) -{ - CrossProduct(from, to, quat); - quat[3] = DotProduct(from, to); +void quat_for_unit_vectors( vec4_t quat, const vec3_t from, const vec3_t to ){ + CrossProduct( from, to, quat ); + quat[3] = DotProduct( from, to ); } -void quat_normalise(vec4_t quat) -{ - const vec_t n = 1 / ( quat[0] * quat[0] + quat[1] * quat[1] + quat[2] * quat[2] + quat[3] * quat[3] ); - quat[0] *= n; - quat[1] *= n; - quat[2] *= n; - quat[3] *= n; +void quat_normalise( vec4_t quat ){ + const vec_t n = 1 / ( quat[0] * quat[0] + quat[1] * quat[1] + quat[2] * quat[2] + quat[3] * quat[3] ); + quat[0] *= n; + quat[1] *= n; + quat[2] *= n; + quat[3] *= n; } -void quat_for_axisangle(vec4_t quat, const vec3_t axis, double angle) -{ - angle *= 0.5; +void quat_for_axisangle( vec4_t quat, const vec3_t axis, double angle ){ + angle *= 0.5; - quat[3] = (float)sin(angle); + quat[3] = (float)sin( angle ); - quat[0] = axis[0] * quat[3]; - quat[1] = axis[1] * quat[3]; - quat[2] = axis[2] * quat[3]; - quat[3] = (float)cos(angle); + quat[0] = axis[0] * quat[3]; + quat[1] = axis[1] * quat[3]; + quat[2] = axis[2] * quat[3]; + quat[3] = (float)cos( angle ); } -void m3x3_multiply_by_m3x3(m3x3_t matrix, const m3x3_t matrix_src) -{ - float *pDest = matrix; +void m3x3_multiply_by_m3x3( m3x3_t matrix, const m3x3_t matrix_src ){ + float *pDest = matrix; float out1, out2, out3; - int i; + int i; - for(i=0;i<3;i++) + for ( i = 0; i < 3; i++ ) { out1 = matrix_src[0] * pDest[0]; out1 += matrix_src[1] * pDest[3]; @@ -1559,13 +1535,12 @@ void m3x3_multiply_by_m3x3(m3x3_t matrix, const m3x3_t matrix_src) pDest[3] = out2; pDest[6] = out3; - pDest++; + pDest++; } } -void m3x3_transform_vec3(const m3x3_t matrix, vec3_t vector) -{ - float out1, out2, out3; +void m3x3_transform_vec3( const m3x3_t matrix, vec3_t vector ){ + float out1, out2, out3; out1 = matrix[0] * vector[0]; out1 += matrix[3] * vector[1]; @@ -1582,297 +1557,293 @@ void m3x3_transform_vec3(const m3x3_t matrix, vec3_t vector) vector[2] = out3; } -float m3_det( m3x3_t mat ) -{ - float det; - - det = mat[0] * ( mat[4]*mat[8] - mat[7]*mat[5] ) - - mat[1] * ( mat[3]*mat[8] - mat[6]*mat[5] ) - + mat[2] * ( mat[3]*mat[7] - mat[6]*mat[4] ); - - return( det ); +float m3_det( m3x3_t mat ){ + float det; + + det = mat[0] * ( mat[4] * mat[8] - mat[7] * mat[5] ) + - mat[1] * ( mat[3] * mat[8] - mat[6] * mat[5] ) + + mat[2] * ( mat[3] * mat[7] - mat[6] * mat[4] ); + + return( det ); } -int m3_inverse( m3x3_t mr, m3x3_t ma ) -{ - float det = m3_det( ma ); - - if (det == 0 ) - { - return 1; - } - - - mr[0] = ma[4]*ma[8] - ma[5]*ma[7] / det; - mr[1] = -( ma[1]*ma[8] - ma[7]*ma[2] ) / det; - mr[2] = ma[1]*ma[5] - ma[4]*ma[2] / det; - - mr[3] = -( ma[3]*ma[8] - ma[5]*ma[6] ) / det; - mr[4] = ma[0]*ma[8] - ma[6]*ma[2] / det; - mr[5] = -( ma[0]*ma[5] - ma[3]*ma[2] ) / det; - - mr[6] = ma[3]*ma[7] - ma[6]*ma[4] / det; - mr[7] = -( ma[0]*ma[7] - ma[6]*ma[1] ) / det; - mr[8] = ma[0]*ma[4] - ma[1]*ma[3] / det; - - return 0; +int m3_inverse( m3x3_t mr, m3x3_t ma ){ + float det = m3_det( ma ); + + if ( det == 0 ) { + return 1; + } + + + mr[0] = ma[4] * ma[8] - ma[5] * ma[7] / det; + mr[1] = -( ma[1] * ma[8] - ma[7] * ma[2] ) / det; + mr[2] = ma[1] * ma[5] - ma[4] * ma[2] / det; + + mr[3] = -( ma[3] * ma[8] - ma[5] * ma[6] ) / det; + mr[4] = ma[0] * ma[8] - ma[6] * ma[2] / det; + mr[5] = -( ma[0] * ma[5] - ma[3] * ma[2] ) / det; + + mr[6] = ma[3] * ma[7] - ma[6] * ma[4] / det; + mr[7] = -( ma[0] * ma[7] - ma[6] * ma[1] ) / det; + mr[8] = ma[0] * ma[4] - ma[1] * ma[3] / det; + + return 0; } -void m4_submat( m4x4_t mr, m3x3_t mb, int i, int j ) -{ - int ti, tj, idst, jdst; - - for ( ti = 0; ti < 4; ti++ ) - { - if ( ti < i ) - idst = ti; - else if ( ti > i ) - idst = ti-1; - else - continue; - - for ( tj = 0; tj < 4; tj++ ) - { - if ( tj < j ) - jdst = tj; - else if ( tj > j ) - jdst = tj-1; - else - continue; - - mb[idst*3 + jdst] = mr[ti*4 + tj ]; - } - } +void m4_submat( m4x4_t mr, m3x3_t mb, int i, int j ){ + int ti, tj, idst, jdst; + + for ( ti = 0; ti < 4; ti++ ) + { + if ( ti < i ) { + idst = ti; + } + else if ( ti > i ) { + idst = ti - 1; + } + else{ + continue; + } + + for ( tj = 0; tj < 4; tj++ ) + { + if ( tj < j ) { + jdst = tj; + } + else if ( tj > j ) { + jdst = tj - 1; + } + else{ + continue; + } + + mb[idst * 3 + jdst] = mr[ti * 4 + tj ]; + } + } } -float m4_det( m4x4_t mr ) -{ - float det, result = 0, i = 1; - m3x3_t msub3; - int n; - - for ( n = 0; n < 4; n++, i *= -1 ) - { - m4_submat( mr, msub3, 0, n ); - - det = m3_det( msub3 ); - result += mr[n] * det * i; - } - - return result; +float m4_det( m4x4_t mr ){ + float det, result = 0, i = 1; + m3x3_t msub3; + int n; + + for ( n = 0; n < 4; n++, i *= -1 ) + { + m4_submat( mr, msub3, 0, n ); + + det = m3_det( msub3 ); + result += mr[n] * det * i; + } + + return result; } -int m4x4_invert(m4x4_t matrix) -{ - float mdet = m4_det( matrix ); - m3x3_t mtemp; - int i, j, sign; - m4x4_t m4x4_temp; - +int m4x4_invert( m4x4_t matrix ){ + float mdet = m4_det( matrix ); + m3x3_t mtemp; + int i, j, sign; + m4x4_t m4x4_temp; + #if 0 - if ( fabs( mdet ) < 0.0000000001 ) - return 1; + if ( fabs( mdet ) < 0.0000000001 ) { + return 1; + } #endif - m4x4_assign(m4x4_temp, matrix); - - for ( i = 0; i < 4; i++ ) - for ( j = 0; j < 4; j++ ) - { - sign = 1 - ( (i +j) % 2 ) * 2; - - m4_submat( m4x4_temp, mtemp, i, j ); - - matrix[i+j*4] = ( m3_det( mtemp ) * sign ) / mdet; /* FIXME: try using * inverse det and see if speed/accuracy are good enough */ - } - - return 0; + m4x4_assign( m4x4_temp, matrix ); + + for ( i = 0; i < 4; i++ ) + for ( j = 0; j < 4; j++ ) + { + sign = 1 - ( ( i + j ) % 2 ) * 2; + + m4_submat( m4x4_temp, mtemp, i, j ); + + matrix[i + j * 4] = ( m3_det( mtemp ) * sign ) / mdet; /* FIXME: try using * inverse det and see if speed/accuracy are good enough */ + } + + return 0; } #if 0 -void m4x4_solve_ge(m4x4_t matrix, vec4_t x) -{ - int indx[4]; - int c,r; - int i; - int best; - float scale[4]; - float f, pivot; - float aug[4]; - float recip, ratio; - float* p; - - for(r=0; r<4; r++) - { - aug[r] = 0; - indx[r] = r; - } - - for (r=0; r<4; r++) - { - scale[r] = 0; - for (c=0; c<4; c++, p++) - { - if (fabs(*p) > scale[r]) - { - scale[r] = (float)fabs(*p); - } - } - } - - for (c=0; c<3; c++) - { - pivot = 0; - for (r=c; r<4; r++) - { - f = (float)fabs(matrix[(indx[r]<<2)+c]) / scale[indx[r]]; - if (f > pivot) - { - pivot = f; - best = r; - } - } - - i = indx[c]; - indx[c] = indx[best]; - indx[best] = i; - - recip = 1 / matrix[(indx[c]<<2)+c]; - - for (r=c+1; r<4; r++) - { - p = matrix + (indx[r]<<2); - ratio = p[c] * recip; - - for (i=c+1; i<4; i++) - p[i] -= ratio * matrix[(indx[c]<<2)+i]; - aug[indx[r]] -= ratio * aug[indx[c]]; - } - } - - x[indx[3]] = aug[indx[3]] / matrix[(indx[3]<<2)+3]; - for(r=2; r>=0; r--) - { - f = aug[indx[r]]; - p = matrix + (indx[r]<<2); - recip = 1 / p[r]; - for(c=(r+1); c<4; c++) - { - f -= (p[c] * x[indx[c]]); - } - x[indx[r]] = f * recip; - } +void m4x4_solve_ge( m4x4_t matrix, vec4_t x ){ + int indx[4]; + int c,r; + int i; + int best; + float scale[4]; + float f, pivot; + float aug[4]; + float recip, ratio; + float* p; + + for ( r = 0; r < 4; r++ ) + { + aug[r] = 0; + indx[r] = r; + } + + for ( r = 0; r < 4; r++ ) + { + scale[r] = 0; + for ( c = 0; c < 4; c++, p++ ) + { + if ( fabs( *p ) > scale[r] ) { + scale[r] = (float)fabs( *p ); + } + } + } + + for ( c = 0; c < 3; c++ ) + { + pivot = 0; + for ( r = c; r < 4; r++ ) + { + f = (float)fabs( matrix[( indx[r] << 2 ) + c] ) / scale[indx[r]]; + if ( f > pivot ) { + pivot = f; + best = r; + } + } + + i = indx[c]; + indx[c] = indx[best]; + indx[best] = i; + + recip = 1 / matrix[( indx[c] << 2 ) + c]; + + for ( r = c + 1; r < 4; r++ ) + { + p = matrix + ( indx[r] << 2 ); + ratio = p[c] * recip; + + for ( i = c + 1; i < 4; i++ ) + p[i] -= ratio * matrix[( indx[c] << 2 ) + i]; + aug[indx[r]] -= ratio * aug[indx[c]]; + } + } + + x[indx[3]] = aug[indx[3]] / matrix[( indx[3] << 2 ) + 3]; + for ( r = 2; r >= 0; r-- ) + { + f = aug[indx[r]]; + p = matrix + ( indx[r] << 2 ); + recip = 1 / p[r]; + for ( c = ( r + 1 ); c < 4; c++ ) + { + f -= ( p[c] * x[indx[c]] ); + } + x[indx[r]] = f * recip; + } } #endif #define N 3 -int matrix_solve_ge(vec_t* matrix, vec_t* aug, vec3_t x) -{ - int indx[N]; - int c,r; - int i; - int best; - float scale[N]; - float f, pivot; - float ratio; - float* p; - - for(r=0; r scale[r]) - { - scale[r] = (float)fabs(*p); - } - } - } - - for (c=0; c pivot) - { - pivot = f; - best = r; - } - } - - if(best == -1) return 1; - - i = indx[c]; - indx[c] = indx[best]; - indx[best] = i; - - for (r=c+1; r=0; r--) - { - f = aug[indx[r]]; - p = matrix + (indx[r]*N); - for(c=(r+1); c scale[r] ) { + scale[r] = (float)fabs( *p ); + } + } + } + + for ( c = 0; c < N; c++ ) + { + pivot = 0; + best = -1; + for ( r = c; r < N; r++ ) + { + f = (float)fabs( matrix[( indx[r] * N ) + c] ) / scale[indx[r]]; + if ( f > pivot ) { + pivot = f; + best = r; + } + } + + if ( best == -1 ) { + return 1; + } + + i = indx[c]; + indx[c] = indx[best]; + indx[best] = i; + + for ( r = c + 1; r < N; r++ ) + { + p = matrix + ( indx[r] * N ); + ratio = p[c] / matrix[( indx[c] * N ) + c]; + + for ( i = c + 1; i < N; i++ ) p[i] -= ratio * matrix[( indx[c] * N ) + i]; + aug[indx[r]] -= ratio * aug[indx[c]]; + } + } + + x[N - 1] = aug[indx[N - 1]] / matrix[( indx[N - 1] * N ) + N - 1]; + for ( r = 1; r >= 0; r-- ) + { + f = aug[indx[r]]; + p = matrix + ( indx[r] * N ); + for ( c = ( r + 1 ); c < N; c++ ) f -= ( p[c] * x[c] ); + x[r] = f / p[r]; + } + return 0; } #ifdef YOU_WANT_IT_TO_BORK - /* Gaussian elimination */ - for(i=0;i<4;i++) - { - for(j=(i+1);j<4;j++) - { - ratio = matrix[j][i] / matrix[i][i]; - for(count=i;count=0;i--) - { - temp = b[i]; - for(j=(i+1);j= 0; i-- ) { - m3x3_t planes; - vec3_t b; - VectorCopy(plane1, planes+0); - b[0] = plane1[3]; - VectorCopy(plane2, planes+3); - b[1] = plane2[3]; - VectorCopy(plane3, planes+6); - b[2] = plane3[3]; - - return matrix_solve_ge(planes, b, intersection); + temp = b[i]; + for ( j = ( i + 1 ); j < n; j++ ) + { + temp -= ( matrix[i][j] * x[j] ); + } + x[i] = temp / matrix[i][i]; +} +#endif + +int plane_intersect_planes( const vec4_t plane1, const vec4_t plane2, const vec4_t plane3, vec3_t intersection ){ + m3x3_t planes; + vec3_t b; + VectorCopy( plane1, planes + 0 ); + b[0] = plane1[3]; + VectorCopy( plane2, planes + 3 ); + b[1] = plane2[3]; + VectorCopy( plane3, planes + 6 ); + b[2] = plane3[3]; + + return matrix_solve_ge( planes, b, intersection ); } diff --git a/libs/mathlib/mathlib.c b/libs/mathlib/mathlib.c index 98fb972a..ce6cfdc2 100644 --- a/libs/mathlib/mathlib.c +++ b/libs/mathlib/mathlib.c @@ -1,23 +1,23 @@ /* -Copyright (C) 1999-2006 Id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ // mathlib.c -- math primitives #include "mathlib.h" @@ -31,25 +31,22 @@ const vec3_t g_vec3_axis_y = { 0, 1, 0, }; const vec3_t g_vec3_axis_z = { 0, 0, 1, }; /* -================ -VectorIsOnAxis -================ -*/ -qboolean VectorIsOnAxis(vec3_t v) -{ - int i, zeroComponentCount; + ================ + VectorIsOnAxis + ================ + */ +qboolean VectorIsOnAxis( vec3_t v ){ + int i, zeroComponentCount; zeroComponentCount = 0; - for (i = 0; i < 3; i++) + for ( i = 0; i < 3; i++ ) { - if (v[i] == 0.0) - { + if ( v[i] == 0.0 ) { zeroComponentCount++; } } - if (zeroComponentCount > 1) - { + if ( zeroComponentCount > 1 ) { // The zero vector will be on axis. return qtrue; } @@ -58,18 +55,16 @@ qboolean VectorIsOnAxis(vec3_t v) } /* -================ -VectorIsOnAxialPlane -================ -*/ -qboolean VectorIsOnAxialPlane(vec3_t v) -{ - int i; + ================ + VectorIsOnAxialPlane + ================ + */ +qboolean VectorIsOnAxialPlane( vec3_t v ){ + int i; - for (i = 0; i < 3; i++) + for ( i = 0; i < 3; i++ ) { - if (v[i] == 0.0) - { + if ( v[i] == 0.0 ) { // The zero vector will be on axial plane. return qtrue; } @@ -79,16 +74,15 @@ qboolean VectorIsOnAxialPlane(vec3_t v) } /* -================ -MakeNormalVectors - -Given a normalized forward vector, create two -other perpendicular vectors -================ -*/ -void MakeNormalVectors (vec3_t forward, vec3_t right, vec3_t up) -{ - float d; + ================ + MakeNormalVectors + + Given a normalized forward vector, create two + other perpendicular vectors + ================ + */ +void MakeNormalVectors( vec3_t forward, vec3_t right, vec3_t up ){ + float d; // this rotate and negate guarantees a vector // not colinear with the original @@ -96,71 +90,64 @@ void MakeNormalVectors (vec3_t forward, vec3_t right, vec3_t up) right[2] = forward[1]; right[0] = forward[2]; - d = DotProduct (right, forward); - VectorMA (right, -d, forward, right); - VectorNormalize (right, right); - CrossProduct (right, forward, up); + d = DotProduct( right, forward ); + VectorMA( right, -d, forward, right ); + VectorNormalize( right, right ); + CrossProduct( right, forward, up ); } -vec_t VectorLength(const vec3_t v) -{ - int i; - float length; - +vec_t VectorLength( const vec3_t v ){ + int i; + float length; + length = 0.0f; - for (i=0 ; i< 3 ; i++) - length += v[i]*v[i]; - length = (float)sqrt (length); + for ( i = 0 ; i < 3 ; i++ ) + length += v[i] * v[i]; + length = (float)sqrt( length ); return length; } -qboolean VectorCompare (const vec3_t v1, const vec3_t v2) -{ - int i; - - for (i=0 ; i<3 ; i++) - if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) +qboolean VectorCompare( const vec3_t v1, const vec3_t v2 ){ + int i; + + for ( i = 0 ; i < 3 ; i++ ) + if ( fabs( v1[i] - v2[i] ) > EQUAL_EPSILON ) { return qfalse; - + } + return qtrue; } -void VectorMA( const vec3_t va, vec_t scale, const vec3_t vb, vec3_t vc ) -{ - vc[0] = va[0] + scale*vb[0]; - vc[1] = va[1] + scale*vb[1]; - vc[2] = va[2] + scale*vb[2]; +void VectorMA( const vec3_t va, vec_t scale, const vec3_t vb, vec3_t vc ){ + vc[0] = va[0] + scale * vb[0]; + vc[1] = va[1] + scale * vb[1]; + vc[2] = va[2] + scale * vb[2]; } -void _CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross) -{ - cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; - cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; - cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; +void _CrossProduct( vec3_t v1, vec3_t v2, vec3_t cross ){ + cross[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross[2] = v1[0] * v2[1] - v1[1] * v2[0]; } -vec_t _DotProduct (vec3_t v1, vec3_t v2) -{ - return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; +vec_t _DotProduct( vec3_t v1, vec3_t v2 ){ + return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } -void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out) -{ - out[0] = va[0]-vb[0]; - out[1] = va[1]-vb[1]; - out[2] = va[2]-vb[2]; +void _VectorSubtract( vec3_t va, vec3_t vb, vec3_t out ){ + out[0] = va[0] - vb[0]; + out[1] = va[1] - vb[1]; + out[2] = va[2] - vb[2]; } -void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out) -{ - out[0] = va[0]+vb[0]; - out[1] = va[1]+vb[1]; - out[2] = va[2]+vb[2]; +void _VectorAdd( vec3_t va, vec3_t vb, vec3_t out ){ + out[0] = va[0] + vb[0]; + out[1] = va[1] + vb[1]; + out[2] = va[2] + vb[2]; } -void _VectorCopy (vec3_t in, vec3_t out) -{ +void _VectorCopy( vec3_t in, vec3_t out ){ out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; @@ -175,40 +162,38 @@ vec_t VectorNormalize( const vec3_t in, vec3_t out ) { // I don't see a reason why using a double outright (instead of using the // vec_accu_t alias for example) could possibly be frowned upon. - double x, y, z, length; + double x, y, z, length; x = (double) in[0]; y = (double) in[1]; z = (double) in[2]; - length = sqrt((x * x) + (y * y) + (z * z)); - if (length == 0) - { - VectorClear (out); + length = sqrt( ( x * x ) + ( y * y ) + ( z * z ) ); + if ( length == 0 ) { + VectorClear( out ); return 0; } - out[0] = (vec_t) (x / length); - out[1] = (vec_t) (y / length); - out[2] = (vec_t) (z / length); + out[0] = (vec_t) ( x / length ); + out[1] = (vec_t) ( y / length ); + out[2] = (vec_t) ( z / length ); return (vec_t) length; #else - vec_t length, ilength; + vec_t length, ilength; - length = (vec_t)sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]); - if (length == 0) - { - VectorClear (out); + length = (vec_t)sqrt( in[0] * in[0] + in[1] * in[1] + in[2] * in[2] ); + if ( length == 0 ) { + VectorClear( out ); return 0; } - ilength = 1.0f/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; + ilength = 1.0f / length; + out[0] = in[0] * ilength; + out[1] = in[1] * ilength; + out[2] = in[2] * ilength; return length; @@ -217,123 +202,115 @@ vec_t VectorNormalize( const vec3_t in, vec3_t out ) { } vec_t ColorNormalize( const vec3_t in, vec3_t out ) { - float max, scale; + float max, scale; max = in[0]; - if (in[1] > max) + if ( in[1] > max ) { max = in[1]; - if (in[2] > max) + } + if ( in[2] > max ) { max = in[2]; + } - if (max == 0) { + if ( max == 0 ) { out[0] = out[1] = out[2] = 1.0; return 0; } scale = 1.0f / max; - VectorScale (in, scale, out); + VectorScale( in, scale, out ); return max; } -void VectorInverse (vec3_t v) -{ +void VectorInverse( vec3_t v ){ v[0] = -v[0]; v[1] = -v[1]; v[2] = -v[2]; } /* -void VectorScale (vec3_t v, vec_t scale, vec3_t out) -{ - out[0] = v[0] * scale; - out[1] = v[1] * scale; - out[2] = v[2] * scale; + void VectorScale (vec3_t v, vec_t scale, vec3_t out) + { + out[0] = v[0] * scale; + out[1] = v[1] * scale; + out[2] = v[2] * scale; + } + */ + +void VectorRotate( vec3_t vIn, vec3_t vRotation, vec3_t out ){ + vec3_t vWork, va; + int nIndex[3][2]; + int i; + + VectorCopy( vIn, va ); + VectorCopy( va, vWork ); + nIndex[0][0] = 1; nIndex[0][1] = 2; + nIndex[1][0] = 2; nIndex[1][1] = 0; + nIndex[2][0] = 0; nIndex[2][1] = 1; + + for ( i = 0; i < 3; i++ ) + { + if ( vRotation[i] != 0 ) { + float dAngle = vRotation[i] * Q_PI / 180.0f; + float c = (vec_t)cos( dAngle ); + float s = (vec_t)sin( dAngle ); + vWork[nIndex[i][0]] = va[nIndex[i][0]] * c - va[nIndex[i][1]] * s; + vWork[nIndex[i][1]] = va[nIndex[i][0]] * s + va[nIndex[i][1]] * c; + } + VectorCopy( vWork, va ); + } + VectorCopy( vWork, out ); } -*/ -void VectorRotate (vec3_t vIn, vec3_t vRotation, vec3_t out) -{ - vec3_t vWork, va; - int nIndex[3][2]; - int i; - - VectorCopy(vIn, va); - VectorCopy(va, vWork); - nIndex[0][0] = 1; nIndex[0][1] = 2; - nIndex[1][0] = 2; nIndex[1][1] = 0; - nIndex[2][0] = 0; nIndex[2][1] = 1; - - for (i = 0; i < 3; i++) - { - if (vRotation[i] != 0) - { - float dAngle = vRotation[i] * Q_PI / 180.0f; - float c = (vec_t)cos(dAngle); - float s = (vec_t)sin(dAngle); - vWork[nIndex[i][0]] = va[nIndex[i][0]] * c - va[nIndex[i][1]] * s; - vWork[nIndex[i][1]] = va[nIndex[i][0]] * s + va[nIndex[i][1]] * c; - } - VectorCopy(vWork, va); - } - VectorCopy(vWork, out); -} - -void VectorRotateOrigin (vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out) -{ - vec3_t vTemp, vTemp2; - - VectorSubtract(vIn, vOrigin, vTemp); - VectorRotate(vTemp, vRotation, vTemp2); - VectorAdd(vTemp2, vOrigin, out); -} - -void VectorPolar(vec3_t v, float radius, float theta, float phi) -{ - v[0]=(float)(radius * cos(theta) * cos(phi)); - v[1]=(float)(radius * sin(theta) * cos(phi)); - v[2]=(float)(radius * sin(phi)); -} - -void VectorSnap(vec3_t v) -{ - int i; - for (i = 0; i < 3; i++) - { - v[i] = (vec_t)FLOAT_TO_INTEGER(v[i]); - } -} - -void VectorISnap(vec3_t point, int snap) -{ - int i; - for (i = 0 ;i < 3 ; i++) +void VectorRotateOrigin( vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out ){ + vec3_t vTemp, vTemp2; + + VectorSubtract( vIn, vOrigin, vTemp ); + VectorRotate( vTemp, vRotation, vTemp2 ); + VectorAdd( vTemp2, vOrigin, out ); +} + +void VectorPolar( vec3_t v, float radius, float theta, float phi ){ + v[0] = (float)( radius * cos( theta ) * cos( phi ) ); + v[1] = (float)( radius * sin( theta ) * cos( phi ) ); + v[2] = (float)( radius * sin( phi ) ); +} + +void VectorSnap( vec3_t v ){ + int i; + for ( i = 0; i < 3; i++ ) + { + v[i] = (vec_t)FLOAT_TO_INTEGER( v[i] ); + } +} + +void VectorISnap( vec3_t point, int snap ){ + int i; + for ( i = 0 ; i < 3 ; i++ ) { - point[i] = (vec_t)FLOAT_SNAP(point[i], snap); + point[i] = (vec_t)FLOAT_SNAP( point[i], snap ); } } -void VectorFSnap(vec3_t point, float snap) -{ - int i; - for (i = 0 ;i < 3 ; i++) +void VectorFSnap( vec3_t point, float snap ){ + int i; + for ( i = 0 ; i < 3 ; i++ ) { - point[i] = (vec_t)FLOAT_SNAP(point[i], snap); + point[i] = (vec_t)FLOAT_SNAP( point[i], snap ); } } -void _Vector5Add (vec5_t va, vec5_t vb, vec5_t out) -{ - out[0] = va[0]+vb[0]; - out[1] = va[1]+vb[1]; - out[2] = va[2]+vb[2]; - out[3] = va[3]+vb[3]; - out[4] = va[4]+vb[4]; +void _Vector5Add( vec5_t va, vec5_t vb, vec5_t out ){ + out[0] = va[0] + vb[0]; + out[1] = va[1] + vb[1]; + out[2] = va[2] + vb[2]; + out[3] = va[3] + vb[3]; + out[4] = va[4] + vb[4]; } -void _Vector5Scale (vec5_t v, vec_t scale, vec5_t out) -{ +void _Vector5Scale( vec5_t v, vec_t scale, vec5_t out ){ out[0] = v[0] * scale; out[1] = v[1] * scale; out[2] = v[2] * scale; @@ -341,8 +318,7 @@ void _Vector5Scale (vec5_t v, vec_t scale, vec5_t out) out[4] = v[4] * scale; } -void _Vector53Copy (vec5_t in, vec3_t out) -{ +void _Vector53Copy( vec5_t in, vec3_t out ){ out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; @@ -350,80 +326,73 @@ void _Vector53Copy (vec5_t in, vec3_t out) // NOTE: added these from Ritual's Q3Radiant #define INVALID_BOUNDS 99999 -void ClearBounds (vec3_t mins, vec3_t maxs) -{ +void ClearBounds( vec3_t mins, vec3_t maxs ){ mins[0] = mins[1] = mins[2] = +INVALID_BOUNDS; maxs[0] = maxs[1] = maxs[2] = -INVALID_BOUNDS; } -void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs) -{ - int i; - vec_t val; +void AddPointToBounds( vec3_t v, vec3_t mins, vec3_t maxs ){ + int i; + vec_t val; - if(mins[0] == +INVALID_BOUNDS) - if(maxs[0] == -INVALID_BOUNDS) - { - VectorCopy(v, mins); - VectorCopy(v, maxs); + if ( mins[0] == +INVALID_BOUNDS ) { + if ( maxs[0] == -INVALID_BOUNDS ) { + VectorCopy( v, mins ); + VectorCopy( v, maxs ); + } } - for (i=0 ; i<3 ; i++) + for ( i = 0 ; i < 3 ; i++ ) { val = v[i]; - if (val < mins[i]) + if ( val < mins[i] ) { mins[i] = val; - if (val > maxs[i]) + } + if ( val > maxs[i] ) { maxs[i] = val; + } } } -void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) -{ - float angle; - static float sr, sp, sy, cr, cp, cy; +void AngleVectors( vec3_t angles, vec3_t forward, vec3_t right, vec3_t up ){ + float angle; + static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs - - angle = angles[YAW] * (Q_PI*2.0f / 360.0f); - sy = (vec_t)sin(angle); - cy = (vec_t)cos(angle); - angle = angles[PITCH] * (Q_PI*2.0f / 360.0f); - sp = (vec_t)sin(angle); - cp = (vec_t)cos(angle); - angle = angles[ROLL] * (Q_PI*2.0f / 360.0f); - sr = (vec_t)sin(angle); - cr = (vec_t)cos(angle); - - if (forward) - { - forward[0] = cp*cy; - forward[1] = cp*sy; + + angle = angles[YAW] * ( Q_PI * 2.0f / 360.0f ); + sy = (vec_t)sin( angle ); + cy = (vec_t)cos( angle ); + angle = angles[PITCH] * ( Q_PI * 2.0f / 360.0f ); + sp = (vec_t)sin( angle ); + cp = (vec_t)cos( angle ); + angle = angles[ROLL] * ( Q_PI * 2.0f / 360.0f ); + sr = (vec_t)sin( angle ); + cr = (vec_t)cos( angle ); + + if ( forward ) { + forward[0] = cp * cy; + forward[1] = cp * sy; forward[2] = -sp; } - if (right) - { - right[0] = -sr*sp*cy+cr*sy; - right[1] = -sr*sp*sy-cr*cy; - right[2] = -sr*cp; + if ( right ) { + right[0] = -sr * sp * cy + cr * sy; + right[1] = -sr * sp * sy - cr * cy; + right[2] = -sr * cp; } - if (up) - { - up[0] = cr*sp*cy+sr*sy; - up[1] = cr*sp*sy-sr*cy; - up[2] = cr*cp; + if ( up ) { + up[0] = cr * sp * cy + sr * sy; + up[1] = cr * sp * sy - sr * cy; + up[2] = cr * cp; } } -void VectorToAngles( vec3_t vec, vec3_t angles ) -{ +void VectorToAngles( vec3_t vec, vec3_t angles ){ float forward; float yaw, pitch; - - if ( ( vec[ 0 ] == 0 ) && ( vec[ 1 ] == 0 ) ) - { + + if ( ( vec[ 0 ] == 0 ) && ( vec[ 1 ] == 0 ) ) { yaw = 0; - if ( vec[ 2 ] > 0 ) - { + if ( vec[ 2 ] > 0 ) { pitch = 90; } else @@ -434,34 +403,32 @@ void VectorToAngles( vec3_t vec, vec3_t angles ) else { yaw = (vec_t)atan2( vec[ 1 ], vec[ 0 ] ) * 180 / Q_PI; - if ( yaw < 0 ) - { + if ( yaw < 0 ) { yaw += 360; } - + forward = ( float )sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] ); pitch = (vec_t)atan2( vec[ 2 ], forward ) * 180 / Q_PI; - if ( pitch < 0 ) - { + if ( pitch < 0 ) { pitch += 360; } } - + angles[ 0 ] = pitch; angles[ 1 ] = yaw; angles[ 2 ] = 0; } /* -===================== -PlaneFromPoints + ===================== + PlaneFromPoints -Returns false if the triangle is degenrate. -The normal will point out of the clock for clockwise ordered points -===================== -*/ + Returns false if the triangle is degenrate. + The normal will point out of the clock for clockwise ordered points + ===================== + */ qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ) { - vec3_t d1, d2; + vec3_t d1, d2; VectorSubtract( b, a, d1 ); VectorSubtract( c, a, d2 ); @@ -487,47 +454,52 @@ void NormalToLatLong( const vec3_t normal, byte bytes[2] ) { if ( normal[0] == 0 && normal[1] == 0 ) { if ( normal[2] > 0 ) { bytes[0] = 0; - bytes[1] = 0; // lat = 0, long = 0 - } else { + bytes[1] = 0; // lat = 0, long = 0 + } + else { bytes[0] = 128; - bytes[1] = 0; // lat = 0, long = 128 + bytes[1] = 0; // lat = 0, long = 128 } - } else { - int a, b; + } + else { + int a, b; - a = (int)( RAD2DEG( atan2( normal[1], normal[0] ) ) * (255.0f / 360.0f ) ); + a = (int)( RAD2DEG( atan2( normal[1], normal[0] ) ) * ( 255.0f / 360.0f ) ); a &= 0xff; b = (int)( RAD2DEG( acos( normal[2] ) ) * ( 255.0f / 360.0f ) ); b &= 0xff; - bytes[0] = b; // longitude - bytes[1] = a; // lattitude + bytes[0] = b; // longitude + bytes[1] = a; // lattitude } } /* -================= -PlaneTypeForNormal -================= -*/ -int PlaneTypeForNormal (vec3_t normal) { - if (normal[0] == 1.0 || normal[0] == -1.0) + ================= + PlaneTypeForNormal + ================= + */ +int PlaneTypeForNormal( vec3_t normal ) { + if ( normal[0] == 1.0 || normal[0] == -1.0 ) { return PLANE_X; - if (normal[1] == 1.0 || normal[1] == -1.0) + } + if ( normal[1] == 1.0 || normal[1] == -1.0 ) { return PLANE_Y; - if (normal[2] == 1.0 || normal[2] == -1.0) + } + if ( normal[2] == 1.0 || normal[2] == -1.0 ) { return PLANE_Z; - + } + return PLANE_NON_AXIAL; } /* -================ -MatrixMultiply -================ -*/ -void MatrixMultiply(float in1[3][3], float in2[3][3], float out[3][3]) { + ================ + MatrixMultiply + ================ + */ +void MatrixMultiply( float in1[3][3], float in2[3][3], float out[3][3] ) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + @@ -548,8 +520,7 @@ void MatrixMultiply(float in1[3][3], float in2[3][3], float out[3][3]) { in1[2][2] * in2[2][2]; } -void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) -{ +void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ){ float d; vec3_t n; float inv_denom; @@ -570,9 +541,8 @@ void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) /* ** assumes "src" is normalized */ -void PerpendicularVector( vec3_t dst, const vec3_t src ) -{ - int pos; +void PerpendicularVector( vec3_t dst, const vec3_t src ){ + int pos; int i; vec_t minelem = 1.0F; vec3_t tempvec; @@ -582,8 +552,7 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) */ for ( pos = 0, i = 0; i < 3; i++ ) { - if ( fabs( src[i] ) < minelem ) - { + if ( fabs( src[i] ) < minelem ) { pos = i; minelem = (vec_t)fabs( src[i] ); } @@ -603,22 +572,22 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) } /* -=============== -RotatePointAroundVector + =============== + RotatePointAroundVector -This is not implemented very well... -=============== -*/ + This is not implemented very well... + =============== + */ void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, - float degrees ) { - float m[3][3]; - float im[3][3]; - float zrot[3][3]; - float tmpmat[3][3]; - float rot[3][3]; - int i; + float degrees ) { + float m[3][3]; + float im[3][3]; + float zrot[3][3]; + float tmpmat[3][3]; + float rot[3][3]; + int i; vec3_t vr, vup, vf; - float rad; + float rad; vf[0] = dir[0]; vf[1] = dir[1]; @@ -674,137 +643,125 @@ void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, //////////////////////////////////////////////////////////////////////////////// /* -================= -VectorLengthAccu -================= -*/ -vec_accu_t VectorLengthAccu(const vec3_accu_t v) -{ - return (vec_accu_t) sqrt((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])); + ================= + VectorLengthAccu + ================= + */ +vec_accu_t VectorLengthAccu( const vec3_accu_t v ){ + return (vec_accu_t) sqrt( ( v[0] * v[0] ) + ( v[1] * v[1] ) + ( v[2] * v[2] ) ); } /* -================= -DotProductAccu -================= -*/ -vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b) -{ - return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]); + ================= + DotProductAccu + ================= + */ +vec_accu_t DotProductAccu( const vec3_accu_t a, const vec3_accu_t b ){ + return ( a[0] * b[0] ) + ( a[1] * b[1] ) + ( a[2] * b[2] ); } /* -================= -VectorSubtractAccu -================= -*/ -void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ + ================= + VectorSubtractAccu + ================= + */ +void VectorSubtractAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ){ out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; } /* -================= -VectorAddAccu -================= -*/ -void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ + ================= + VectorAddAccu + ================= + */ +void VectorAddAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ){ out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; } /* -================= -VectorCopyAccu -================= -*/ -void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out) -{ + ================= + VectorCopyAccu + ================= + */ +void VectorCopyAccu( const vec3_accu_t in, vec3_accu_t out ){ out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; } /* -================= -VectorScaleAccu -================= -*/ -void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out) -{ + ================= + VectorScaleAccu + ================= + */ +void VectorScaleAccu( const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out ){ out[0] = in[0] * scaleFactor; out[1] = in[1] * scaleFactor; out[2] = in[2] * scaleFactor; } /* -================= -CrossProductAccu -================= -*/ -void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ - out[0] = (a[1] * b[2]) - (a[2] * b[1]); - out[1] = (a[2] * b[0]) - (a[0] * b[2]); - out[2] = (a[0] * b[1]) - (a[1] * b[0]); + ================= + CrossProductAccu + ================= + */ +void CrossProductAccu( const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out ){ + out[0] = ( a[1] * b[2] ) - ( a[2] * b[1] ); + out[1] = ( a[2] * b[0] ) - ( a[0] * b[2] ); + out[2] = ( a[0] * b[1] ) - ( a[1] * b[0] ); } /* -================= -Q_rintAccu -================= -*/ -vec_accu_t Q_rintAccu(vec_accu_t val) -{ - return (vec_accu_t) floor(val + 0.5); + ================= + Q_rintAccu + ================= + */ +vec_accu_t Q_rintAccu( vec_accu_t val ){ + return (vec_accu_t) floor( val + 0.5 ); } /* -================= -VectorCopyAccuToRegular -================= -*/ -void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out) -{ + ================= + VectorCopyAccuToRegular + ================= + */ +void VectorCopyAccuToRegular( const vec3_accu_t in, vec3_t out ){ out[0] = (vec_t) in[0]; out[1] = (vec_t) in[1]; out[2] = (vec_t) in[2]; } /* -================= -VectorCopyRegularToAccu -================= -*/ -void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out) -{ + ================= + VectorCopyRegularToAccu + ================= + */ +void VectorCopyRegularToAccu( const vec3_t in, vec3_accu_t out ){ out[0] = (vec_accu_t) in[0]; out[1] = (vec_accu_t) in[1]; out[2] = (vec_accu_t) in[2]; } /* -================= -VectorNormalizeAccu -================= -*/ -vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out) -{ + ================= + VectorNormalizeAccu + ================= + */ +vec_accu_t VectorNormalizeAccu( const vec3_accu_t in, vec3_accu_t out ){ // The sqrt() function takes double as an input and returns double as an // output according the the man pages on Debian and on FreeBSD. Therefore, // I don't see a reason why using a double outright (instead of using the // vec_accu_t alias for example) could possibly be frowned upon. - vec_accu_t length; + vec_accu_t length; - length = (vec_accu_t) sqrt((in[0] * in[0]) + (in[1] * in[1]) + (in[2] * in[2])); - if (length == 0) - { - VectorClear(out); + length = (vec_accu_t) sqrt( ( in[0] * in[0] ) + ( in[1] * in[1] ) + ( in[2] * in[2] ) ); + if ( length == 0 ) { + VectorClear( out ); return 0; } @@ -814,5 +771,3 @@ vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out) return length; } - - diff --git a/libs/mathlib/ray.c b/libs/mathlib/ray.c index bea7c5c5..f08a8842 100644 --- a/libs/mathlib/ray.c +++ b/libs/mathlib/ray.c @@ -1,140 +1,143 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "mathlib.h" #include vec3_t identity = { 0,0,0 }; -void ray_construct_for_vec3(ray_t *ray, const vec3_t origin, const vec3_t direction) -{ - VectorCopy(origin, ray->origin); - VectorCopy(direction, ray->direction); +void ray_construct_for_vec3( ray_t *ray, const vec3_t origin, const vec3_t direction ){ + VectorCopy( origin, ray->origin ); + VectorCopy( direction, ray->direction ); } - -void ray_transform(ray_t *ray, const m4x4_t matrix) -{ - m4x4_transform_point(matrix, ray->origin); - m4x4_transform_normal(matrix, ray->direction); + +void ray_transform( ray_t *ray, const m4x4_t matrix ){ + m4x4_transform_point( matrix, ray->origin ); + m4x4_transform_normal( matrix, ray->direction ); } -vec_t ray_intersect_point(const ray_t *ray, const vec3_t point, vec_t epsilon, vec_t divergence) -{ - vec3_t displacement; - vec_t depth; - - // calc displacement of test point from ray origin - VectorSubtract(point, ray->origin, displacement); - // calc length of displacement vector along ray direction - depth = DotProduct(displacement, ray->direction); - if(depth < 0.0f) return (vec_t)FLT_MAX; - // calc position of closest point on ray to test point - VectorMA (ray->origin, depth, ray->direction, displacement); - // calc displacement of test point from closest point - VectorSubtract(point, displacement, displacement); - // calc length of displacement, subtract depth-dependant epsilon - if (VectorLength(displacement) - (epsilon + (depth * divergence)) > 0.0f) return (vec_t)FLT_MAX; - return depth; +vec_t ray_intersect_point( const ray_t *ray, const vec3_t point, vec_t epsilon, vec_t divergence ){ + vec3_t displacement; + vec_t depth; + + // calc displacement of test point from ray origin + VectorSubtract( point, ray->origin, displacement ); + // calc length of displacement vector along ray direction + depth = DotProduct( displacement, ray->direction ); + if ( depth < 0.0f ) { + return (vec_t)FLT_MAX; + } + // calc position of closest point on ray to test point + VectorMA( ray->origin, depth, ray->direction, displacement ); + // calc displacement of test point from closest point + VectorSubtract( point, displacement, displacement ); + // calc length of displacement, subtract depth-dependant epsilon + if ( VectorLength( displacement ) - ( epsilon + ( depth * divergence ) ) > 0.0f ) { + return (vec_t)FLT_MAX; + } + return depth; } // Tomas Moller and Ben Trumbore. Fast, minimum storage ray-triangle intersection. Journal of graphics tools, 2(1):21-28, 1997 #define EPSILON 0.000001 -vec_t ray_intersect_triangle(const ray_t *ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2) -{ - float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; - float det,inv_det; - float u, v; - vec_t depth = (vec_t)FLT_MAX; - - /* find vectors for two edges sharing vert0 */ - VectorSubtract(vert1, vert0, edge1); - VectorSubtract(vert2, vert0, edge2); - - /* begin calculating determinant - also used to calculate U parameter */ - CrossProduct(ray->direction, edge2, pvec); - - /* if determinant is near zero, ray lies in plane of triangle */ - det = DotProduct(edge1, pvec); - - if (bCullBack == qtrue) - { - if (det < EPSILON) - return depth; - - // calculate distance from vert0 to ray origin - VectorSubtract(ray->origin, vert0, tvec); - - // calculate U parameter and test bounds - u = DotProduct(tvec, pvec); - if (u < 0.0 || u > det) - return depth; - - // prepare to test V parameter - CrossProduct(tvec, edge1, qvec); - - // calculate V parameter and test bounds - v = DotProduct(ray->direction, qvec); - if (v < 0.0 || u + v > det) - return depth; - - // calculate t, scale parameters, ray intersects triangle - depth = DotProduct(edge2, qvec); - inv_det = 1.0f / det; - depth *= inv_det; - //u *= inv_det; - //v *= inv_det; - } - else - { - /* the non-culling branch */ - if (det > -EPSILON && det < EPSILON) - return depth; - inv_det = 1.0f / det; - - /* calculate distance from vert0 to ray origin */ - VectorSubtract(ray->origin, vert0, tvec); - - /* calculate U parameter and test bounds */ - u = DotProduct(tvec, pvec) * inv_det; - if (u < 0.0 || u > 1.0) - return depth; - - /* prepare to test V parameter */ - CrossProduct(tvec, edge1, qvec); - - /* calculate V parameter and test bounds */ - v = DotProduct(ray->direction, qvec) * inv_det; - if (v < 0.0 || u + v > 1.0) - return depth; - - /* calculate t, ray intersects triangle */ - depth = DotProduct(edge2, qvec) * inv_det; - } - return depth; -} +vec_t ray_intersect_triangle( const ray_t *ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2 ){ + float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; + float det,inv_det; + float u, v; + vec_t depth = (vec_t)FLT_MAX; + + /* find vectors for two edges sharing vert0 */ + VectorSubtract( vert1, vert0, edge1 ); + VectorSubtract( vert2, vert0, edge2 ); + + /* begin calculating determinant - also used to calculate U parameter */ + CrossProduct( ray->direction, edge2, pvec ); + + /* if determinant is near zero, ray lies in plane of triangle */ + det = DotProduct( edge1, pvec ); + + if ( bCullBack == qtrue ) { + if ( det < EPSILON ) { + return depth; + } + + // calculate distance from vert0 to ray origin + VectorSubtract( ray->origin, vert0, tvec ); + + // calculate U parameter and test bounds + u = DotProduct( tvec, pvec ); + if ( u < 0.0 || u > det ) { + return depth; + } -vec_t ray_intersect_plane(const ray_t* ray, const vec3_t normal, vec_t dist) -{ - return -(DotProduct(normal, ray->origin) - dist) / DotProduct(ray->direction, normal); + // prepare to test V parameter + CrossProduct( tvec, edge1, qvec ); + + // calculate V parameter and test bounds + v = DotProduct( ray->direction, qvec ); + if ( v < 0.0 || u + v > det ) { + return depth; + } + + // calculate t, scale parameters, ray intersects triangle + depth = DotProduct( edge2, qvec ); + inv_det = 1.0f / det; + depth *= inv_det; + //u *= inv_det; + //v *= inv_det; + } + else + { + /* the non-culling branch */ + if ( det > -EPSILON && det < EPSILON ) { + return depth; + } + inv_det = 1.0f / det; + + /* calculate distance from vert0 to ray origin */ + VectorSubtract( ray->origin, vert0, tvec ); + + /* calculate U parameter and test bounds */ + u = DotProduct( tvec, pvec ) * inv_det; + if ( u < 0.0 || u > 1.0 ) { + return depth; + } + + /* prepare to test V parameter */ + CrossProduct( tvec, edge1, qvec ); + + /* calculate V parameter and test bounds */ + v = DotProduct( ray->direction, qvec ) * inv_det; + if ( v < 0.0 || u + v > 1.0 ) { + return depth; + } + + /* calculate t, ray intersects triangle */ + depth = DotProduct( edge2, qvec ) * inv_det; + } + return depth; } +vec_t ray_intersect_plane( const ray_t* ray, const vec3_t normal, vec_t dist ){ + return -( DotProduct( normal, ray->origin ) - dist ) / DotProduct( ray->direction, normal ); +} diff --git a/libs/md5lib.h b/libs/md5lib.h index f0aca115..db9fd333 100644 --- a/libs/md5lib.h +++ b/libs/md5lib.h @@ -1,50 +1,50 @@ /* - Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. + Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: - 1. The origin of this software must not be misrepresented; you must not + 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be + 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. + 3. This notice may not be removed or altered from any source distribution. - L. Peter Deutsch - ghost@aladdin.com + L. Peter Deutsch + ghost@aladdin.com */ /* $Id: md5lib.h,v 1.1.2.1 2003/07/19 23:25:50 spog Exp $ */ /* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.h is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Removed support for non-ANSI compilers; removed - references to Ghostscript; clarified derivation from RFC 1321; - now handles byte order either statically or dynamically. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke . - 1999-05-03 lpd Original version. + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.h is L. Peter Deutsch + . Other authors are noted in the change history + that follows (in reverse chronological order): + + 2002-04-13 lpd Removed support for non-ANSI compilers; removed + references to Ghostscript; clarified derivation from RFC 1321; + now handles byte order either statically or dynamically. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); + added conditionalization for C++ compilation from Martin + Purschke . + 1999-05-03 lpd Original version. */ #ifndef md5_INCLUDED @@ -65,24 +65,24 @@ typedef unsigned int md5_word_t; /* 32-bit word */ /* Define the state of the MD5 Algorithm. */ typedef struct md5_state_s { - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ + md5_word_t count[2]; /* message length in bits, lsw first */ + md5_word_t abcd[4]; /* digest buffer */ + md5_byte_t buf[64]; /* accumulate block */ } md5_state_t; #ifdef __cplusplus -extern "C" +extern "C" { #endif /* Initialize the algorithm. */ -void md5_init(md5_state_t *pms); +void md5_init( md5_state_t *pms ); /* Append a string to the message. */ -void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); +void md5_append( md5_state_t *pms, const md5_byte_t *data, int nbytes ); /* Finish the message and return the digest. */ -void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); +void md5_finish( md5_state_t * pms, md5_byte_t digest[16] ); #ifdef __cplusplus } /* end extern "C" */ diff --git a/libs/md5lib/md5lib.c b/libs/md5lib/md5lib.c index 60b45148..f30d0958 100644 --- a/libs/md5lib/md5lib.c +++ b/libs/md5lib/md5lib.c @@ -1,64 +1,64 @@ /* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. + Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: - 1. The origin of this software must not be misrepresented; you must not + 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be + 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. + 3. This notice may not be removed or altered from any source distribution. - L. Peter Deutsch - ghost@aladdin.com + L. Peter Deutsch + ghost@aladdin.com */ /* $Id: md5lib.c,v 1.1 2003/07/18 04:24:39 ydnar Exp $ */ /* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.c is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2003-07-17 ydnar added to gtkradiant project from + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.c is L. Peter Deutsch + . Other authors are noted in the change history + that follows (in reverse chronological order): + + 2003-07-17 ydnar added to gtkradiant project from http://sourceforge.net/projects/libmd5-rfc/ - 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order - either statically or dynamically; added missing #include - in library. - 2002-03-11 lpd Corrected argument list for main(), and added int return - type, in test program and T value program. - 2002-02-21 lpd Added missing #include in test program. - 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; made test program - self-checking. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). - 1999-05-03 lpd Original version. + 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order + either statically or dynamically; added missing #include + in library. + 2002-03-11 lpd Corrected argument list for main(), and added int return + type, in test program and T value program. + 2002-02-21 lpd Added missing #include in test program. + 2000-07-03 lpd Patched to eliminate warnings about "constant is + unsigned in ANSI C, signed in traditional"; made test program + self-checking. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). + 1999-05-03 lpd Original version. */ -#include "md5lib.h" /* ydnar */ +#include "md5lib.h" /* ydnar */ #include /* ydnar: gtkradiant endian picking */ #ifdef _SGI_SOURCE -#define __BIG_ENDIAN__ +#define __BIG_ENDIAN__ #endif #ifdef __BIG_ENDIAN__ @@ -68,328 +68,329 @@ #endif /* ydnar: end */ -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ +#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ #ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) +# define BYTE_ORDER ( ARCH_IS_BIG_ENDIAN ? 1 : -1 ) #else # define BYTE_ORDER 0 #endif -#define T_MASK ((md5_word_t)~0) -#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) -#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) +#define T_MASK ( ( md5_word_t ) ~0 ) +#define T1 /* 0xd76aa478 */ ( T_MASK ^ 0x28955b87 ) +#define T2 /* 0xe8c7b756 */ ( T_MASK ^ 0x173848a9 ) #define T3 0x242070db -#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) -#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) +#define T4 /* 0xc1bdceee */ ( T_MASK ^ 0x3e423111 ) +#define T5 /* 0xf57c0faf */ ( T_MASK ^ 0x0a83f050 ) #define T6 0x4787c62a -#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) -#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) +#define T7 /* 0xa8304613 */ ( T_MASK ^ 0x57cfb9ec ) +#define T8 /* 0xfd469501 */ ( T_MASK ^ 0x02b96afe ) #define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) -#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) -#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) +#define T10 /* 0x8b44f7af */ ( T_MASK ^ 0x74bb0850 ) +#define T11 /* 0xffff5bb1 */ ( T_MASK ^ 0x0000a44e ) +#define T12 /* 0x895cd7be */ ( T_MASK ^ 0x76a32841 ) #define T13 0x6b901122 -#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) -#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) +#define T14 /* 0xfd987193 */ ( T_MASK ^ 0x02678e6c ) +#define T15 /* 0xa679438e */ ( T_MASK ^ 0x5986bc71 ) #define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) -#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) +#define T17 /* 0xf61e2562 */ ( T_MASK ^ 0x09e1da9d ) +#define T18 /* 0xc040b340 */ ( T_MASK ^ 0x3fbf4cbf ) #define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) -#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) +#define T20 /* 0xe9b6c7aa */ ( T_MASK ^ 0x16493855 ) +#define T21 /* 0xd62f105d */ ( T_MASK ^ 0x29d0efa2 ) #define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) -#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) +#define T23 /* 0xd8a1e681 */ ( T_MASK ^ 0x275e197e ) +#define T24 /* 0xe7d3fbc8 */ ( T_MASK ^ 0x182c0437 ) #define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) -#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) +#define T26 /* 0xc33707d6 */ ( T_MASK ^ 0x3cc8f829 ) +#define T27 /* 0xf4d50d87 */ ( T_MASK ^ 0x0b2af278 ) #define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) -#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) +#define T29 /* 0xa9e3e905 */ ( T_MASK ^ 0x561c16fa ) +#define T30 /* 0xfcefa3f8 */ ( T_MASK ^ 0x03105c07 ) #define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) -#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) -#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) +#define T32 /* 0x8d2a4c8a */ ( T_MASK ^ 0x72d5b375 ) +#define T33 /* 0xfffa3942 */ ( T_MASK ^ 0x0005c6bd ) +#define T34 /* 0x8771f681 */ ( T_MASK ^ 0x788e097e ) #define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) -#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) +#define T36 /* 0xfde5380c */ ( T_MASK ^ 0x021ac7f3 ) +#define T37 /* 0xa4beea44 */ ( T_MASK ^ 0x5b4115bb ) #define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) -#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) +#define T39 /* 0xf6bb4b60 */ ( T_MASK ^ 0x0944b49f ) +#define T40 /* 0xbebfbc70 */ ( T_MASK ^ 0x4140438f ) #define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) -#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) +#define T42 /* 0xeaa127fa */ ( T_MASK ^ 0x155ed805 ) +#define T43 /* 0xd4ef3085 */ ( T_MASK ^ 0x2b10cf7a ) #define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) -#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) +#define T45 /* 0xd9d4d039 */ ( T_MASK ^ 0x262b2fc6 ) +#define T46 /* 0xe6db99e5 */ ( T_MASK ^ 0x1924661a ) #define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) -#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) +#define T48 /* 0xc4ac5665 */ ( T_MASK ^ 0x3b53a99a ) +#define T49 /* 0xf4292244 */ ( T_MASK ^ 0x0bd6ddbb ) #define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) -#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) +#define T51 /* 0xab9423a7 */ ( T_MASK ^ 0x546bdc58 ) +#define T52 /* 0xfc93a039 */ ( T_MASK ^ 0x036c5fc6 ) #define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) -#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) -#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) +#define T54 /* 0x8f0ccc92 */ ( T_MASK ^ 0x70f3336d ) +#define T55 /* 0xffeff47d */ ( T_MASK ^ 0x00100b82 ) +#define T56 /* 0x85845dd1 */ ( T_MASK ^ 0x7a7ba22e ) #define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) -#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) +#define T58 /* 0xfe2ce6e0 */ ( T_MASK ^ 0x01d3191f ) +#define T59 /* 0xa3014314 */ ( T_MASK ^ 0x5cfebceb ) #define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) -#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) +#define T61 /* 0xf7537e82 */ ( T_MASK ^ 0x08ac817d ) +#define T62 /* 0xbd3af235 */ ( T_MASK ^ 0x42c50dca ) #define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) +#define T64 /* 0xeb86d391 */ ( T_MASK ^ 0x14792c6e ) static void -md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) -{ - md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; - md5_word_t t; +md5_process( md5_state_t *pms, const md5_byte_t *data /*[64]*/ ){ + md5_word_t + a = pms->abcd[0], b = pms->abcd[1], + c = pms->abcd[2], d = pms->abcd[3]; + md5_word_t t; #if BYTE_ORDER > 0 - /* Define storage only for big-endian CPUs. */ - md5_word_t X[16]; + /* Define storage only for big-endian CPUs. */ + md5_word_t X[16]; #else - /* Define storage for little-endian or both types of CPUs. */ - md5_word_t xbuf[16]; - const md5_word_t *X; + /* Define storage for little-endian or both types of CPUs. */ + md5_word_t xbuf[16]; + const md5_word_t *X; #endif - { + { #if BYTE_ORDER == 0 - /* - * Determine dynamically whether this is a big-endian or - * little-endian machine, since we can use a more efficient - * algorithm on the latter. - */ - static const int w = 1; - - if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ + /* + * Determine dynamically whether this is a big-endian or + * little-endian machine, since we can use a more efficient + * algorithm on the latter. + */ + static const int w = 1; + + if ( *( (const md5_byte_t *)&w ) ) /* dynamic little-endian */ #endif -#if BYTE_ORDER <= 0 /* little-endian */ - { - /* - * On little-endian machines, we can process properly aligned - * data without copying it. - */ - if (!((data - (const md5_byte_t *)0) & 3)) { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } - } +#if BYTE_ORDER <= 0 /* little-endian */ + { + /* + * On little-endian machines, we can process properly aligned + * data without copying it. + */ + if ( !( ( data - (const md5_byte_t *)0 ) & 3 ) ) { + /* data are properly aligned */ + X = (const md5_word_t *)data; + } + else { + /* not aligned */ + memcpy( xbuf, data, 64 ); + X = xbuf; + } + } #endif #if BYTE_ORDER == 0 - else /* dynamic big-endian */ + else /* dynamic big-endian */ #endif -#if BYTE_ORDER >= 0 /* big-endian */ - { - /* - * On big-endian machines, we must arrange the bytes in the - * right order. - */ - const md5_byte_t *xp = data; - int i; +#if BYTE_ORDER >= 0 /* big-endian */ + { + /* + * On big-endian machines, we must arrange the bytes in the + * right order. + */ + const md5_byte_t *xp = data; + int i; # if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ + X = xbuf; /* (dynamic only) */ # else -# define xbuf X /* (static only) */ +# define xbuf X /* (static only) */ # endif - for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - } + for ( i = 0; i < 16; ++i, xp += 4 ) + xbuf[i] = xp[0] + ( xp[1] << 8 ) + ( xp[2] << 16 ) + ( xp[3] << 24 ); + } #endif - } - -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ -#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); - SET(c, d, a, b, 10, 17, T11); - SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); - SET(d, a, b, c, 13, 12, T14); - SET(c, d, a, b, 14, 17, T15); - SET(b, c, d, a, 15, 22, T16); + } + +#define ROTATE_LEFT( x, n ) ( ( ( x ) << ( n ) ) | ( ( x ) >> ( 32 - ( n ) ) ) ) + + /* Round 1. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ +#define F( x, y, z ) ( ( ( x ) & ( y ) ) | ( ~( x ) & ( z ) ) ) +#define SET( a, b, c, d, k, s, Ti ) \ + t = a + F( b,c,d ) + X[k] + Ti; \ + a = ROTATE_LEFT( t, s ) + b + /* Do the following 16 operations. */ + SET( a, b, c, d, 0, 7, T1 ); + SET( d, a, b, c, 1, 12, T2 ); + SET( c, d, a, b, 2, 17, T3 ); + SET( b, c, d, a, 3, 22, T4 ); + SET( a, b, c, d, 4, 7, T5 ); + SET( d, a, b, c, 5, 12, T6 ); + SET( c, d, a, b, 6, 17, T7 ); + SET( b, c, d, a, 7, 22, T8 ); + SET( a, b, c, d, 8, 7, T9 ); + SET( d, a, b, c, 9, 12, T10 ); + SET( c, d, a, b, 10, 17, T11 ); + SET( b, c, d, a, 11, 22, T12 ); + SET( a, b, c, d, 12, 7, T13 ); + SET( d, a, b, c, 13, 12, T14 ); + SET( c, d, a, b, 14, 17, T15 ); + SET( b, c, d, a, 15, 22, T16 ); #undef SET - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ -#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); - SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); - SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); - SET(b, c, d, a, 12, 20, T32); + /* Round 2. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ +#define G( x, y, z ) ( ( ( x ) & ( z ) ) | ( ( y ) & ~( z ) ) ) +#define SET( a, b, c, d, k, s, Ti ) \ + t = a + G( b,c,d ) + X[k] + Ti; \ + a = ROTATE_LEFT( t, s ) + b + /* Do the following 16 operations. */ + SET( a, b, c, d, 1, 5, T17 ); + SET( d, a, b, c, 6, 9, T18 ); + SET( c, d, a, b, 11, 14, T19 ); + SET( b, c, d, a, 0, 20, T20 ); + SET( a, b, c, d, 5, 5, T21 ); + SET( d, a, b, c, 10, 9, T22 ); + SET( c, d, a, b, 15, 14, T23 ); + SET( b, c, d, a, 4, 20, T24 ); + SET( a, b, c, d, 9, 5, T25 ); + SET( d, a, b, c, 14, 9, T26 ); + SET( c, d, a, b, 3, 14, T27 ); + SET( b, c, d, a, 8, 20, T28 ); + SET( a, b, c, d, 13, 5, T29 ); + SET( d, a, b, c, 2, 9, T30 ); + SET( c, d, a, b, 7, 14, T31 ); + SET( b, c, d, a, 12, 20, T32 ); #undef SET - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); - SET(c, d, a, b, 11, 16, T35); - SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); - SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); - SET(d, a, b, c, 12, 11, T46); - SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); + /* Round 3. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ +#define H( x, y, z ) ( ( x ) ^ ( y ) ^ ( z ) ) +#define SET( a, b, c, d, k, s, Ti ) \ + t = a + H( b,c,d ) + X[k] + Ti; \ + a = ROTATE_LEFT( t, s ) + b + /* Do the following 16 operations. */ + SET( a, b, c, d, 5, 4, T33 ); + SET( d, a, b, c, 8, 11, T34 ); + SET( c, d, a, b, 11, 16, T35 ); + SET( b, c, d, a, 14, 23, T36 ); + SET( a, b, c, d, 1, 4, T37 ); + SET( d, a, b, c, 4, 11, T38 ); + SET( c, d, a, b, 7, 16, T39 ); + SET( b, c, d, a, 10, 23, T40 ); + SET( a, b, c, d, 13, 4, T41 ); + SET( d, a, b, c, 0, 11, T42 ); + SET( c, d, a, b, 3, 16, T43 ); + SET( b, c, d, a, 6, 23, T44 ); + SET( a, b, c, d, 9, 4, T45 ); + SET( d, a, b, c, 12, 11, T46 ); + SET( c, d, a, b, 15, 16, T47 ); + SET( b, c, d, a, 2, 23, T48 ); #undef SET - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ -#define I(x, y, z) ((y) ^ ((x) | ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); - SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); - SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); - SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); - SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); - SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); + /* Round 4. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ +#define I( x, y, z ) ( ( y ) ^ ( ( x ) | ~( z ) ) ) +#define SET( a, b, c, d, k, s, Ti ) \ + t = a + I( b,c,d ) + X[k] + Ti; \ + a = ROTATE_LEFT( t, s ) + b + /* Do the following 16 operations. */ + SET( a, b, c, d, 0, 6, T49 ); + SET( d, a, b, c, 7, 10, T50 ); + SET( c, d, a, b, 14, 15, T51 ); + SET( b, c, d, a, 5, 21, T52 ); + SET( a, b, c, d, 12, 6, T53 ); + SET( d, a, b, c, 3, 10, T54 ); + SET( c, d, a, b, 10, 15, T55 ); + SET( b, c, d, a, 1, 21, T56 ); + SET( a, b, c, d, 8, 6, T57 ); + SET( d, a, b, c, 15, 10, T58 ); + SET( c, d, a, b, 6, 15, T59 ); + SET( b, c, d, a, 13, 21, T60 ); + SET( a, b, c, d, 4, 6, T61 ); + SET( d, a, b, c, 11, 10, T62 ); + SET( c, d, a, b, 2, 15, T63 ); + SET( b, c, d, a, 9, 21, T64 ); #undef SET - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->abcd[0] += a; - pms->abcd[1] += b; - pms->abcd[2] += c; - pms->abcd[3] += d; + /* Then perform the following additions. (That is increment each + of the four registers by the value it had before this block + was started.) */ + pms->abcd[0] += a; + pms->abcd[1] += b; + pms->abcd[2] += c; + pms->abcd[3] += d; } void -md5_init(md5_state_t *pms) -{ - pms->count[0] = pms->count[1] = 0; - pms->abcd[0] = 0x67452301; - pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->abcd[3] = 0x10325476; +md5_init( md5_state_t *pms ){ + pms->count[0] = pms->count[1] = 0; + pms->abcd[0] = 0x67452301; + pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; + pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; + pms->abcd[3] = 0x10325476; } void -md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) -{ - const md5_byte_t *p = data; - int left = nbytes; - int offset = (pms->count[0] >> 3) & 63; - md5_word_t nbits = (md5_word_t)(nbytes << 3); - - if (nbytes <= 0) - return; - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if (pms->count[0] < nbits) - pms->count[1]++; - - /* Process an initial partial block. */ - if (offset) { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - - memcpy(pms->buf + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buf); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); - - /* Process a final partial block. */ - if (left) - memcpy(pms->buf, p, left); +md5_append( md5_state_t *pms, const md5_byte_t *data, int nbytes ){ + const md5_byte_t *p = data; + int left = nbytes; + int offset = ( pms->count[0] >> 3 ) & 63; + md5_word_t nbits = (md5_word_t)( nbytes << 3 ); + + if ( nbytes <= 0 ) { + return; + } + + /* Update the message length. */ + pms->count[1] += nbytes >> 29; + pms->count[0] += nbits; + if ( pms->count[0] < nbits ) { + pms->count[1]++; + } + + /* Process an initial partial block. */ + if ( offset ) { + int copy = ( offset + nbytes > 64 ? 64 - offset : nbytes ); + + memcpy( pms->buf + offset, p, copy ); + if ( offset + copy < 64 ) { + return; + } + p += copy; + left -= copy; + md5_process( pms, pms->buf ); + } + + /* Process full blocks. */ + for (; left >= 64; p += 64, left -= 64 ) + md5_process( pms, p ); + + /* Process a final partial block. */ + if ( left ) { + memcpy( pms->buf, p, left ); + } } void -md5_finish(md5_state_t *pms, md5_byte_t digest[16]) -{ - static const md5_byte_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - md5_byte_t data[8]; - int i; - - /* Save the length before padding. */ - for (i = 0; i < 8; ++i) - data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); - /* Pad to 56 bytes mod 64. */ - md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); - /* Append the length. */ - md5_append(pms, data, 8); - for (i = 0; i < 16; ++i) - digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); +md5_finish( md5_state_t *pms, md5_byte_t digest[16] ){ + static const md5_byte_t pad[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + md5_byte_t data[8]; + int i; + + /* Save the length before padding. */ + for ( i = 0; i < 8; ++i ) + data[i] = (md5_byte_t)( pms->count[i >> 2] >> ( ( i & 3 ) << 3 ) ); + /* Pad to 56 bytes mod 64. */ + md5_append( pms, pad, ( ( 55 - ( pms->count[0] >> 3 ) ) & 63 ) + 1 ); + /* Append the length. */ + md5_append( pms, data, 8 ); + for ( i = 0; i < 16; ++i ) + digest[i] = (md5_byte_t)( pms->abcd[i >> 2] >> ( ( i & 3 ) << 3 ) ); } diff --git a/libs/memory/allocator.cpp b/libs/memory/allocator.cpp index 17fbdaca..0e4decf4 100644 --- a/libs/memory/allocator.cpp +++ b/libs/memory/allocator.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "memory/allocator.h" @@ -25,56 +25,52 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template struct Vector -{ - typedef std::vector > Type; +{ + typedef std::vector > Type; }; namespace { - class Bleh - { - int* m_blah; - public: - Bleh(int* blah) : m_blah(blah) - { - } - ~Bleh() - { - *m_blah = 15; - } - }; +class Bleh +{ +int* m_blah; +public: +Bleh( int* blah ) : m_blah( blah ){ +} +~Bleh(){ + *m_blah = 15; +} +}; - void TestAllocator() - { - Vector::Type test; +void TestAllocator(){ + Vector::Type test; - int i = 0; - test.push_back(Bleh(&i)); - } + int i = 0; + test.push_back( Bleh( &i ) ); +} - void TestNewDelete() - { - { - NamedAllocator allocator("test"); - int* p = NamedNew::type(allocator).scalar(); - //new int(); - NamedDelete::type(allocator).scalar(p); - } +void TestNewDelete(){ + { + NamedAllocator allocator( "test" ); + int* p = NamedNew::type( allocator ).scalar(); + //new int(); + NamedDelete::type( allocator ).scalar( p ); + } - { - int* p = New().scalar(3); - Delete().scalar(p); - } + { + int* p = New().scalar( 3 ); + Delete().scalar( p ); + } - { - int* p = New().scalar(int(15.9)); - Delete().scalar(p); - } + { + int* p = New().scalar( int(15.9) ); + Delete().scalar( p ); + } - { - int* p = New().vector(15); - // new int[15] - Delete().vector(p, 15); - } - } + { + int* p = New().vector( 15 ); + // new int[15] + Delete().vector( p, 15 ); + } +} } \ No newline at end of file diff --git a/libs/memory/allocator.h b/libs/memory/allocator.h index ebaeeb5b..bef7d7cb 100644 --- a/libs/memory/allocator.h +++ b/libs/memory/allocator.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MEMORY_ALLOCATOR_H) +#if !defined( INCLUDED_MEMORY_ALLOCATOR_H ) #define INCLUDED_MEMORY_ALLOCATOR_H #include @@ -38,72 +38,59 @@ class DefaultAllocator { public: - typedef Type value_type; - typedef value_type* pointer; - typedef const Type* const_pointer; - typedef Type& reference; - typedef const Type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - - template - struct rebind - { - typedef DefaultAllocator other; - }; - - DefaultAllocator() - { - } - DefaultAllocator(const DefaultAllocator&) - { - } - template DefaultAllocator(const DefaultAllocator&) - { - } - ~DefaultAllocator() - { - } - - pointer address(reference instance) const - { - return &instance; - } - const_pointer address(const_reference instance) const - { - return &instance; - } - Type* allocate(size_type size, const void* = 0) - { - return static_cast(::operator new(size * sizeof(Type))); - } - void deallocate(pointer p, size_type) - { - ::operator delete(p); - } - size_type max_size() const - { - return std::size_t(-1) / sizeof (Type); - } - void construct(pointer p, const Type& value) - { - new(p) Type(value); - } - void destroy(pointer p) - { - p->~Type(); - } +typedef Type value_type; +typedef value_type* pointer; +typedef const Type* const_pointer; +typedef Type& reference; +typedef const Type& const_reference; +typedef size_t size_type; +typedef ptrdiff_t difference_type; + +template +struct rebind +{ + typedef DefaultAllocator other; +}; + +DefaultAllocator(){ +} +DefaultAllocator( const DefaultAllocator& ){ +} +template DefaultAllocator( const DefaultAllocator& ){ +} +~DefaultAllocator(){ +} + +pointer address( reference instance ) const { + return &instance; +} +const_pointer address( const_reference instance ) const { + return &instance; +} +Type* allocate( size_type size, const void* = 0 ){ + return static_cast( ::operator new( size * sizeof( Type ) ) ); +} +void deallocate( pointer p, size_type ){ + ::operator delete( p ); +} +size_type max_size() const { + return std::size_t( -1 ) / sizeof( Type ); +} +void construct( pointer p, const Type& value ){ + new(p) Type( value ); +} +void destroy( pointer p ){ + p->~Type(); +} }; template -inline bool operator==(const DefaultAllocator&, const DefaultAllocator&) -{ - return true; +inline bool operator==( const DefaultAllocator&, const DefaultAllocator& ){ + return true; } template -inline bool operator==(const DefaultAllocator&, const OtherAllocator&) -{ - return false; +inline bool operator==( const DefaultAllocator&, const OtherAllocator& ){ + return false; } #endif @@ -112,79 +99,66 @@ inline bool operator==(const DefaultAllocator&, const OtherAllocator&) template class NamedAllocator : public DefaultAllocator { - typedef DefaultAllocator allocator_type; +typedef DefaultAllocator allocator_type; - const char* m_name; +const char* m_name; public: - typedef Type value_type; - typedef value_type* pointer; - typedef const Type* const_pointer; - typedef Type& reference; - typedef const Type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - - template - struct rebind - { - typedef NamedAllocator other; - }; - - explicit NamedAllocator(const char* name) : m_name(name) - { - } - NamedAllocator(const NamedAllocator& other) : m_name(other.m_name) - { - } - template NamedAllocator(const NamedAllocator& other) : m_name(other.m_name) - { - } - ~NamedAllocator() - { - } - - pointer address(reference instance) const - { - return allocator_type::address(instance); - } - const_pointer address(const_reference instance) const - { - return allocator_type::address(instance); - } - Type* allocate(size_type size, const void* = 0) - { - return allocator_type::allocate(size); - } - void deallocate(pointer p, size_type size) - { - allocator_type::deallocate(p, size); - } - size_type max_size() const - { - return allocator_type::max_size(); - } - void construct(pointer p, const Type& value) - { - allocator_type::construct(p, value); - } - void destroy(pointer p) - { - allocator_type::destroy(p); - } - - template - bool operator==(const NamedAllocator& other) - { - return true; - } - - // returns true if the allocators are not interchangeable - template - bool operator!=(const NamedAllocator& other) - { - return false; - } +typedef Type value_type; +typedef value_type* pointer; +typedef const Type* const_pointer; +typedef Type& reference; +typedef const Type& const_reference; +typedef size_t size_type; +typedef ptrdiff_t difference_type; + +template +struct rebind +{ + typedef NamedAllocator other; +}; + +explicit NamedAllocator( const char* name ) : m_name( name ){ +} +NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ +} +template NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ +} +~NamedAllocator(){ +} + +pointer address( reference instance ) const { + return allocator_type::address( instance ); +} +const_pointer address( const_reference instance ) const { + return allocator_type::address( instance ); +} +Type* allocate( size_type size, const void* = 0 ){ + return allocator_type::allocate( size ); +} +void deallocate( pointer p, size_type size ){ + allocator_type::deallocate( p, size ); +} +size_type max_size() const { + return allocator_type::max_size(); +} +void construct( pointer p, const Type& value ){ + allocator_type::construct( p, value ); +} +void destroy( pointer p ){ + allocator_type::destroy( p ); +} + +template +bool operator==( const NamedAllocator& other ){ + return true; +} + +// returns true if the allocators are not interchangeable +template +bool operator!=( const NamedAllocator& other ){ + return false; +} }; @@ -198,125 +172,105 @@ template class DefaultConstruct { public: - void operator()(Type& t) - { - constructor(t); - } +void operator()( Type& t ){ + constructor( t ); +} }; template class Construct { - const T1& other; +const T1& other; public: - Construct(const T1& other_) : other(other_) - { - } - void operator()(Type& t) - { - constructor(t, other); - } +Construct( const T1& other_ ) : other( other_ ){ +} +void operator()( Type& t ){ + constructor( t, other ); +} }; template class Destroy { public: - void operator()(Type& t) - { - destructor(t); - } +void operator()( Type& t ){ + destructor( t ); +} }; template > class New : public Allocator { public: - New() - { - } - explicit New(const Allocator& allocator) : Allocator(allocator) - { - } - - Type* scalar() - { - return new(Allocator::allocate(1)) Type(); - } - template - Type* scalar(const T1& t1) - { - return new(Allocator::allocate(1)) Type(t1); - } - template - Type* scalar(const T1& t1, const T2& t2) - { - return new(Allocator::allocate(1)) Type(t1, t2); - } - template - Type* scalar(const T1& t1, const T2& t2, const T3& t3) - { - return new(Allocator::allocate(1)) Type(t1, t2, t3); - } - template - Type* scalar(const T1& t1, const T2& t2, const T3& t3, const T4& t4) - { - return new(Allocator::allocate(1)) Type(t1, t2, t3, t4); - } - template - Type* scalar(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) - { - return new(Allocator::allocate(1)) Type(t1, t2, t3, t4, t5); - } - Type* vector(std::size_t size) - { +New(){ +} +explicit New( const Allocator& allocator ) : Allocator( allocator ){ +} + +Type* scalar(){ + return new( Allocator::allocate( 1 ) )Type(); +} +template +Type* scalar( const T1& t1 ){ + return new( Allocator::allocate( 1 ) )Type( t1 ); +} +template +Type* scalar( const T1& t1, const T2& t2 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2 ); +} +template +Type* scalar( const T1& t1, const T2& t2, const T3& t3 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3 ); +} +template +Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4 ); +} +template +Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ + return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4, t5 ); +} +Type* vector( std::size_t size ){ #if 1 - Type* p = Allocator::allocate(size); - std::for_each(p, p + size, DefaultConstruct()); - return p; + Type* p = Allocator::allocate( size ); + std::for_each( p, p + size, DefaultConstruct() ); + return p; #else - // this does not work with msvc71 runtime - return new(Allocator::allocate(size)) Type[size]; + // this does not work with msvc71 runtime + return new( Allocator::allocate( size ) )Type[size]; #endif - } - template - Type* vector(std::size_t size, const T1& t1) - { - Type* p = Allocator::allocate(size); - std::for_each(p, p + size, Construct(t1)); - return p; - } +} +template +Type* vector( std::size_t size, const T1& t1 ){ + Type* p = Allocator::allocate( size ); + std::for_each( p, p + size, Construct( t1 ) ); + return p; +} }; template > class Delete : public Allocator { public: - Delete() - { - } - explicit Delete(const Allocator& allocator) : Allocator(allocator) - { - } - - void scalar(Type* p) - { - if(p != 0) - { - p->~Type(); - Allocator::deallocate(p, 1); - } - } - void vector(Type* p, std::size_t size) - { - // '::operator delete' handles null - // 'std::allocator::deallocate' requires non-null - if(p != 0) - { - std::for_each(p, p + size, Destroy()); - Allocator::deallocate(p, size); - } - } +Delete(){ +} +explicit Delete( const Allocator& allocator ) : Allocator( allocator ){ +} + +void scalar( Type* p ){ + if ( p != 0 ) { + p->~Type(); + Allocator::deallocate( p, 1 ); + } +} +void vector( Type* p, std::size_t size ){ + // '::operator delete' handles null + // 'std::allocator::deallocate' requires non-null + if ( p != 0 ) { + std::for_each( p, p + size, Destroy() ); + Allocator::deallocate( p, size ); + } +} }; @@ -324,14 +278,14 @@ template class NamedNew { public: - typedef New > type; +typedef New > type; }; template class NamedDelete { public: - typedef Delete > type; +typedef Delete > type; }; #endif diff --git a/libs/moduleobservers.cpp b/libs/moduleobservers.cpp index a2d51f7d..56150f91 100644 --- a/libs/moduleobservers.cpp +++ b/libs/moduleobservers.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "moduleobservers.h" - diff --git a/libs/moduleobservers.h b/libs/moduleobservers.h index cd3bb1ef..1ee91e27 100644 --- a/libs/moduleobservers.h +++ b/libs/moduleobservers.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULEOBSERVERS_H) +#if !defined( INCLUDED_MODULEOBSERVERS_H ) #define INCLUDED_MODULEOBSERVERS_H #include "debugging/debugging.h" @@ -28,37 +28,32 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class ModuleObservers { - typedef std::set Observers; - Observers m_observers; +typedef std::set Observers; +Observers m_observers; public: - ~ModuleObservers() - { - ASSERT_MESSAGE(m_observers.empty(), "ModuleObservers::~ModuleObservers: observers still attached"); - } - void attach(ModuleObserver& observer) - { - ASSERT_MESSAGE(m_observers.find(&observer) == m_observers.end(), "ModuleObservers::attach: cannot attach observer"); - m_observers.insert(&observer); - } - void detach(ModuleObserver& observer) - { - ASSERT_MESSAGE(m_observers.find(&observer) != m_observers.end(), "ModuleObservers::detach: cannot detach observer"); - m_observers.erase(&observer); - } - void realise() - { - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->realise(); - } - } - void unrealise() - { - for(Observers::reverse_iterator i = m_observers.rbegin(); i != m_observers.rend(); ++i) - { - (*i)->unrealise(); - } - } +~ModuleObservers(){ + ASSERT_MESSAGE( m_observers.empty(), "ModuleObservers::~ModuleObservers: observers still attached" ); +} +void attach( ModuleObserver& observer ){ + ASSERT_MESSAGE( m_observers.find( &observer ) == m_observers.end(), "ModuleObservers::attach: cannot attach observer" ); + m_observers.insert( &observer ); +} +void detach( ModuleObserver& observer ){ + ASSERT_MESSAGE( m_observers.find( &observer ) != m_observers.end(), "ModuleObservers::detach: cannot detach observer" ); + m_observers.erase( &observer ); +} +void realise(){ + for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) + { + ( *i )->realise(); + } +} +void unrealise(){ + for ( Observers::reverse_iterator i = m_observers.rbegin(); i != m_observers.rend(); ++i ) + { + ( *i )->unrealise(); + } +} }; #endif diff --git a/libs/modulesystem/moduleregistry.cpp b/libs/modulesystem/moduleregistry.cpp index 9841f797..1e5bba6d 100644 --- a/libs/modulesystem/moduleregistry.cpp +++ b/libs/modulesystem/moduleregistry.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "moduleregistry.h" - diff --git a/libs/modulesystem/moduleregistry.h b/libs/modulesystem/moduleregistry.h index bd39cb06..abea5a05 100644 --- a/libs/modulesystem/moduleregistry.h +++ b/libs/modulesystem/moduleregistry.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULESYSTEM_MODULEREGISTRY_H) +#if !defined( INCLUDED_MODULESYSTEM_MODULEREGISTRY_H ) #define INCLUDED_MODULESYSTEM_MODULEREGISTRY_H #include "generic/static.h" @@ -28,25 +28,23 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class ModuleRegisterable { public: - virtual void selfRegister() = 0; +virtual void selfRegister() = 0; }; class ModuleRegistryList { - typedef std::list RegisterableModules; - RegisterableModules m_modules; +typedef std::list RegisterableModules; +RegisterableModules m_modules; public: - void addModule(ModuleRegisterable& module) - { - m_modules.push_back(&module); - } - void registerModules() const - { - for(RegisterableModules::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i) - { - (*i)->selfRegister(); - } - } +void addModule( ModuleRegisterable& module ){ + m_modules.push_back( &module ); +} +void registerModules() const { + for ( RegisterableModules::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + ( *i )->selfRegister(); + } +} }; typedef SmartStatic StaticModuleRegistryList; @@ -55,10 +53,9 @@ typedef SmartStatic StaticModuleRegistryList; class StaticRegisterModule : public StaticModuleRegistryList { public: - StaticRegisterModule(ModuleRegisterable& module) - { - StaticModuleRegistryList::instance().addModule(module); - } +StaticRegisterModule( ModuleRegisterable& module ){ + StaticModuleRegistryList::instance().addModule( module ); +} }; diff --git a/libs/modulesystem/modulesmap.cpp b/libs/modulesystem/modulesmap.cpp index 4edfc701..a80f2135 100644 --- a/libs/modulesystem/modulesmap.cpp +++ b/libs/modulesystem/modulesmap.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "modulesmap.h" diff --git a/libs/modulesystem/modulesmap.h b/libs/modulesystem/modulesmap.h index dfc2ea45..a48a083b 100644 --- a/libs/modulesystem/modulesmap.h +++ b/libs/modulesystem/modulesmap.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULESYSTEM_MODULESMAP_H) +#if !defined( INCLUDED_MODULESYSTEM_MODULESMAP_H ) #define INCLUDED_MODULESYSTEM_MODULESMAP_H #include "modulesystem.h" @@ -30,123 +30,106 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA template class ModulesMap : public Modules { - typedef std::map modules_t; - modules_t m_modules; +typedef std::map modules_t; +modules_t m_modules; public: - ~ModulesMap() - { - for(modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i) - { - (*i).second->release(); - } - } +~ModulesMap(){ + for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + ( *i ).second->release(); + } +} - typedef modules_t::const_iterator iterator; +typedef modules_t::const_iterator iterator; - iterator begin() const - { - return m_modules.begin(); - } - iterator end() const - { - return m_modules.end(); - } +iterator begin() const { + return m_modules.begin(); +} +iterator end() const { + return m_modules.end(); +} - void insert(const char* name, Module& module) - { - module.capture(); - if(globalModuleServer().getError()) - { - module.release(); - globalModuleServer().setError(false); - } - else - { - m_modules.insert(modules_t::value_type(name, &module)); - } - } +void insert( const char* name, Module& module ){ + module.capture(); + if ( globalModuleServer().getError() ) { + module.release(); + globalModuleServer().setError( false ); + } + else + { + m_modules.insert( modules_t::value_type( name, &module ) ); + } +} - Type* find(const char* name) - { - modules_t::iterator i = m_modules.find(name); - if(i != m_modules.end()) - { - return static_cast(Module_getTable(*(*i).second)); - } - return 0; - } +Type* find( const char* name ){ + modules_t::iterator i = m_modules.find( name ); + if ( i != m_modules.end() ) { + return static_cast( Module_getTable( *( *i ).second ) ); + } + return 0; +} - Type* findModule(const char* name) - { - return find(name); - } - void foreachModule(const typename Modules::Visitor& visitor) - { - for(modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i) - { - visitor.visit((*i).first.c_str(), *static_cast(Module_getTable(*(*i).second))); - } - } +Type* findModule( const char* name ){ + return find( name ); +} +void foreachModule( const typename Modules::Visitor& visitor ){ + for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) + { + visitor.visit( ( *i ).first.c_str(), *static_cast( Module_getTable( *( *i ).second ) ) ); + } +} }; template class InsertModules : public ModuleServer::Visitor { - ModulesMap& m_modules; +ModulesMap& m_modules; public: - InsertModules(ModulesMap& modules) - : m_modules(modules) - { - } - void visit(const char* name, Module& module) const - { - m_modules.insert(name, module); - } +InsertModules( ModulesMap& modules ) + : m_modules( modules ){ +} +void visit( const char* name, Module& module ) const { + m_modules.insert( name, module ); +} }; template class ModulesRef { - ModulesMap m_modules; +ModulesMap m_modules; public: - ModulesRef(const char* names) - { - if(!globalModuleServer().getError()) - { - if(string_equal(names, "*")) - { - InsertModules visitor(m_modules); - globalModuleServer().foreachModule(typename Type::Name(), typename Type::Version(), visitor); - } - else - { - StringTokeniser tokeniser(names); - for(;;) - { - const char* name = tokeniser.getToken(); - if(string_empty(name)) - { - break; - } - Module* module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - break; - } - else - { - m_modules.insert(name, *module); - } - } - } - } - } - ModulesMap& get() - { - return m_modules; - } +ModulesRef( const char* names ){ + if ( !globalModuleServer().getError() ) { + if ( string_equal( names, "*" ) ) { + InsertModules visitor( m_modules ); + globalModuleServer().foreachModule( typename Type::Name(), typename Type::Version(), visitor ); + } + else + { + StringTokeniser tokeniser( names ); + for (;; ) + { + const char* name = tokeniser.getToken(); + if ( string_empty( name ) ) { + break; + } + Module* module = globalModuleServer().findModule( typename Type::Name(), typename Type::Version(), name ); + if ( module == 0 ) { + globalModuleServer().setError( true ); + globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted( typename Type::Name() ) << " version=" << makeQuoted( typename Type::Version() ) << " name=" << makeQuoted( name ) << " - not found\n"; + break; + } + else + { + m_modules.insert( name, *module ); + } + } + } + } +} +ModulesMap& get(){ + return m_modules; +} }; #endif diff --git a/libs/modulesystem/singletonmodule.cpp b/libs/modulesystem/singletonmodule.cpp index 866c24fa..207051a8 100644 --- a/libs/modulesystem/singletonmodule.cpp +++ b/libs/modulesystem/singletonmodule.cpp @@ -1,23 +1,23 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "singletonmodule.h" #include "generic/constant.h" @@ -25,24 +25,22 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA class NullType { public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, ""); +INTEGER_CONSTANT( Version, 1 ); +STRING_CONSTANT( Name, "" ); }; class NullModule { public: - typedef NullType Type; - STRING_CONSTANT(Name, ""); - void* getTable() - { - return NULL; - } +typedef NullType Type; +STRING_CONSTANT( Name, "" ); +void* getTable(){ + return NULL; +} }; -void TEST_SINGLETONMODULE() -{ - SingletonModule null; - null.capture(); - null.release(); +void TEST_SINGLETONMODULE(){ + SingletonModule null; + null.capture(); + null.release(); } diff --git a/libs/modulesystem/singletonmodule.h b/libs/modulesystem/singletonmodule.h index f68587b7..6dd9c52a 100644 --- a/libs/modulesystem/singletonmodule.h +++ b/libs/modulesystem/singletonmodule.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_MODULESYSTEM_SINGLETONMODULE_H) +#if !defined( INCLUDED_MODULESYSTEM_SINGLETONMODULE_H ) #define INCLUDED_MODULESYSTEM_SINGLETONMODULE_H #include "modulesystem.h" @@ -32,38 +32,32 @@ template class DefaultAPIConstructor { public: - const char* getName() - { - return typename API::Name(); - } - - API* constructAPI(Dependencies& dependencies) - { - return new API; - } - void destroyAPI(API* api) - { - delete api; - } +const char* getName(){ + return typename API::Name(); +} + +API* constructAPI( Dependencies& dependencies ){ + return new API; +} +void destroyAPI( API* api ){ + delete api; +} }; template class DependenciesAPIConstructor { public: - const char* getName() - { - return typename API::Name(); - } - - API* constructAPI(Dependencies& dependencies) - { - return new API(dependencies); - } - void destroyAPI(API* api) - { - delete api; - } +const char* getName(){ + return typename API::Name(); +} + +API* constructAPI( Dependencies& dependencies ){ + return new API( dependencies ); +} +void destroyAPI( API* api ){ + delete api; +} }; class NullDependencies @@ -74,76 +68,63 @@ class NullDependencies template > class SingletonModule : public APIConstructor, public Module, public ModuleRegisterable { - Dependencies* m_dependencies; - API* m_api; - std::size_t m_refcount; - bool m_dependencyCheck; - bool m_cycleCheck; +Dependencies* m_dependencies; +API* m_api; +std::size_t m_refcount; +bool m_dependencyCheck; +bool m_cycleCheck; public: - typedef typename API::Type Type; - - SingletonModule() - : m_dependencies(0), m_api(0), m_refcount(0), m_dependencyCheck(false), m_cycleCheck(false) - { - } - explicit SingletonModule(const APIConstructor& constructor) - : APIConstructor(constructor), m_dependencies(0), m_api(0), m_refcount(0), m_dependencyCheck(false), m_cycleCheck(false) - { - } - ~SingletonModule() - { - ASSERT_MESSAGE(m_refcount == 0, "module still referenced at shutdown"); - } - - void selfRegister() - { - globalModuleServer().registerModule(typename Type::Name(), typename Type::Version(), APIConstructor::getName(), *this); - } - - Dependencies& getDependencies() - { - return *m_dependencies; - } - void* getTable() - { - if(m_api != 0) - { - return m_api->getTable(); - } - return 0; - } - void capture() - { - if(++m_refcount == 1) - { - globalOutputStream() << "Module Initialising: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - m_dependencies = new Dependencies(); - m_dependencyCheck = !globalModuleServer().getError(); - if(m_dependencyCheck) - { - m_api = APIConstructor::constructAPI(*m_dependencies); - globalOutputStream() << "Module Ready: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - } - else - { - globalOutputStream() << "Module Dependencies Failed: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - } - m_cycleCheck = true; - } - - ASSERT_MESSAGE(m_cycleCheck, "cyclic dependency detected"); - } - void release() - { - if(--m_refcount == 0) - { - if(m_dependencyCheck) - { - APIConstructor::destroyAPI(m_api); - } - delete m_dependencies; - } - } +typedef typename API::Type Type; + +SingletonModule() + : m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ +} +explicit SingletonModule( const APIConstructor& constructor ) + : APIConstructor( constructor ), m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ +} +~SingletonModule(){ + ASSERT_MESSAGE( m_refcount == 0, "module still referenced at shutdown" ); +} + +void selfRegister(){ + globalModuleServer().registerModule( typename Type::Name(), typename Type::Version(), APIConstructor::getName(), *this ); +} + +Dependencies& getDependencies(){ + return *m_dependencies; +} +void* getTable(){ + if ( m_api != 0 ) { + return m_api->getTable(); + } + return 0; +} +void capture(){ + if ( ++m_refcount == 1 ) { + globalOutputStream() << "Module Initialising: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + m_dependencies = new Dependencies(); + m_dependencyCheck = !globalModuleServer().getError(); + if ( m_dependencyCheck ) { + m_api = APIConstructor::constructAPI( *m_dependencies ); + globalOutputStream() << "Module Ready: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + } + else + { + globalOutputStream() << "Module Dependencies Failed: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + } + m_cycleCheck = true; + } + + ASSERT_MESSAGE( m_cycleCheck, "cyclic dependency detected" ); +} +void release(){ + if ( --m_refcount == 0 ) { + if ( m_dependencyCheck ) { + APIConstructor::destroyAPI( m_api ); + } + delete m_dependencies; + } +} }; diff --git a/libs/os/dir.cpp b/libs/os/dir.cpp index a775e5bd..8ab81296 100644 --- a/libs/os/dir.cpp +++ b/libs/os/dir.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "dir.h" - diff --git a/libs/os/dir.h b/libs/os/dir.h index bdb385e1..3047a028 100644 --- a/libs/os/dir.h +++ b/libs/os/dir.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_OS_DIR_H) +#if !defined( INCLUDED_OS_DIR_H ) #define INCLUDED_OS_DIR_H /// \file @@ -29,46 +29,39 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA typedef GDir Directory; -inline bool directory_good(Directory* directory) -{ - return directory != 0; +inline bool directory_good( Directory* directory ){ + return directory != 0; } -inline Directory* directory_open(const char* name) -{ - return g_dir_open(name, 0, 0); +inline Directory* directory_open( const char* name ){ + return g_dir_open( name, 0, 0 ); } -inline void directory_close(Directory* directory) -{ - g_dir_close(directory); +inline void directory_close( Directory* directory ){ + g_dir_close( directory ); } -inline const char* directory_read_and_increment(Directory* directory) -{ - return g_dir_read_name(directory); +inline const char* directory_read_and_increment( Directory* directory ){ + return g_dir_read_name( directory ); } template -void Directory_forEach(const char* path, const Functor& functor) -{ - Directory* dir = directory_open(path); - - if(directory_good(dir)) - { - for(;;) - { - const char* name = directory_read_and_increment(dir); - if(name == 0) - { - break; - } - - functor(name); - } - - directory_close(dir); - } +void Directory_forEach( const char* path, const Functor& functor ){ + Directory* dir = directory_open( path ); + + if ( directory_good( dir ) ) { + for (;; ) + { + const char* name = directory_read_and_increment( dir ); + if ( name == 0 ) { + break; + } + + functor( name ); + } + + directory_close( dir ); + } } diff --git a/libs/os/file.cpp b/libs/os/file.cpp index 766638f9..1855b5d1 100644 --- a/libs/os/file.cpp +++ b/libs/os/file.cpp @@ -1,23 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "file.h" - diff --git a/libs/os/file.h b/libs/os/file.h index b1290760..43381c63 100644 --- a/libs/os/file.h +++ b/libs/os/file.h @@ -1,37 +1,37 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined(INCLUDED_OS_FILE_H) +#if !defined( INCLUDED_OS_FILE_H ) #define INCLUDED_OS_FILE_H /// \file /// \brief OS file-system querying and manipulation. #if defined( WIN32 ) -#define S_ISDIR(mode) (mode & _S_IFDIR) +#define S_ISDIR( mode ) ( mode & _S_IFDIR ) #include // _access() #define F_OK 0x00 #define W_OK 0x02 #define R_OK 0x04 -#define access(path, mode) _access(path, mode) +#define access( path, mode ) _access( path, mode ) #else #include // access() #endif @@ -51,10 +51,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /// - The directory component of \p from identifies an existing directory which is accessible for writing. /// - The path \p to does not identify an existing file or directory. /// - The directory component of \p to identifies an existing directory which is accessible for writing. -inline bool file_move(const char* from, const char* to) -{ - ASSERT_MESSAGE(from != 0 && to != 0, "file_move: invalid path"); - return rename(from, to) == 0; +inline bool file_move( const char* from, const char* to ){ + ASSERT_MESSAGE( from != 0 && to != 0, "file_move: invalid path" ); + return rename( from, to ) == 0; } /// \brief Attempts to remove the file identified by \p path and returns true if the operation was successful. @@ -62,72 +61,63 @@ inline bool file_move(const char* from, const char* to) /// The operation will fail unless: /// - The \p path identifies an existing file. /// - The parent-directory component of \p path identifies an existing directory which is accessible for writing. -inline bool file_remove(const char* path) -{ - ASSERT_MESSAGE(path != 0, "file_remove: invalid path"); - return remove(path) == 0; +inline bool file_remove( const char* path ){ + ASSERT_MESSAGE( path != 0, "file_remove: invalid path" ); + return remove( path ) == 0; } namespace FileAccess { - enum Mode - { - Read = R_OK, - Write = W_OK, - ReadWrite = Read | Write, - Exists = F_OK - }; +enum Mode +{ + Read = R_OK, + Write = W_OK, + ReadWrite = Read | Write, + Exists = F_OK +}; } /// \brief Returns true if the file or directory identified by \p path exists and/or may be accessed for reading, writing or both, depending on the value of \p mode. -inline bool file_accessible(const char* path, FileAccess::Mode mode) -{ - ASSERT_MESSAGE(path != 0, "file_accessible: invalid path"); - return access(path, static_cast(mode)) == 0; +inline bool file_accessible( const char* path, FileAccess::Mode mode ){ + ASSERT_MESSAGE( path != 0, "file_accessible: invalid path" ); + return access( path, static_cast( mode ) ) == 0; } /// \brief Returns true if the file or directory identified by \p path exists and may be opened for reading. -inline bool file_readable(const char* path) -{ - return file_accessible(path, FileAccess::Read); +inline bool file_readable( const char* path ){ + return file_accessible( path, FileAccess::Read ); } /// \brief Returns true if the file or directory identified by \p path exists and may be opened for writing. -inline bool file_writeable(const char* path) -{ - return file_accessible(path, FileAccess::Write); +inline bool file_writeable( const char* path ){ + return file_accessible( path, FileAccess::Write ); } /// \brief Returns true if the file or directory identified by \p path exists. -inline bool file_exists(const char* path) -{ - return file_accessible(path, FileAccess::Exists); +inline bool file_exists( const char* path ){ + return file_accessible( path, FileAccess::Exists ); } /// \brief Returns true if the file or directory identified by \p path exists and is a directory. -inline bool file_is_directory(const char* path) -{ - ASSERT_MESSAGE(path != 0, "file_is_directory: invalid path"); - struct stat st; - if(stat(path, &st) == -1) - { - return false; - } - return S_ISDIR (st.st_mode) != 0; +inline bool file_is_directory( const char* path ){ + ASSERT_MESSAGE( path != 0, "file_is_directory: invalid path" ); + struct stat st; + if ( stat( path, &st ) == -1 ) { + return false; + } + return S_ISDIR( st.st_mode ) != 0; } typedef std::size_t FileSize; /// \brief Returns the size in bytes of the file identified by \p path, or 0 if the file was not found. -inline FileSize file_size(const char* path) -{ - ASSERT_MESSAGE(path != 0, "file_size: invalid path"); - struct stat st; - if(stat(path, &st) == -1) - { - return 0; - } - return st.st_size; +inline FileSize file_size( const char* path ){ + ASSERT_MESSAGE( path != 0, "file_size: invalid path" ); + struct stat st; + if ( stat( path, &st ) == -1 ) { + return 0; + } + return st.st_size; } /// Seconds elapsed since Jan 1, 1970 @@ -136,15 +126,13 @@ typedef std::time_t FileTime; const FileTime c_invalidFileTime = -1; /// \brief Returns the time that the file identified by \p path was last modified, or c_invalidFileTime if the file was not found. -inline FileTime file_modified(const char* path) -{ - ASSERT_MESSAGE(path != 0, "file_modified: invalid path"); - struct stat st; - if(stat(path, &st) == -1) - { - return c_invalidFileTime; - } - return st.st_mtime; +inline FileTime file_modified( const char* path ){ + ASSERT_MESSAGE( path != 0, "file_modified: invalid path" ); + struct stat st; + if ( stat( path, &st ) == -1 ) { + return c_invalidFileTime; + } + return st.st_mtime; } diff --git a/libs/os/path.cpp b/libs/os/path.cpp index ab03e1d2..b62c219e 100644 --- a/libs/os/path.cpp +++ b/libs/os/path.cpp @@ -1,22 +1,22 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #include "path.h" diff --git a/libs/os/path.h b/libs/os/path.h index 082b56fa..e3329a75 100644 --- a/libs/os/path.h +++ b/libs/os/path.h @@ -1,25 +1,25 @@ /* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. + Copyright (C) 2001-2006, William Joseph. + All Rights Reserved. -This file is part of GtkRadiant. + This file is part of GtkRadiant. -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. + GtkRadiant is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + GtkRadiant is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU General Public License + along with GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ -#if !defined (INCLUDED_OS_PATH_H) +#if !defined ( INCLUDED_OS_PATH_H ) #define INCLUDED_OS_PATH_H /// \file @@ -33,19 +33,18 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "string/string.h" -#if defined(WIN32) +#if defined( WIN32 ) #define OS_CASE_INSENSITIVE #endif /// \brief Returns true if \p path is lexicographically sorted before \p other. /// If both \p path and \p other refer to the same file, neither will be sorted before the other. /// O(n) -inline bool path_less(const char* path, const char* other) -{ -#if defined(OS_CASE_INSENSITIVE) - return string_less_nocase(path, other); +inline bool path_less( const char* path, const char* other ){ +#if defined( OS_CASE_INSENSITIVE ) + return string_less_nocase( path, other ); #else - return string_less(path, other); + return string_less( path, other ); #endif } @@ -53,230 +52,201 @@ inline bool path_less(const char* path, const char* other) /// Returns >0 if \p path is lexicographically greater than \p other. /// Returns 0 if both \p path and \p other refer to the same file. /// O(n) -inline int path_compare(const char* path, const char* other) -{ -#if defined(OS_CASE_INSENSITIVE) - return string_compare_nocase(path, other); +inline int path_compare( const char* path, const char* other ){ +#if defined( OS_CASE_INSENSITIVE ) + return string_compare_nocase( path, other ); #else - return string_compare(path, other); + return string_compare( path, other ); #endif } /// \brief Returns true if \p path and \p other refer to the same file or directory. /// O(n) -inline bool path_equal(const char* path, const char* other) -{ -#if defined(OS_CASE_INSENSITIVE) - return string_equal_nocase(path, other); +inline bool path_equal( const char* path, const char* other ){ +#if defined( OS_CASE_INSENSITIVE ) + return string_equal_nocase( path, other ); #else - return string_equal(path, other); + return string_equal( path, other ); #endif } /// \brief Returns true if the first \p n bytes of \p path and \p other form paths that refer to the same file or directory. /// If the paths are UTF-8 encoded, [\p path, \p path + \p n) must be a complete path. /// O(n) -inline bool path_equal_n(const char* path, const char* other, std::size_t n) -{ -#if defined(OS_CASE_INSENSITIVE) - return string_equal_nocase_n(path, other, n); +inline bool path_equal_n( const char* path, const char* other, std::size_t n ){ +#if defined( OS_CASE_INSENSITIVE ) + return string_equal_nocase_n( path, other, n ); #else - return string_equal_n(path, other, n); + return string_equal_n( path, other, n ); #endif } /// \brief Returns true if \p path is a fully qualified file-system path. /// O(1) -inline bool path_is_absolute(const char* path) -{ -#if defined(WIN32) - return path[0] == '/' - || (path[0] != '\0' && path[1] == ':'); // local drive -#elif defined(POSIX) - return path[0] == '/'; +inline bool path_is_absolute( const char* path ){ +#if defined( WIN32 ) + return path[0] == '/' + || ( path[0] != '\0' && path[1] == ':' ); // local drive +#elif defined( POSIX ) + return path[0] == '/'; #endif } /// \brief Returns true if \p path is a directory. /// O(n) -inline bool path_is_directory(const char* path) -{ - std::size_t length = strlen(path); - if(length > 0) - { - return path[length-1] == '/'; - } - return false; +inline bool path_is_directory( const char* path ){ + std::size_t length = strlen( path ); + if ( length > 0 ) { + return path[length - 1] == '/'; + } + return false; } /// \brief Returns a pointer to the first character of the component of \p path following the first directory component. /// O(n) -inline const char* path_remove_directory(const char* path) -{ - const char* first_separator = strchr(path, '/'); - if(first_separator != 0) - { - return ++first_separator; - } - return ""; +inline const char* path_remove_directory( const char* path ){ + const char* first_separator = strchr( path, '/' ); + if ( first_separator != 0 ) { + return ++first_separator; + } + return ""; } /// \brief Returns a pointer to the first character of the filename component of \p path. /// O(n) -inline const char* path_get_filename_start(const char* path) -{ - { - const char* last_forward_slash = strrchr(path, '/'); - if(last_forward_slash != 0) - { - return last_forward_slash + 1; - } - } - - // not strictly necessary,since paths should not contain '\' - { - const char* last_backward_slash = strrchr(path, '\\'); - if(last_backward_slash != 0) - { - return last_backward_slash + 1; - } - } - - return path; +inline const char* path_get_filename_start( const char* path ){ + { + const char* last_forward_slash = strrchr( path, '/' ); + if ( last_forward_slash != 0 ) { + return last_forward_slash + 1; + } + } + + // not strictly necessary,since paths should not contain '\' + { + const char* last_backward_slash = strrchr( path, '\\' ); + if ( last_backward_slash != 0 ) { + return last_backward_slash + 1; + } + } + + return path; } /// \brief Returns a pointer to the character after the end of the filename component of \p path - either the extension separator or the terminating null character. /// O(n) -inline const char* path_get_filename_base_end(const char* path) -{ - const char* last_period = strrchr(path_get_filename_start(path), '.'); - return (last_period != 0) ? last_period : path + string_length(path); +inline const char* path_get_filename_base_end( const char* path ){ + const char* last_period = strrchr( path_get_filename_start( path ), '.' ); + return ( last_period != 0 ) ? last_period : path + string_length( path ); } /// \brief Returns the length of the filename component (not including extension) of \p path. /// O(n) -inline std::size_t path_get_filename_base_length(const char* path) -{ - return path_get_filename_base_end(path) - path; +inline std::size_t path_get_filename_base_length( const char* path ){ + return path_get_filename_base_end( path ) - path; } /// \brief If \p path is a child of \p base, returns the subpath relative to \p base, else returns \p path. /// O(n) -inline const char* path_make_relative(const char* path, const char* base) -{ - const std::size_t length = string_length(base); - if(path_equal_n(path, base, length)) - { - return path + length; - } - return path; +inline const char* path_make_relative( const char* path, const char* base ){ + const std::size_t length = string_length( base ); + if ( path_equal_n( path, base, length ) ) { + return path + length; + } + return path; } /// \brief Returns a pointer to the first character of the file extension of \p path, or "" if not found. /// O(n) -inline const char* path_get_extension(const char* path) -{ - const char* last_period = strrchr(path_get_filename_start(path), '.'); - if(last_period != 0) - { - return ++last_period; - } - return ""; +inline const char* path_get_extension( const char* path ){ + const char* last_period = strrchr( path_get_filename_start( path ), '.' ); + if ( last_period != 0 ) { + return ++last_period; + } + return ""; } /// \brief Returns true if \p extension is of the same type as \p other. /// O(n) -inline bool extension_equal(const char* extension, const char* other) -{ - return path_equal(extension, other); +inline bool extension_equal( const char* extension, const char* other ){ + return path_equal( extension, other ); } template class MatchFileExtension { - const char* m_extension; - const Functor& m_functor; +const char* m_extension; +const Functor& m_functor; public: - MatchFileExtension(const char* extension, const Functor& functor) : m_extension(extension), m_functor(functor) - { - } - void operator()(const char* name) const - { - const char* extension = path_get_extension(name); - if(extension_equal(extension, m_extension)) - { - m_functor(name); - } - } +MatchFileExtension( const char* extension, const Functor& functor ) : m_extension( extension ), m_functor( functor ){ +} +void operator()( const char* name ) const { + const char* extension = path_get_extension( name ); + if ( extension_equal( extension, m_extension ) ) { + m_functor( name ); + } +} }; /// \brief A functor which invokes its contained \p functor if the \p name argument matches its \p extension. template -inline MatchFileExtension matchFileExtension(const char* extension, const Functor& functor) -{ - return MatchFileExtension(extension, functor); +inline MatchFileExtension matchFileExtension( const char* extension, const Functor& functor ){ + return MatchFileExtension( extension, functor ); } class PathCleaned { public: - const char* m_path; - PathCleaned(const char* path) : m_path(path) - { - } +const char* m_path; +PathCleaned( const char* path ) : m_path( path ){ +} }; /// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators. template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const PathCleaned& path) -{ - const char* i = path.m_path; - for(; *i != '\0'; ++i) - { - if(*i == '\\') - { - ostream << '/'; - } - else - { - ostream << *i; - } - } - return ostream; +TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const PathCleaned& path ){ + const char* i = path.m_path; + for (; *i != '\0'; ++i ) + { + if ( *i == '\\' ) { + ostream << '/'; + } + else + { + ostream << *i; + } + } + return ostream; } class DirectoryCleaned { public: - const char* m_path; - DirectoryCleaned(const char* path) : m_path(path) - { - } +const char* m_path; +DirectoryCleaned( const char* path ) : m_path( path ){ +} }; /// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators, and appends a separator if necessary. template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const DirectoryCleaned& path) -{ - const char* i = path.m_path; - for(; *i != '\0'; ++i) - { - if(*i == '\\') - { - ostream << '/'; - } - else - { - ostream << *i; - } - } - char c = *(i - 1); - if(c != '/' && c != '\\') - { - ostream << '/'; - } - return ostream; +TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const DirectoryCleaned& path ){ + const char* i = path.m_path; + for (; *i != '\0'; ++i ) + { + if ( *i == '\\' ) { + ostream << '/'; + } + else + { + ostream << *i; + } + } + char c = *( i - 1 ); + if ( c != '/' && c != '\\' ) { + ostream << '/'; + } + return ostream; } diff --git a/libs/picomodel.h b/libs/picomodel.h index a771e943..370afef9 100644 --- a/libs/picomodel.h +++ b/libs/picomodel.h @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -48,28 +48,28 @@ extern "C" /* version */ -#define PICOMODEL_VERSION "0.8.20" +#define PICOMODEL_VERSION "0.8.20" /* constants */ -#define PICO_GROW_SHADERS 16 -#define PICO_GROW_SURFACES 16 -#define PICO_GROW_VERTEXES 1024 -#define PICO_GROW_INDEXES 1024 -#define PICO_GROW_ARRAYS 8 -#define PICO_GROW_FACES 256 -#define PICO_MAX_SPECIAL 8 -#define PICO_MAX_DEFAULT_EXTS 4 /* max default extensions per module */ +#define PICO_GROW_SHADERS 16 +#define PICO_GROW_SURFACES 16 +#define PICO_GROW_VERTEXES 1024 +#define PICO_GROW_INDEXES 1024 +#define PICO_GROW_ARRAYS 8 +#define PICO_GROW_FACES 256 +#define PICO_MAX_SPECIAL 8 +#define PICO_MAX_DEFAULT_EXTS 4 /* max default extensions per module */ /* types */ -typedef unsigned char picoByte_t; -typedef float picoVec_t; -typedef float picoVec2_t[ 2 ]; -typedef float picoVec3_t[ 3 ]; -typedef float picoVec4_t[ 4 ]; -typedef picoByte_t picoColor_t[ 4 ]; -typedef int picoIndex_t; +typedef unsigned char picoByte_t; +typedef float picoVec_t; +typedef float picoVec2_t[ 2 ]; +typedef float picoVec3_t[ 3 ]; +typedef float picoVec4_t[ 4 ]; +typedef picoByte_t picoColor_t[ 4 ]; +typedef int picoIndex_t; typedef enum { @@ -89,73 +89,73 @@ typedef enum } picoPrintLevel_t; -typedef struct picoSurface_s picoSurface_t; -typedef struct picoShader_s picoShader_t; -typedef struct picoModel_s picoModel_t; -typedef struct picoModule_s picoModule_t; +typedef struct picoSurface_s picoSurface_t; +typedef struct picoShader_s picoShader_t; +typedef struct picoModel_s picoModel_t; +typedef struct picoModule_s picoModule_t; struct picoSurface_s { - void *data; - - picoModel_t *model; /* owner model */ - - picoSurfaceType_t type; - char *name; /* sea: surface name */ - picoShader_t *shader; /* ydnar: changed to ptr */ - - int numVertexes, maxVertexes; - picoVec3_t *xyz; - picoVec3_t *normal; - picoIndex_t *smoothingGroup; - - int numSTArrays, maxSTArrays; - picoVec2_t **st; - - int numColorArrays, maxColorArrays; - picoColor_t **color; - - int numIndexes, maxIndexes; - picoIndex_t *index; - - int numFaceNormals, maxFaceNormals; - picoVec3_t *faceNormal; - - int special[ PICO_MAX_SPECIAL ]; + void *data; + + picoModel_t *model; /* owner model */ + + picoSurfaceType_t type; + char *name; /* sea: surface name */ + picoShader_t *shader; /* ydnar: changed to ptr */ + + int numVertexes, maxVertexes; + picoVec3_t *xyz; + picoVec3_t *normal; + picoIndex_t *smoothingGroup; + + int numSTArrays, maxSTArrays; + picoVec2_t **st; + + int numColorArrays, maxColorArrays; + picoColor_t **color; + + int numIndexes, maxIndexes; + picoIndex_t *index; + + int numFaceNormals, maxFaceNormals; + picoVec3_t *faceNormal; + + int special[ PICO_MAX_SPECIAL ]; }; /* seaw0lf */ struct picoShader_s { - picoModel_t *model; /* owner model */ - - char *name; /* shader name */ - char *mapName; /* shader file name (name of diffuse texturemap) */ - picoColor_t ambientColor; /* ambient color of mesh (rgba) */ - picoColor_t diffuseColor; /* diffuse color of mesh (rgba) */ - picoColor_t specularColor; /* specular color of mesh (rgba) */ - float transparency; /* transparency (0..1; 1 = 100% transparent) */ - float shininess; /* shininess (0..128; 128 = 100% shiny) */ + picoModel_t *model; /* owner model */ + + char *name; /* shader name */ + char *mapName; /* shader file name (name of diffuse texturemap) */ + picoColor_t ambientColor; /* ambient color of mesh (rgba) */ + picoColor_t diffuseColor; /* diffuse color of mesh (rgba) */ + picoColor_t specularColor; /* specular color of mesh (rgba) */ + float transparency; /* transparency (0..1; 1 = 100% transparent) */ + float shininess; /* shininess (0..128; 128 = 100% shiny) */ }; struct picoModel_s { - void *data; - char *name; /* model name */ - char *fileName; /* sea: model file name */ - int frameNum; /* sea: renamed to frameNum */ - int numFrames; /* sea: number of frames */ - picoVec3_t mins; - picoVec3_t maxs; - - int numShaders, maxShaders; - picoShader_t **shader; - - int numSurfaces, maxSurfaces; - picoSurface_t **surface; - - const picoModule_t *module; /* sea */ + void *data; + char *name; /* model name */ + char *fileName; /* sea: model file name */ + int frameNum; /* sea: renamed to frameNum */ + int numFrames; /* sea: number of frames */ + picoVec3_t mins; + picoVec3_t maxs; + + int numShaders, maxShaders; + picoShader_t **shader; + + int numSurfaces, maxSurfaces; + picoSurface_t **surface; + + const picoModule_t *module; /* sea */ }; @@ -165,12 +165,12 @@ struct picoModel_s /* that there was an error. */ enum { - PICO_PMV_OK, /* file valid */ - PICO_PMV_ERROR, /* file not valid */ - PICO_PMV_ERROR_IDENT, /* unknown file magic (aka ident) */ - PICO_PMV_ERROR_VERSION, /* unsupported file version */ - PICO_PMV_ERROR_SIZE, /* file size error */ - PICO_PMV_ERROR_MEMORY, /* out of memory error */ + PICO_PMV_OK, /* file valid */ + PICO_PMV_ERROR, /* file not valid */ + PICO_PMV_ERROR_IDENT, /* unknown file magic (aka ident) */ + PICO_PMV_ERROR_VERSION, /* unsupported file version */ + PICO_PMV_ERROR_SIZE, /* file size error */ + PICO_PMV_ERROR_MEMORY, /* out of memory error */ }; /* convenience (makes it easy to add new params to the callbacks) */ @@ -184,164 +184,164 @@ enum void #define PM_PARAMS_SAVE \ - const char *fileName, picoModel_t *model + const char *fileName, picoModel_t * model /* pico file format module structure */ struct picoModule_s { - char *version; /* internal module version (e.g. '1.5-b2') */ + char *version; /* internal module version (e.g. '1.5-b2') */ - char *displayName; /* string used to display in guis, etc. */ - char *authorName; /* author name (eg. 'My Real Name') */ - char *copyright; /* copyright year and holder (eg. '2002 My Company') */ + char *displayName; /* string used to display in guis, etc. */ + char *authorName; /* author name (eg. 'My Real Name') */ + char *copyright; /* copyright year and holder (eg. '2002 My Company') */ - char *defaultExts[ PICO_MAX_DEFAULT_EXTS ]; /* default file extensions used by this file type */ - int (*canload)( PM_PARAMS_CANLOAD ); /* checks whether module can load given file (returns PMVR_*) */ - picoModel_t *(*load)( PM_PARAMS_LOAD ); /* parses model file data */ - int (*cansave)( PM_PARAMS_CANSAVE ); /* checks whether module can save (returns 1 or 0 and might spit out a message) */ - int (*save)( PM_PARAMS_SAVE ); /* saves a pico model in module's native model format */ + char *defaultExts[ PICO_MAX_DEFAULT_EXTS ]; /* default file extensions used by this file type */ + int ( *canload )( PM_PARAMS_CANLOAD ); /* checks whether module can load given file (returns PMVR_*) */ + picoModel_t *( *load )( PM_PARAMS_LOAD ); /* parses model file data */ + int ( *cansave )( PM_PARAMS_CANSAVE ); /* checks whether module can save (returns 1 or 0 and might spit out a message) */ + int ( *save )( PM_PARAMS_SAVE ); /* saves a pico model in module's native model format */ }; /* general functions */ -int PicoInit( void ); -void PicoShutdown( void ); -int PicoError( void ); +int PicoInit( void ); +void PicoShutdown( void ); +int PicoError( void ); -void PicoSetMallocFunc( void *(*func)( size_t ) ); -void PicoSetFreeFunc( void (*func)( void* ) ); -void PicoSetLoadFileFunc( void (*func)( const char*, unsigned char**, int* ) ); -void PicoSetFreeFileFunc( void (*func)( void* ) ); -void PicoSetPrintFunc( void (*func)( int, const char* ) ); +void PicoSetMallocFunc( void *( *func )( size_t ) ); +void PicoSetFreeFunc( void ( *func )( void* ) ); +void PicoSetLoadFileFunc( void ( *func )( const char*, unsigned char**, int* ) ); +void PicoSetFreeFileFunc( void ( *func )( void* ) ); +void PicoSetPrintFunc( void ( *func )( int, const char* ) ); -const picoModule_t **PicoModuleList( int *numModules ); +const picoModule_t **PicoModuleList( int *numModules ); -picoModel_t *PicoLoadModel( const char *name, int frameNum ); +picoModel_t *PicoLoadModel( const char *name, int frameNum ); -typedef size_t (*PicoInputStreamReadFunc)(void* inputStream, unsigned char* buffer, size_t length); +typedef size_t ( *PicoInputStreamReadFunc )( void* inputStream, unsigned char* buffer, size_t length ); picoModel_t* PicoModuleLoadModelStream( const picoModule_t* module, void* inputStream, PicoInputStreamReadFunc inputStreamRead, size_t streamLength, int frameNum, const char *fileName ); /* model functions */ -picoModel_t *PicoNewModel( void ); -void PicoFreeModel( picoModel_t *model ); -int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ); +picoModel_t *PicoNewModel( void ); +void PicoFreeModel( picoModel_t *model ); +int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ); /* shader functions */ -picoShader_t *PicoNewShader( picoModel_t *model ); -void PicoFreeShader( picoShader_t *shader ); -picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ); +picoShader_t *PicoNewShader( picoModel_t *model ); +void PicoFreeShader( picoShader_t *shader ); +picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ); /* surface functions */ -picoSurface_t *PicoNewSurface( picoModel_t *model ); -void PicoFreeSurface( picoSurface_t *surface ); -picoSurface_t *PicoFindSurface( picoModel_t *model, char *name, int caseSensitive ); -int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ); +picoSurface_t *PicoNewSurface( picoModel_t *model ); +void PicoFreeSurface( picoSurface_t *surface ); +picoSurface_t *PicoFindSurface( picoModel_t *model, char *name, int caseSensitive ); +int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ); /* setter functions */ -void PicoSetModelName( picoModel_t *model, const char *name ); -void PicoSetModelFileName( picoModel_t *model, const char *fileName ); -void PicoSetModelFrameNum( picoModel_t *model, int frameNum ); -void PicoSetModelNumFrames( picoModel_t *model, int numFrames ); -void PicoSetModelData( picoModel_t *model, void *data ); - -void PicoSetShaderName( picoShader_t *shader, char *name ); -void PicoSetShaderMapName( picoShader_t *shader, char *mapName ); -void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderTransparency( picoShader_t *shader, float value ); -void PicoSetShaderShininess( picoShader_t *shader, float value ); - -void PicoSetSurfaceData( picoSurface_t *surface, void *data ); -void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ); -void PicoSetSurfaceName( picoSurface_t *surface, const char *name ); -void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ); -void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ); -void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); -void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ); -void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ); -void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ); -void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ); -void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); -void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ); -void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ); +void PicoSetModelName( picoModel_t *model, const char *name ); +void PicoSetModelFileName( picoModel_t *model, const char *fileName ); +void PicoSetModelFrameNum( picoModel_t *model, int frameNum ); +void PicoSetModelNumFrames( picoModel_t *model, int numFrames ); +void PicoSetModelData( picoModel_t *model, void *data ); + +void PicoSetShaderName( picoShader_t *shader, char *name ); +void PicoSetShaderMapName( picoShader_t *shader, char *mapName ); +void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ); +void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ); +void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ); +void PicoSetShaderTransparency( picoShader_t *shader, float value ); +void PicoSetShaderShininess( picoShader_t *shader, float value ); + +void PicoSetSurfaceData( picoSurface_t *surface, void *data ); +void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ); +void PicoSetSurfaceName( picoSurface_t *surface, const char *name ); +void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ); +void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ); +void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); +void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ); +void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ); +void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ); +void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ); +void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); +void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ); +void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ); /* getter functions */ -char *PicoGetModelName( picoModel_t *model ); -char *PicoGetModelFileName( picoModel_t *model ); -int PicoGetModelFrameNum( picoModel_t *model ); -int PicoGetModelNumFrames( picoModel_t *model ); -void *PicoGetModelData( picoModel_t *model ); -int PicoGetModelNumShaders( picoModel_t *model ); -picoShader_t *PicoGetModelShader( picoModel_t *model, int num ); /* sea */ -int PicoGetModelNumSurfaces( picoModel_t *model ); -picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ); -int PicoGetModelTotalVertexes( picoModel_t *model ); -int PicoGetModelTotalIndexes( picoModel_t *model ); - -char *PicoGetShaderName( picoShader_t *shader ); -char *PicoGetShaderMapName( picoShader_t *shader ); -picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ); -picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ); -picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ); -float PicoGetShaderTransparency( picoShader_t *shader ); -float PicoGetShaderShininess( picoShader_t *shader ); - -void *PicoGetSurfaceData( picoSurface_t *surface ); -char *PicoGetSurfaceName( picoSurface_t *surface ); /* sea */ -picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ); -char *PicoGetSurfaceName( picoSurface_t *surface ); -picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ); /* sea */ - -int PicoGetSurfaceNumVertexes( picoSurface_t *surface ); -picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ); -picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ); -picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ); -picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ); -int PicoGetSurfaceNumIndexes( picoSurface_t *surface ); -picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ); -picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ); -picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ); -int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ); +char *PicoGetModelName( picoModel_t *model ); +char *PicoGetModelFileName( picoModel_t *model ); +int PicoGetModelFrameNum( picoModel_t *model ); +int PicoGetModelNumFrames( picoModel_t *model ); +void *PicoGetModelData( picoModel_t *model ); +int PicoGetModelNumShaders( picoModel_t *model ); +picoShader_t *PicoGetModelShader( picoModel_t *model, int num ); /* sea */ +int PicoGetModelNumSurfaces( picoModel_t *model ); +picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ); +int PicoGetModelTotalVertexes( picoModel_t *model ); +int PicoGetModelTotalIndexes( picoModel_t *model ); + +char *PicoGetShaderName( picoShader_t *shader ); +char *PicoGetShaderMapName( picoShader_t *shader ); +picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ); +picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ); +picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ); +float PicoGetShaderTransparency( picoShader_t *shader ); +float PicoGetShaderShininess( picoShader_t *shader ); + +void *PicoGetSurfaceData( picoSurface_t *surface ); +char *PicoGetSurfaceName( picoSurface_t *surface ); /* sea */ +picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ); +char *PicoGetSurfaceName( picoSurface_t *surface ); +picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ); /* sea */ + +int PicoGetSurfaceNumVertexes( picoSurface_t *surface ); +picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ); +picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ); +picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ); +picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ); +int PicoGetSurfaceNumIndexes( picoSurface_t *surface ); +picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ); +picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ); +picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ); +int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ); /* hashtable related functions */ typedef struct picoVertexCombinationData_s { - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; } picoVertexCombinationData_t; typedef struct picoVertexCombinationHash_s { - picoVertexCombinationData_t vcd; - picoIndex_t index; + picoVertexCombinationData_t vcd; + picoIndex_t index; - void *data; + void *data; - struct picoVertexCombinationHash_s *next; + struct picoVertexCombinationHash_s *next; } picoVertexCombinationHash_t; -int PicoGetHashTableSize( void ); -unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ); -picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ); -void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ); -picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ); +int PicoGetHashTableSize( void ); +unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ); +picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ); +void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ); +picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ); picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color, picoIndex_t index ); /* specialized functions */ -int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup ); -void PicoFixSurfaceNormals( picoSurface_t *surface ); -int PicoRemapModel( picoModel_t *model, char *remapFile ); +int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup ); +void PicoFixSurfaceNormals( picoSurface_t *surface ); +int PicoRemapModel( picoModel_t *model, char *remapFile ); -void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, picoShader_t* shader, const char *name, picoIndex_t* smoothingGroup); +void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, picoShader_t* shader, const char *name, picoIndex_t* smoothingGroup ); /* end marker */ #ifdef __cplusplus diff --git a/libs/picomodel/lwo/clip.c b/libs/picomodel/lwo/clip.c index d83ea61f..1e68cc1c 100644 --- a/libs/picomodel/lwo/clip.c +++ b/libs/picomodel/lwo/clip.c @@ -1,278 +1,300 @@ /* -====================================================================== -clip.c + ====================================================================== + clip.c -Functions for LWO2 image references. + Functions for LWO2 image references. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwFreeClip() - -Free memory used by an lwClip. -====================================================================== */ - -void lwFreeClip( lwClip *clip ) -{ - if ( clip ) { - lwListFree( clip->ifilter, (void *) lwFreePlugin ); - lwListFree( clip->pfilter, (void *) lwFreePlugin ); - - switch ( clip->type ) { - case ID_STIL: - _pico_free( clip->source.still.name); - break; - - case ID_ISEQ: - _pico_free( clip->source.seq.prefix ); - _pico_free( clip->source.seq.suffix ); - break; - - case ID_ANIM: - _pico_free( clip->source.anim.name ); - _pico_free( clip->source.anim.server ); - _pico_free( clip->source.anim.data ); - break; - - case ID_XREF: - _pico_free( clip->source.xref.string ); - break; - - case ID_STCC: - _pico_free( clip->source.cycle.name ); - break; - - default: - break; - } - - _pico_free( clip ); - } + ====================================================================== + lwFreeClip() + + Free memory used by an lwClip. + ====================================================================== */ + +void lwFreeClip( lwClip *clip ){ + if ( clip ) { + lwListFree( clip->ifilter, (void *) lwFreePlugin ); + lwListFree( clip->pfilter, (void *) lwFreePlugin ); + + switch ( clip->type ) { + case ID_STIL: + _pico_free( clip->source.still.name ); + break; + + case ID_ISEQ: + _pico_free( clip->source.seq.prefix ); + _pico_free( clip->source.seq.suffix ); + break; + + case ID_ANIM: + _pico_free( clip->source.anim.name ); + _pico_free( clip->source.anim.server ); + _pico_free( clip->source.anim.data ); + break; + + case ID_XREF: + _pico_free( clip->source.xref.string ); + break; + + case ID_STCC: + _pico_free( clip->source.cycle.name ); + break; + + default: + break; + } + + _pico_free( clip ); + } } /* -====================================================================== -lwGetClip() + ====================================================================== + lwGetClip() -Read image references from a CLIP chunk in an LWO2 file. -====================================================================== */ - -lwClip *lwGetClip( picoMemStream_t *fp, int cksize ) -{ - lwClip *clip; - lwPlugin *filt; - unsigned int id; - unsigned short sz; - int pos, rlen; - - - /* allocate the Clip structure */ - - clip = _pico_calloc( 1, sizeof( lwClip )); - if ( !clip ) goto Fail; - - clip->contrast.val = 1.0f; - clip->brightness.val = 1.0f; - clip->saturation.val = 1.0f; - clip->gamma.val = 1.0f; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* index */ - - clip->index = getI4( fp ); - - /* first subchunk header */ - - clip->type = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - sz += sz & 1; - set_flen( 0 ); - - switch ( clip->type ) { - case ID_STIL: - clip->source.still.name = getS0( fp ); - break; - - case ID_ISEQ: - clip->source.seq.digits = getU1( fp ); - clip->source.seq.flags = getU1( fp ); - clip->source.seq.offset = getI2( fp ); - getU2( fp ); /* not sure what this is yet */ - clip->source.seq.start = getI2( fp ); - clip->source.seq.end = getI2( fp ); - clip->source.seq.prefix = getS0( fp ); - clip->source.seq.suffix = getS0( fp ); - break; - - case ID_ANIM: - clip->source.anim.name = getS0( fp ); - clip->source.anim.server = getS0( fp ); - rlen = get_flen(); - clip->source.anim.data = getbytes( fp, sz - rlen ); - break; - - case ID_XREF: - clip->source.xref.index = getI4( fp ); - clip->source.xref.string = getS0( fp ); - break; - - case ID_STCC: - clip->source.cycle.lo = getI2( fp ); - clip->source.cycle.hi = getI2( fp ); - clip->source.cycle.name = getS0( fp ); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the CLIP chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) goto Fail; - if ( cksize == rlen ) - return clip; - - /* process subchunks as they're encountered */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TIME: - clip->start_time = getF4( fp ); - clip->duration = getF4( fp ); - clip->frame_rate = getF4( fp ); - break; - - case ID_CONT: - clip->contrast.val = getF4( fp ); - clip->contrast.eindex = getVX( fp ); - break; - - case ID_BRIT: - clip->brightness.val = getF4( fp ); - clip->brightness.eindex = getVX( fp ); - break; - - case ID_SATR: - clip->saturation.val = getF4( fp ); - clip->saturation.eindex = getVX( fp ); - break; - - case ID_HUE: - clip->hue.val = getF4( fp ); - clip->hue.eindex = getVX( fp ); - break; - - case ID_GAMM: - clip->gamma.val = getF4( fp ); - clip->gamma.eindex = getVX( fp ); - break; - - case ID_NEGA: - clip->negative = getU2( fp ); - break; - - case ID_IFLT: - case ID_PFLT: - filt = _pico_calloc( 1, sizeof( lwPlugin )); - if ( !filt ) goto Fail; - - filt->name = getS0( fp ); - filt->flags = getU2( fp ); - rlen = get_flen(); - filt->data = getbytes( fp, sz - rlen ); - - if ( id == ID_IFLT ) { - lwListAdd( (void *) &clip->ifilter, filt ); - clip->nifilters++; - } - else { - lwListAdd( (void *) &clip->pfilter, filt ); - clip->npfilters++; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the CLIP chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) goto Fail; - if ( cksize == rlen ) break; - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) goto Fail; - } - - return clip; + Read image references from a CLIP chunk in an LWO2 file. + ====================================================================== */ + +lwClip *lwGetClip( picoMemStream_t *fp, int cksize ){ + lwClip *clip; + lwPlugin *filt; + unsigned int id; + unsigned short sz; + int pos, rlen; + + + /* allocate the Clip structure */ + + clip = _pico_calloc( 1, sizeof( lwClip ) ); + if ( !clip ) { + goto Fail; + } + + clip->contrast.val = 1.0f; + clip->brightness.val = 1.0f; + clip->saturation.val = 1.0f; + clip->gamma.val = 1.0f; + + /* remember where we started */ + + set_flen( 0 ); + pos = _pico_memstream_tell( fp ); + + /* index */ + + clip->index = getI4( fp ); + + /* first subchunk header */ + + clip->type = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + sz += sz & 1; + set_flen( 0 ); + + switch ( clip->type ) { + case ID_STIL: + clip->source.still.name = getS0( fp ); + break; + + case ID_ISEQ: + clip->source.seq.digits = getU1( fp ); + clip->source.seq.flags = getU1( fp ); + clip->source.seq.offset = getI2( fp ); + getU2( fp ); /* not sure what this is yet */ + clip->source.seq.start = getI2( fp ); + clip->source.seq.end = getI2( fp ); + clip->source.seq.prefix = getS0( fp ); + clip->source.seq.suffix = getS0( fp ); + break; + + case ID_ANIM: + clip->source.anim.name = getS0( fp ); + clip->source.anim.server = getS0( fp ); + rlen = get_flen(); + clip->source.anim.data = getbytes( fp, sz - rlen ); + break; + + case ID_XREF: + clip->source.xref.index = getI4( fp ); + clip->source.xref.string = getS0( fp ); + break; + + case ID_STCC: + clip->source.cycle.lo = getI2( fp ); + clip->source.cycle.hi = getI2( fp ); + clip->source.cycle.name = getS0( fp ); + break; + + default: + break; + } + + /* error while reading current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the CLIP chunk? */ + + rlen = _pico_memstream_tell( fp ) - pos; + if ( cksize < rlen ) { + goto Fail; + } + if ( cksize == rlen ) { + return clip; + } + + /* process subchunks as they're encountered */ + + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_TIME: + clip->start_time = getF4( fp ); + clip->duration = getF4( fp ); + clip->frame_rate = getF4( fp ); + break; + + case ID_CONT: + clip->contrast.val = getF4( fp ); + clip->contrast.eindex = getVX( fp ); + break; + + case ID_BRIT: + clip->brightness.val = getF4( fp ); + clip->brightness.eindex = getVX( fp ); + break; + + case ID_SATR: + clip->saturation.val = getF4( fp ); + clip->saturation.eindex = getVX( fp ); + break; + + case ID_HUE: + clip->hue.val = getF4( fp ); + clip->hue.eindex = getVX( fp ); + break; + + case ID_GAMM: + clip->gamma.val = getF4( fp ); + clip->gamma.eindex = getVX( fp ); + break; + + case ID_NEGA: + clip->negative = getU2( fp ); + break; + + case ID_IFLT: + case ID_PFLT: + filt = _pico_calloc( 1, sizeof( lwPlugin ) ); + if ( !filt ) { + goto Fail; + } + + filt->name = getS0( fp ); + filt->flags = getU2( fp ); + rlen = get_flen(); + filt->data = getbytes( fp, sz - rlen ); + + if ( id == ID_IFLT ) { + lwListAdd( (void *) &clip->ifilter, filt ); + clip->nifilters++; + } + else { + lwListAdd( (void *) &clip->pfilter, filt ); + clip->npfilters++; + } + break; + + default: + break; + } + + /* error while reading current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the CLIP chunk? */ + + rlen = _pico_memstream_tell( fp ) - pos; + if ( cksize < rlen ) { + goto Fail; + } + if ( cksize == rlen ) { + break; + } + + /* get the next chunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + goto Fail; + } + } + + return clip; Fail: - lwFreeClip( clip ); - return NULL; + lwFreeClip( clip ); + return NULL; } /* -====================================================================== -lwFindClip() - -Returns an lwClip pointer, given a clip index. -====================================================================== */ - -lwClip *lwFindClip( lwClip *list, int index ) -{ - lwClip *clip; - - clip = list; - while ( clip ) { - if ( clip->index == index ) break; - clip = clip->next; - } - return clip; + ====================================================================== + lwFindClip() + + Returns an lwClip pointer, given a clip index. + ====================================================================== */ + +lwClip *lwFindClip( lwClip *list, int index ){ + lwClip *clip; + + clip = list; + while ( clip ) { + if ( clip->index == index ) { + break; + } + clip = clip->next; + } + return clip; } diff --git a/libs/picomodel/lwo/envelope.c b/libs/picomodel/lwo/envelope.c index 3720a8eb..8c5bb8fa 100644 --- a/libs/picomodel/lwo/envelope.c +++ b/libs/picomodel/lwo/envelope.c @@ -1,600 +1,641 @@ /* -====================================================================== -envelope.c + ====================================================================== + envelope.c -Envelope functions for an LWO2 reader. + Envelope functions for an LWO2 reader. -Ernie Wright 16 Nov 00 -====================================================================== */ + Ernie Wright 16 Nov 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwFreeEnvelope() - -Free the memory used by an lwEnvelope. -====================================================================== */ - -void lwFreeEnvelope( lwEnvelope *env ) -{ - if ( env ) { - if ( env->name ) _pico_free( env->name ); - lwListFree( env->key, _pico_free ); - lwListFree( env->cfilter, (void *) lwFreePlugin ); - _pico_free( env ); - } + ====================================================================== + lwFreeEnvelope() + + Free the memory used by an lwEnvelope. + ====================================================================== */ + +void lwFreeEnvelope( lwEnvelope *env ){ + if ( env ) { + if ( env->name ) { + _pico_free( env->name ); + } + lwListFree( env->key, _pico_free ); + lwListFree( env->cfilter, (void *) lwFreePlugin ); + _pico_free( env ); + } } -static int compare_keys( lwKey *k1, lwKey *k2 ) -{ - return k1->time > k2->time ? 1 : k1->time < k2->time ? -1 : 0; +static int compare_keys( lwKey *k1, lwKey *k2 ){ + return k1->time > k2->time ? 1 : k1->time < k2->time ? -1 : 0; } /* -====================================================================== -lwGetEnvelope() - -Read an ENVL chunk from an LWO2 file. -====================================================================== */ - -lwEnvelope *lwGetEnvelope( picoMemStream_t *fp, int cksize ) -{ - lwEnvelope *env; - lwKey *key = NULL; - lwPlugin *plug; - unsigned int id; - unsigned short sz; - float f[ 4 ]; - int i, nparams, pos, rlen; - - - /* allocate the Envelope structure */ - - env = _pico_calloc( 1, sizeof( lwEnvelope )); - if ( !env ) goto Fail; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* index */ - - env->index = getVX( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TYPE: - env->type = getU2( fp ); - break; - - case ID_NAME: - env->name = getS0( fp ); - break; - - case ID_PRE: - env->behavior[ 0 ] = getU2( fp ); - break; - - case ID_POST: - env->behavior[ 1 ] = getU2( fp ); - break; - - case ID_KEY: - key = _pico_calloc( 1, sizeof( lwKey )); - if ( !key ) goto Fail; - key->time = getF4( fp ); - key->value = getF4( fp ); - lwListInsert( (void **) &env->key, key, (void *) compare_keys ); - env->nkeys++; - break; - - case ID_SPAN: - if ( !key ) goto Fail; - key->shape = getU4( fp ); - - nparams = ( sz - 4 ) / 4; - if ( nparams > 4 ) nparams = 4; - for ( i = 0; i < nparams; i++ ) - f[ i ] = getF4( fp ); - - switch ( key->shape ) { - case ID_TCB: - key->tension = f[ 0 ]; - key->continuity = f[ 1 ]; - key->bias = f[ 2 ]; - break; - - case ID_BEZI: - case ID_HERM: - case ID_BEZ2: - for ( i = 0; i < nparams; i++ ) - key->param[ i ] = f[ i ]; - break; - } - break; - - case ID_CHAN: - plug = _pico_calloc( 1, sizeof( lwPlugin )); - if ( !plug ) goto Fail; - - plug->name = getS0( fp ); - plug->flags = getU2( fp ); - plug->data = getbytes( fp, sz - get_flen() ); - - lwListAdd( (void *) &env->cfilter, plug ); - env->ncfilters++; - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the ENVL chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) goto Fail; - if ( cksize == rlen ) break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) goto Fail; - } - - return env; + ====================================================================== + lwGetEnvelope() + + Read an ENVL chunk from an LWO2 file. + ====================================================================== */ + +lwEnvelope *lwGetEnvelope( picoMemStream_t *fp, int cksize ){ + lwEnvelope *env; + lwKey *key = NULL; + lwPlugin *plug; + unsigned int id; + unsigned short sz; + float f[ 4 ]; + int i, nparams, pos, rlen; + + + /* allocate the Envelope structure */ + + env = _pico_calloc( 1, sizeof( lwEnvelope ) ); + if ( !env ) { + goto Fail; + } + + /* remember where we started */ + + set_flen( 0 ); + pos = _pico_memstream_tell( fp ); + + /* index */ + + env->index = getVX( fp ); + + /* first subchunk header */ + + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + /* process subchunks as they're encountered */ + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_TYPE: + env->type = getU2( fp ); + break; + + case ID_NAME: + env->name = getS0( fp ); + break; + + case ID_PRE: + env->behavior[ 0 ] = getU2( fp ); + break; + + case ID_POST: + env->behavior[ 1 ] = getU2( fp ); + break; + + case ID_KEY: + key = _pico_calloc( 1, sizeof( lwKey ) ); + if ( !key ) { + goto Fail; + } + key->time = getF4( fp ); + key->value = getF4( fp ); + lwListInsert( (void **) &env->key, key, (void *) compare_keys ); + env->nkeys++; + break; + + case ID_SPAN: + if ( !key ) { + goto Fail; + } + key->shape = getU4( fp ); + + nparams = ( sz - 4 ) / 4; + if ( nparams > 4 ) { + nparams = 4; + } + for ( i = 0; i < nparams; i++ ) + f[ i ] = getF4( fp ); + + switch ( key->shape ) { + case ID_TCB: + key->tension = f[ 0 ]; + key->continuity = f[ 1 ]; + key->bias = f[ 2 ]; + break; + + case ID_BEZI: + case ID_HERM: + case ID_BEZ2: + for ( i = 0; i < nparams; i++ ) + key->param[ i ] = f[ i ]; + break; + } + break; + + case ID_CHAN: + plug = _pico_calloc( 1, sizeof( lwPlugin ) ); + if ( !plug ) { + goto Fail; + } + + plug->name = getS0( fp ); + plug->flags = getU2( fp ); + plug->data = getbytes( fp, sz - get_flen() ); + + lwListAdd( (void *) &env->cfilter, plug ); + env->ncfilters++; + break; + + default: + break; + } + + /* error while reading current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the ENVL chunk? */ + + rlen = _pico_memstream_tell( fp ) - pos; + if ( cksize < rlen ) { + goto Fail; + } + if ( cksize == rlen ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + goto Fail; + } + } + + return env; Fail: - lwFreeEnvelope( env ); - return NULL; + lwFreeEnvelope( env ); + return NULL; } /* -====================================================================== -lwFindEnvelope() - -Returns an lwEnvelope pointer, given an envelope index. -====================================================================== */ - -lwEnvelope *lwFindEnvelope( lwEnvelope *list, int index ) -{ - lwEnvelope *env; - - env = list; - while ( env ) { - if ( env->index == index ) break; - env = env->next; - } - return env; + ====================================================================== + lwFindEnvelope() + + Returns an lwEnvelope pointer, given an envelope index. + ====================================================================== */ + +lwEnvelope *lwFindEnvelope( lwEnvelope *list, int index ){ + lwEnvelope *env; + + env = list; + while ( env ) { + if ( env->index == index ) { + break; + } + env = env->next; + } + return env; } /* -====================================================================== -range() + ====================================================================== + range() -Given the value v of a periodic function, returns the equivalent value -v2 in the principal interval [lo, hi]. If i isn't NULL, it receives -the number of wavelengths between v and v2. + Given the value v of a periodic function, returns the equivalent value + v2 in the principal interval [lo, hi]. If i isn't NULL, it receives + the number of wavelengths between v and v2. v2 = v - i * (hi - lo) -For example, range( 3 pi, 0, 2 pi, i ) returns pi, with i = 1. -====================================================================== */ + For example, range( 3 pi, 0, 2 pi, i ) returns pi, with i = 1. + ====================================================================== */ -static float range( float v, float lo, float hi, int *i ) -{ - float v2, r = hi - lo; +static float range( float v, float lo, float hi, int *i ){ + float v2, r = hi - lo; - if ( r == 0.0 ) { - if ( i ) *i = 0; - return lo; - } + if ( r == 0.0 ) { + if ( i ) { + *i = 0; + } + return lo; + } - v2 = lo + v - r * ( float ) floor(( double ) v / r ); - if ( i ) *i = -( int )(( v2 - v ) / r + ( v2 > v ? 0.5 : -0.5 )); + v2 = lo + v - r * ( float ) floor( ( double ) v / r ); + if ( i ) { + *i = -( int )( ( v2 - v ) / r + ( v2 > v ? 0.5 : -0.5 ) ); + } - return v2; + return v2; } /* -====================================================================== -hermite() + ====================================================================== + hermite() -Calculate the Hermite coefficients. -====================================================================== */ + Calculate the Hermite coefficients. + ====================================================================== */ -static void hermite( float t, float *h1, float *h2, float *h3, float *h4 ) -{ - float t2, t3; +static void hermite( float t, float *h1, float *h2, float *h3, float *h4 ){ + float t2, t3; - t2 = t * t; - t3 = t * t2; + t2 = t * t; + t3 = t * t2; - *h2 = 3.0f * t2 - t3 - t3; - *h1 = 1.0f - *h2; - *h4 = t3 - t2; - *h3 = *h4 - t2 + t; + *h2 = 3.0f * t2 - t3 - t3; + *h1 = 1.0f - *h2; + *h4 = t3 - t2; + *h3 = *h4 - t2 + t; } /* -====================================================================== -bezier() + ====================================================================== + bezier() -Interpolate the value of a 1D Bezier curve. -====================================================================== */ + Interpolate the value of a 1D Bezier curve. + ====================================================================== */ -static float bezier( float x0, float x1, float x2, float x3, float t ) -{ - float a, b, c, t2, t3; +static float bezier( float x0, float x1, float x2, float x3, float t ){ + float a, b, c, t2, t3; - t2 = t * t; - t3 = t2 * t; + t2 = t * t; + t3 = t2 * t; - c = 3.0f * ( x1 - x0 ); - b = 3.0f * ( x2 - x1 ) - c; - a = x3 - x0 - c - b; + c = 3.0f * ( x1 - x0 ); + b = 3.0f * ( x2 - x1 ) - c; + a = x3 - x0 - c - b; - return a * t3 + b * t2 + c * t + x0; + return a * t3 + b * t2 + c * t + x0; } /* -====================================================================== -bez2_time() + ====================================================================== + bez2_time() -Find the t for which bezier() returns the input time. The handle -endpoints of a BEZ2 curve represent the control points, and these have -(time, value) coordinates, so time is used as both a coordinate and a -parameter for this curve type. -====================================================================== */ + Find the t for which bezier() returns the input time. The handle + endpoints of a BEZ2 curve represent the control points, and these have + (time, value) coordinates, so time is used as both a coordinate and a + parameter for this curve type. + ====================================================================== */ static float bez2_time( float x0, float x1, float x2, float x3, float time, - float *t0, float *t1 ) -{ - float v, t; - - t = *t0 + ( *t1 - *t0 ) * 0.5f; - v = bezier( x0, x1, x2, x3, t ); - if ( fabs( time - v ) > .0001f ) { - if ( v > time ) - *t1 = t; - else - *t0 = t; - return bez2_time( x0, x1, x2, x3, time, t0, t1 ); - } - else - return t; + float *t0, float *t1 ){ + float v, t; + + t = *t0 + ( *t1 - *t0 ) * 0.5f; + v = bezier( x0, x1, x2, x3, t ); + if ( fabs( time - v ) > .0001f ) { + if ( v > time ) { + *t1 = t; + } + else{ + *t0 = t; + } + return bez2_time( x0, x1, x2, x3, time, t0, t1 ); + } + else{ + return t; + } } /* -====================================================================== -bez2() + ====================================================================== + bez2() -Interpolate the value of a BEZ2 curve. -====================================================================== */ + Interpolate the value of a BEZ2 curve. + ====================================================================== */ -static float bez2( lwKey *key0, lwKey *key1, float time ) -{ - float x, y, t, t0 = 0.0f, t1 = 1.0f; +static float bez2( lwKey *key0, lwKey *key1, float time ){ + float x, y, t, t0 = 0.0f, t1 = 1.0f; - if ( key0->shape == ID_BEZ2 ) - x = key0->time + key0->param[ 2 ]; - else - x = key0->time + ( key1->time - key0->time ) / 3.0f; + if ( key0->shape == ID_BEZ2 ) { + x = key0->time + key0->param[ 2 ]; + } + else{ + x = key0->time + ( key1->time - key0->time ) / 3.0f; + } - t = bez2_time( key0->time, x, key1->time + key1->param[ 0 ], key1->time, - time, &t0, &t1 ); + t = bez2_time( key0->time, x, key1->time + key1->param[ 0 ], key1->time, + time, &t0, &t1 ); - if ( key0->shape == ID_BEZ2 ) - y = key0->value + key0->param[ 3 ]; - else - y = key0->value + key0->param[ 1 ] / 3.0f; + if ( key0->shape == ID_BEZ2 ) { + y = key0->value + key0->param[ 3 ]; + } + else{ + y = key0->value + key0->param[ 1 ] / 3.0f; + } - return bezier( key0->value, y, key1->param[ 1 ] + key1->value, key1->value, t ); + return bezier( key0->value, y, key1->param[ 1 ] + key1->value, key1->value, t ); } /* -====================================================================== -outgoing() - -Return the outgoing tangent to the curve at key0. The value returned -for the BEZ2 case is used when extrapolating a linear pre behavior and -when interpolating a non-BEZ2 span. -====================================================================== */ - -static float outgoing( lwKey *key0, lwKey *key1 ) -{ - float a, b, d, t, out; - - switch ( key0->shape ) - { - case ID_TCB: - a = ( 1.0f - key0->tension ) - * ( 1.0f + key0->continuity ) - * ( 1.0f + key0->bias ); - b = ( 1.0f - key0->tension ) - * ( 1.0f - key0->continuity ) - * ( 1.0f - key0->bias ); - d = key1->value - key0->value; - - if ( key0->prev ) { - t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - out = t * ( a * ( key0->value - key0->prev->value ) + b * d ); - } - else - out = b * d; - break; - - case ID_LINE: - d = key1->value - key0->value; - if ( key0->prev ) { - t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - out = t * ( key0->value - key0->prev->value + d ); - } - else - out = d; - break; - - case ID_BEZI: - case ID_HERM: - out = key0->param[ 1 ]; - if ( key0->prev ) - out *= ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - break; - - case ID_BEZ2: - out = key0->param[ 3 ] * ( key1->time - key0->time ); - if ( fabs( key0->param[ 2 ] ) > 1e-5f ) - out /= key0->param[ 2 ]; - else - out *= 1e5f; - break; - - case ID_STEP: - default: - out = 0.0f; - break; - } - - return out; + ====================================================================== + outgoing() + + Return the outgoing tangent to the curve at key0. The value returned + for the BEZ2 case is used when extrapolating a linear pre behavior and + when interpolating a non-BEZ2 span. + ====================================================================== */ + +static float outgoing( lwKey *key0, lwKey *key1 ){ + float a, b, d, t, out; + + switch ( key0->shape ) + { + case ID_TCB: + a = ( 1.0f - key0->tension ) + * ( 1.0f + key0->continuity ) + * ( 1.0f + key0->bias ); + b = ( 1.0f - key0->tension ) + * ( 1.0f - key0->continuity ) + * ( 1.0f - key0->bias ); + d = key1->value - key0->value; + + if ( key0->prev ) { + t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); + out = t * ( a * ( key0->value - key0->prev->value ) + b * d ); + } + else{ + out = b * d; + } + break; + + case ID_LINE: + d = key1->value - key0->value; + if ( key0->prev ) { + t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); + out = t * ( key0->value - key0->prev->value + d ); + } + else{ + out = d; + } + break; + + case ID_BEZI: + case ID_HERM: + out = key0->param[ 1 ]; + if ( key0->prev ) { + out *= ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); + } + break; + + case ID_BEZ2: + out = key0->param[ 3 ] * ( key1->time - key0->time ); + if ( fabs( key0->param[ 2 ] ) > 1e-5f ) { + out /= key0->param[ 2 ]; + } + else{ + out *= 1e5f; + } + break; + + case ID_STEP: + default: + out = 0.0f; + break; + } + + return out; } /* -====================================================================== -incoming() - -Return the incoming tangent to the curve at key1. The value returned -for the BEZ2 case is used when extrapolating a linear post behavior. -====================================================================== */ - -static float incoming( lwKey *key0, lwKey *key1 ) -{ - float a, b, d, t, in; - - switch ( key1->shape ) - { - case ID_LINE: - d = key1->value - key0->value; - if ( key1->next ) { - t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - in = t * ( key1->next->value - key1->value + d ); - } - else - in = d; - break; - - case ID_TCB: - a = ( 1.0f - key1->tension ) - * ( 1.0f - key1->continuity ) - * ( 1.0f + key1->bias ); - b = ( 1.0f - key1->tension ) - * ( 1.0f + key1->continuity ) - * ( 1.0f - key1->bias ); - d = key1->value - key0->value; - - if ( key1->next ) { - t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - in = t * ( b * ( key1->next->value - key1->value ) + a * d ); - } - else - in = a * d; - break; - - case ID_BEZI: - case ID_HERM: - in = key1->param[ 0 ]; - if ( key1->next ) - in *= ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - break; - return in; - - case ID_BEZ2: - in = key1->param[ 1 ] * ( key1->time - key0->time ); - if ( fabs( key1->param[ 0 ] ) > 1e-5f ) - in /= key1->param[ 0 ]; - else - in *= 1e5f; - break; - - case ID_STEP: - default: - in = 0.0f; - break; - } - - return in; + ====================================================================== + incoming() + + Return the incoming tangent to the curve at key1. The value returned + for the BEZ2 case is used when extrapolating a linear post behavior. + ====================================================================== */ + +static float incoming( lwKey *key0, lwKey *key1 ){ + float a, b, d, t, in; + + switch ( key1->shape ) + { + case ID_LINE: + d = key1->value - key0->value; + if ( key1->next ) { + t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); + in = t * ( key1->next->value - key1->value + d ); + } + else{ + in = d; + } + break; + + case ID_TCB: + a = ( 1.0f - key1->tension ) + * ( 1.0f - key1->continuity ) + * ( 1.0f + key1->bias ); + b = ( 1.0f - key1->tension ) + * ( 1.0f + key1->continuity ) + * ( 1.0f - key1->bias ); + d = key1->value - key0->value; + + if ( key1->next ) { + t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); + in = t * ( b * ( key1->next->value - key1->value ) + a * d ); + } + else{ + in = a * d; + } + break; + + case ID_BEZI: + case ID_HERM: + in = key1->param[ 0 ]; + if ( key1->next ) { + in *= ( key1->time - key0->time ) / ( key1->next->time - key0->time ); + } + break; + return in; + + case ID_BEZ2: + in = key1->param[ 1 ] * ( key1->time - key0->time ); + if ( fabs( key1->param[ 0 ] ) > 1e-5f ) { + in /= key1->param[ 0 ]; + } + else{ + in *= 1e5f; + } + break; + + case ID_STEP: + default: + in = 0.0f; + break; + } + + return in; } /* -====================================================================== -evalEnvelope() - -Given a list of keys and a time, returns the interpolated value of the -envelope at that time. -====================================================================== */ - -float evalEnvelope( lwEnvelope *env, float time ) -{ - lwKey *key0, *key1, *skey, *ekey; - float t, h1, h2, h3, h4, in, out, offset = 0.0f; - int noff; - - - /* if there's no key, the value is 0 */ - - if ( env->nkeys == 0 ) return 0.0f; - - /* if there's only one key, the value is constant */ - - if ( env->nkeys == 1 ) - return env->key->value; + ====================================================================== + evalEnvelope() - /* find the first and last keys */ + Given a list of keys and a time, returns the interpolated value of the + envelope at that time. + ====================================================================== */ - skey = ekey = env->key; - while ( ekey->next ) ekey = ekey->next; +float evalEnvelope( lwEnvelope *env, float time ){ + lwKey *key0, *key1, *skey, *ekey; + float t, h1, h2, h3, h4, in, out, offset = 0.0f; + int noff; + + + /* if there's no key, the value is 0 */ - /* use pre-behavior if time is before first key time */ + if ( env->nkeys == 0 ) { + return 0.0f; + } - if ( time < skey->time ) { - switch ( env->behavior[ 0 ] ) - { - case BEH_RESET: - return 0.0f; + /* if there's only one key, the value is constant */ - case BEH_CONSTANT: - return skey->value; + if ( env->nkeys == 1 ) { + return env->key->value; + } - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; + /* find the first and last keys */ - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) - time = ekey->time - skey->time - time; - break; + skey = ekey = env->key; + while ( ekey->next ) ekey = ekey->next; - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; + /* use pre-behavior if time is before first key time */ + + if ( time < skey->time ) { + switch ( env->behavior[ 0 ] ) + { + case BEH_RESET: + return 0.0f; - case BEH_LINEAR: - out = outgoing( skey, skey->next ) - / ( skey->next->time - skey->time ); - return out * ( time - skey->time ) + skey->value; - } - } + case BEH_CONSTANT: + return skey->value; - /* use post-behavior if time is after last key time */ + case BEH_REPEAT: + time = range( time, skey->time, ekey->time, NULL ); + break; - else if ( time > ekey->time ) { - switch ( env->behavior[ 1 ] ) - { - case BEH_RESET: - return 0.0f; + case BEH_OSCILLATE: + time = range( time, skey->time, ekey->time, &noff ); + if ( noff % 2 ) { + time = ekey->time - skey->time - time; + } + break; - case BEH_CONSTANT: - return ekey->value; + case BEH_OFFSET: + time = range( time, skey->time, ekey->time, &noff ); + offset = noff * ( ekey->value - skey->value ); + break; - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; + case BEH_LINEAR: + out = outgoing( skey, skey->next ) + / ( skey->next->time - skey->time ); + return out * ( time - skey->time ) + skey->value; + } + } - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) - time = ekey->time - skey->time - time; - break; + /* use post-behavior if time is after last key time */ - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; + else if ( time > ekey->time ) { + switch ( env->behavior[ 1 ] ) + { + case BEH_RESET: + return 0.0f; - case BEH_LINEAR: - in = incoming( ekey->prev, ekey ) - / ( ekey->time - ekey->prev->time ); - return in * ( time - ekey->time ) + ekey->value; - } - } + case BEH_CONSTANT: + return ekey->value; - /* get the endpoints of the interval being evaluated */ + case BEH_REPEAT: + time = range( time, skey->time, ekey->time, NULL ); + break; - key0 = env->key; - while ( time > key0->next->time ) - key0 = key0->next; - key1 = key0->next; + case BEH_OSCILLATE: + time = range( time, skey->time, ekey->time, &noff ); + if ( noff % 2 ) { + time = ekey->time - skey->time - time; + } + break; - /* check for singularities first */ + case BEH_OFFSET: + time = range( time, skey->time, ekey->time, &noff ); + offset = noff * ( ekey->value - skey->value ); + break; - if ( time == key0->time ) - return key0->value + offset; - else if ( time == key1->time ) - return key1->value + offset; + case BEH_LINEAR: + in = incoming( ekey->prev, ekey ) + / ( ekey->time - ekey->prev->time ); + return in * ( time - ekey->time ) + ekey->value; + } + } - /* get interval length, time in [0, 1] */ + /* get the endpoints of the interval being evaluated */ - t = ( time - key0->time ) / ( key1->time - key0->time ); + key0 = env->key; + while ( time > key0->next->time ) + key0 = key0->next; + key1 = key0->next; - /* interpolate */ + /* check for singularities first */ - switch ( key1->shape ) - { - case ID_TCB: - case ID_BEZI: - case ID_HERM: - out = outgoing( key0, key1 ); - in = incoming( key0, key1 ); - hermite( t, &h1, &h2, &h3, &h4 ); - return h1 * key0->value + h2 * key1->value + h3 * out + h4 * in + offset; - - case ID_BEZ2: - return bez2( key0, key1, time ) + offset; - - case ID_LINE: - return key0->value + t * ( key1->value - key0->value ) + offset; - - case ID_STEP: - return key0->value + offset; - - default: - return offset; - } + if ( time == key0->time ) { + return key0->value + offset; + } + else if ( time == key1->time ) { + return key1->value + offset; + } + + /* get interval length, time in [0, 1] */ + + t = ( time - key0->time ) / ( key1->time - key0->time ); + + /* interpolate */ + + switch ( key1->shape ) + { + case ID_TCB: + case ID_BEZI: + case ID_HERM: + out = outgoing( key0, key1 ); + in = incoming( key0, key1 ); + hermite( t, &h1, &h2, &h3, &h4 ); + return h1 * key0->value + h2 * key1->value + h3 * out + h4 * in + offset; + + case ID_BEZ2: + return bez2( key0, key1, time ) + offset; + + case ID_LINE: + return key0->value + t * ( key1->value - key0->value ) + offset; + + case ID_STEP: + return key0->value + offset; + + default: + return offset; + } } diff --git a/libs/picomodel/lwo/list.c b/libs/picomodel/lwo/list.c index d337296c..d57547db 100644 --- a/libs/picomodel/lwo/list.c +++ b/libs/picomodel/lwo/list.c @@ -1,101 +1,100 @@ /* -====================================================================== -list.c + ====================================================================== + list.c -Generic linked list operations. + Generic linked list operations. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwListFree() - -Free the items in a list. -====================================================================== */ - -void lwListFree( void *list, void ( *freeNode )( void * )) -{ - lwNode *node, *next; - - node = ( lwNode * ) list; - while ( node ) { - next = node->next; - freeNode( node ); - node = next; - } + ====================================================================== + lwListFree() + + Free the items in a list. + ====================================================================== */ + +void lwListFree( void *list, void ( *freeNode )( void * ) ){ + lwNode *node, *next; + + node = ( lwNode * ) list; + while ( node ) { + next = node->next; + freeNode( node ); + node = next; + } } /* -====================================================================== -lwListAdd() - -Append a node to a list. -====================================================================== */ - -void lwListAdd( void **list, void *node ) -{ - lwNode *head, *tail; - - head = *(( lwNode ** ) list ); - if ( !head ) { - *list = node; - return; - } - while ( head ) { - tail = head; - head = head->next; - } - tail->next = ( lwNode * ) node; - (( lwNode * ) node )->prev = tail; + ====================================================================== + lwListAdd() + + Append a node to a list. + ====================================================================== */ + +void lwListAdd( void **list, void *node ){ + lwNode *head, *tail; + + head = *( ( lwNode ** ) list ); + if ( !head ) { + *list = node; + return; + } + while ( head ) { + tail = head; + head = head->next; + } + tail->next = ( lwNode * ) node; + ( ( lwNode * ) node )->prev = tail; } /* -====================================================================== -lwListInsert() - -Insert a node into a list in sorted order. -====================================================================== */ - -void lwListInsert( void **vlist, void *vitem, int ( *compare )( void *, void * )) -{ - lwNode **list, *item, *node, *prev; - - if ( !*vlist ) { - *vlist = vitem; - return; - } - - list = ( lwNode ** ) vlist; - item = ( lwNode * ) vitem; - node = *list; - prev = NULL; - - while ( node ) { - if ( 0 < compare( node, item )) break; - prev = node; - node = node->next; - } - - if ( !prev ) { - *list = item; - node->prev = item; - item->next = node; - } - else if ( !node ) { - prev->next = item; - item->prev = prev; - } - else { - item->next = node; - item->prev = prev; - prev->next = item; - node->prev = item; - } + ====================================================================== + lwListInsert() + + Insert a node into a list in sorted order. + ====================================================================== */ + +void lwListInsert( void **vlist, void *vitem, int ( *compare )( void *, void * ) ){ + lwNode **list, *item, *node, *prev; + + if ( !*vlist ) { + *vlist = vitem; + return; + } + + list = ( lwNode ** ) vlist; + item = ( lwNode * ) vitem; + node = *list; + prev = NULL; + + while ( node ) { + if ( 0 < compare( node, item ) ) { + break; + } + prev = node; + node = node->next; + } + + if ( !prev ) { + *list = item; + node->prev = item; + item->next = node; + } + else if ( !node ) { + prev->next = item; + item->prev = prev; + } + else { + item->next = node; + item->prev = prev; + prev->next = item; + node->prev = item; + } } diff --git a/libs/picomodel/lwo/lwio.c b/libs/picomodel/lwo/lwio.c index 63e9af76..0964273e 100644 --- a/libs/picomodel/lwo/lwio.c +++ b/libs/picomodel/lwo/lwio.c @@ -1,28 +1,28 @@ /* -====================================================================== -lwio.c + ====================================================================== + lwio.c -Functions for reading basic LWO2 data types. + Functions for reading basic LWO2 data types. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -flen + ====================================================================== + flen -This accumulates a count of the number of bytes read. Callers can set -it at the beginning of a sequence of reads and then retrieve it to get -the number of bytes actually read. If one of the I/O functions fails, -flen is set to an error code, after which the I/O functions ignore -read requests until flen is reset. -====================================================================== */ + This accumulates a count of the number of bytes read. Callers can set + it at the beginning of a sequence of reads and then retrieve it to get + the number of bytes actually read. If one of the I/O functions fails, + flen is set to an error code, after which the I/O functions ignore + read requests until flen is reset. + ====================================================================== */ -#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ +#define INT_MIN ( -2147483647 - 1 ) /* minimum (signed) int value */ #define FLEN_ERROR INT_MIN static int flen; @@ -34,409 +34,438 @@ int get_flen( void ) { return flen; } #ifndef __BIG_ENDIAN__ /* -===================================================================== -revbytes() + ===================================================================== + revbytes() -Reverses byte order in place. + Reverses byte order in place. -INPUTS + INPUTS bp bytes to reverse elsize size of the underlying data type elcount number of elements to swap -RESULTS + RESULTS Reverses the byte order in each of elcount elements. -This only needs to be defined on little-endian platforms, most -notably Windows. lwo2.h replaces this with a #define on big-endian -platforms. -===================================================================== */ - -void revbytes( void *bp, int elsize, int elcount ) -{ - register unsigned char *p, *q; - - p = ( unsigned char * ) bp; - - if ( elsize == 2 ) { - q = p + 1; - while ( elcount-- ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - p += 2; - q += 2; - } - return; - } - - while ( elcount-- ) { - q = p + elsize - 1; - while ( p < q ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - ++p; - --q; - } - p += elsize >> 1; - } + This only needs to be defined on little-endian platforms, most + notably Windows. lwo2.h replaces this with a #define on big-endian + platforms. + ===================================================================== */ + +void revbytes( void *bp, int elsize, int elcount ){ + register unsigned char *p, *q; + + p = ( unsigned char * ) bp; + + if ( elsize == 2 ) { + q = p + 1; + while ( elcount-- ) { + *p ^= *q; + *q ^= *p; + *p ^= *q; + p += 2; + q += 2; + } + return; + } + + while ( elcount-- ) { + q = p + elsize - 1; + while ( p < q ) { + *p ^= *q; + *q ^= *p; + *p ^= *q; + ++p; + --q; + } + p += elsize >> 1; + } } #endif -void *getbytes( picoMemStream_t *fp, int size ) -{ - void *data; - - if ( flen == FLEN_ERROR ) return NULL; - if ( size < 0 ) { - flen = FLEN_ERROR; - return NULL; - } - data = _pico_alloc( size ); - if ( !data ) { - flen = FLEN_ERROR; - return NULL; - } - if ( 1 != _pico_memstream_read( fp, data, size )) { - flen = FLEN_ERROR; - _pico_free( data ); - return NULL; - } - - flen += size; - return data; +void *getbytes( picoMemStream_t *fp, int size ){ + void *data; + + if ( flen == FLEN_ERROR ) { + return NULL; + } + if ( size < 0 ) { + flen = FLEN_ERROR; + return NULL; + } + data = _pico_alloc( size ); + if ( !data ) { + flen = FLEN_ERROR; + return NULL; + } + if ( 1 != _pico_memstream_read( fp, data, size ) ) { + flen = FLEN_ERROR; + _pico_free( data ); + return NULL; + } + + flen += size; + return data; } -void skipbytes( picoMemStream_t *fp, int n ) -{ - if ( flen == FLEN_ERROR ) return; - if ( _pico_memstream_seek( fp, n, PICO_SEEK_CUR )) - flen = FLEN_ERROR; - else - flen += n; +void skipbytes( picoMemStream_t *fp, int n ){ + if ( flen == FLEN_ERROR ) { + return; + } + if ( _pico_memstream_seek( fp, n, PICO_SEEK_CUR ) ) { + flen = FLEN_ERROR; + } + else{ + flen += n; + } } -int getI1( picoMemStream_t *fp ) -{ - int i; - - if ( flen == FLEN_ERROR ) return 0; - i = _pico_memstream_getc( fp ); - if ( i < 0 ) { - flen = FLEN_ERROR; - return 0; - } - if ( i > 127 ) i -= 256; - flen += 1; - return i; +int getI1( picoMemStream_t *fp ){ + int i; + + if ( flen == FLEN_ERROR ) { + return 0; + } + i = _pico_memstream_getc( fp ); + if ( i < 0 ) { + flen = FLEN_ERROR; + return 0; + } + if ( i > 127 ) { + i -= 256; + } + flen += 1; + return i; } -short getI2( picoMemStream_t *fp ) -{ - short i; +short getI2( picoMemStream_t *fp ){ + short i; - if ( flen == FLEN_ERROR ) return 0; - if ( 1 != _pico_memstream_read( fp, &i, 2 )) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + if ( 1 != _pico_memstream_read( fp, &i, 2 ) ) { + flen = FLEN_ERROR; + return 0; + } + revbytes( &i, 2, 1 ); + flen += 2; + return i; } -int getI4( picoMemStream_t *fp ) -{ - int i; +int getI4( picoMemStream_t *fp ){ + int i; - if ( flen == FLEN_ERROR ) return 0; - if ( 1 != _pico_memstream_read( fp, &i, 4 )) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + if ( 1 != _pico_memstream_read( fp, &i, 4 ) ) { + flen = FLEN_ERROR; + return 0; + } + revbytes( &i, 4, 1 ); + flen += 4; + return i; } -unsigned char getU1( picoMemStream_t *fp ) -{ - int i; +unsigned char getU1( picoMemStream_t *fp ){ + int i; - if ( flen == FLEN_ERROR ) return 0; - i = _pico_memstream_getc( fp ); - if ( i < 0 ) { - flen = FLEN_ERROR; - return 0; - } - flen += 1; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + i = _pico_memstream_getc( fp ); + if ( i < 0 ) { + flen = FLEN_ERROR; + return 0; + } + flen += 1; + return i; } -unsigned short getU2( picoMemStream_t *fp ) -{ - unsigned short i; +unsigned short getU2( picoMemStream_t *fp ){ + unsigned short i; - if ( flen == FLEN_ERROR ) return 0; - if ( 1 != _pico_memstream_read( fp, &i, 2 )) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + if ( 1 != _pico_memstream_read( fp, &i, 2 ) ) { + flen = FLEN_ERROR; + return 0; + } + revbytes( &i, 2, 1 ); + flen += 2; + return i; } -unsigned int getU4( picoMemStream_t *fp ) -{ - unsigned int i; +unsigned int getU4( picoMemStream_t *fp ){ + unsigned int i; - if ( flen == FLEN_ERROR ) return 0; - if ( 1 != _pico_memstream_read( fp, &i, 4 )) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + if ( 1 != _pico_memstream_read( fp, &i, 4 ) ) { + flen = FLEN_ERROR; + return 0; + } + revbytes( &i, 4, 1 ); + flen += 4; + return i; } -int getVX( picoMemStream_t *fp ) -{ - int i, c; - - if ( flen == FLEN_ERROR ) return 0; - - c = _pico_memstream_getc( fp ); - if ( c != 0xFF ) { - i = c << 8; - c = _pico_memstream_getc( fp ); - i |= c; - flen += 2; - } - else { - c = _pico_memstream_getc( fp ); - i = c << 16; - c = _pico_memstream_getc( fp ); - i |= c << 8; - c = _pico_memstream_getc( fp ); - i |= c; - flen += 4; - } - - if ( _pico_memstream_error( fp )) { - flen = FLEN_ERROR; - return 0; - } - return i; +int getVX( picoMemStream_t *fp ){ + int i, c; + + if ( flen == FLEN_ERROR ) { + return 0; + } + + c = _pico_memstream_getc( fp ); + if ( c != 0xFF ) { + i = c << 8; + c = _pico_memstream_getc( fp ); + i |= c; + flen += 2; + } + else { + c = _pico_memstream_getc( fp ); + i = c << 16; + c = _pico_memstream_getc( fp ); + i |= c << 8; + c = _pico_memstream_getc( fp ); + i |= c; + flen += 4; + } + + if ( _pico_memstream_error( fp ) ) { + flen = FLEN_ERROR; + return 0; + } + return i; } -float getF4( picoMemStream_t *fp ) -{ - float f; +float getF4( picoMemStream_t *fp ){ + float f; - if ( flen == FLEN_ERROR ) return 0.0f; - if ( 1 != _pico_memstream_read( fp, &f, 4 )) { - flen = FLEN_ERROR; - return 0.0f; - } - revbytes( &f, 4, 1 ); - flen += 4; - return f; + if ( flen == FLEN_ERROR ) { + return 0.0f; + } + if ( 1 != _pico_memstream_read( fp, &f, 4 ) ) { + flen = FLEN_ERROR; + return 0.0f; + } + revbytes( &f, 4, 1 ); + flen += 4; + return f; } -char *getS0( picoMemStream_t *fp ) -{ - char *s; - int i, c, len, pos; - - if ( flen == FLEN_ERROR ) return NULL; - - pos = _pico_memstream_tell( fp ); - for ( i = 1; ; i++ ) { - c = _pico_memstream_getc( fp ); - if ( c <= 0 ) break; - } - if ( c < 0 ) { - flen = FLEN_ERROR; - return NULL; - } - - if ( i == 1 ) { - if ( _pico_memstream_seek( fp, pos + 2, PICO_SEEK_SET )) - flen = FLEN_ERROR; - else - flen += 2; - return NULL; - } - - len = i + ( i & 1 ); - s = _pico_alloc( len ); - if ( !s ) { - flen = FLEN_ERROR; - return NULL; - } - - if ( _pico_memstream_seek( fp, pos, PICO_SEEK_SET )) { - flen = FLEN_ERROR; - return NULL; - } - if ( 1 != _pico_memstream_read( fp, s, len )) { - flen = FLEN_ERROR; - return NULL; - } - - flen += len; - return s; +char *getS0( picoMemStream_t *fp ){ + char *s; + int i, c, len, pos; + + if ( flen == FLEN_ERROR ) { + return NULL; + } + + pos = _pico_memstream_tell( fp ); + for ( i = 1; ; i++ ) { + c = _pico_memstream_getc( fp ); + if ( c <= 0 ) { + break; + } + } + if ( c < 0 ) { + flen = FLEN_ERROR; + return NULL; + } + + if ( i == 1 ) { + if ( _pico_memstream_seek( fp, pos + 2, PICO_SEEK_SET ) ) { + flen = FLEN_ERROR; + } + else{ + flen += 2; + } + return NULL; + } + + len = i + ( i & 1 ); + s = _pico_alloc( len ); + if ( !s ) { + flen = FLEN_ERROR; + return NULL; + } + + if ( _pico_memstream_seek( fp, pos, PICO_SEEK_SET ) ) { + flen = FLEN_ERROR; + return NULL; + } + if ( 1 != _pico_memstream_read( fp, s, len ) ) { + flen = FLEN_ERROR; + return NULL; + } + + flen += len; + return s; } -int sgetI1( unsigned char **bp ) -{ - int i; +int sgetI1( unsigned char **bp ){ + int i; - if ( flen == FLEN_ERROR ) return 0; - i = **bp; - if ( i > 127 ) i -= 256; - flen += 1; - (*bp)++; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + i = **bp; + if ( i > 127 ) { + i -= 256; + } + flen += 1; + ( *bp )++; + return i; } -short sgetI2( unsigned char **bp ) -{ - short i; +short sgetI2( unsigned char **bp ){ + short i; - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 2 ); - revbytes( &i, 2, 1 ); - flen += 2; - *bp += 2; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + memcpy( &i, *bp, 2 ); + revbytes( &i, 2, 1 ); + flen += 2; + *bp += 2; + return i; } -int sgetI4( unsigned char **bp ) -{ - int i; +int sgetI4( unsigned char **bp ){ + int i; - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + memcpy( &i, *bp, 4 ); + revbytes( &i, 4, 1 ); + flen += 4; + *bp += 4; + return i; } -unsigned char sgetU1( unsigned char **bp ) -{ - unsigned char c; +unsigned char sgetU1( unsigned char **bp ){ + unsigned char c; - if ( flen == FLEN_ERROR ) return 0; - c = **bp; - flen += 1; - (*bp)++; - return c; + if ( flen == FLEN_ERROR ) { + return 0; + } + c = **bp; + flen += 1; + ( *bp )++; + return c; } -unsigned short sgetU2( unsigned char **bp ) -{ - unsigned char *buf = *bp; - unsigned short i; +unsigned short sgetU2( unsigned char **bp ){ + unsigned char *buf = *bp; + unsigned short i; - if ( flen == FLEN_ERROR ) return 0; - i = ( buf[ 0 ] << 8 ) | buf[ 1 ]; - flen += 2; - *bp += 2; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + i = ( buf[ 0 ] << 8 ) | buf[ 1 ]; + flen += 2; + *bp += 2; + return i; } -unsigned int sgetU4( unsigned char **bp ) -{ - unsigned int i; +unsigned int sgetU4( unsigned char **bp ){ + unsigned int i; - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; + if ( flen == FLEN_ERROR ) { + return 0; + } + memcpy( &i, *bp, 4 ); + revbytes( &i, 4, 1 ); + flen += 4; + *bp += 4; + return i; } -int sgetVX( unsigned char **bp ) -{ - unsigned char *buf = *bp; - int i; - - if ( flen == FLEN_ERROR ) return 0; - - if ( buf[ 0 ] != 0xFF ) { - i = buf[ 0 ] << 8 | buf[ 1 ]; - flen += 2; - *bp += 2; - } - else { - i = ( buf[ 1 ] << 16 ) | ( buf[ 2 ] << 8 ) | buf[ 3 ]; - flen += 4; - *bp += 4; - } - return i; +int sgetVX( unsigned char **bp ){ + unsigned char *buf = *bp; + int i; + + if ( flen == FLEN_ERROR ) { + return 0; + } + + if ( buf[ 0 ] != 0xFF ) { + i = buf[ 0 ] << 8 | buf[ 1 ]; + flen += 2; + *bp += 2; + } + else { + i = ( buf[ 1 ] << 16 ) | ( buf[ 2 ] << 8 ) | buf[ 3 ]; + flen += 4; + *bp += 4; + } + return i; } -float sgetF4( unsigned char **bp ) -{ - float f; +float sgetF4( unsigned char **bp ){ + float f; - if ( flen == FLEN_ERROR ) return 0.0f; - memcpy( &f, *bp, 4 ); - revbytes( &f, 4, 1 ); - flen += 4; - *bp += 4; - return f; + if ( flen == FLEN_ERROR ) { + return 0.0f; + } + memcpy( &f, *bp, 4 ); + revbytes( &f, 4, 1 ); + flen += 4; + *bp += 4; + return f; } -char *sgetS0( unsigned char **bp ) -{ - char *s; - unsigned char *buf = *bp; - int len; - - if ( flen == FLEN_ERROR ) return NULL; - - len = strlen( (const char *) buf ) + 1; - if ( len == 1 ) { - flen += 2; - *bp += 2; - return NULL; - } - len += len & 1; - s = _pico_alloc( len ); - if ( !s ) { - flen = FLEN_ERROR; - return NULL; - } - - memcpy( s, buf, len ); - flen += len; - *bp += len; - return s; +char *sgetS0( unsigned char **bp ){ + char *s; + unsigned char *buf = *bp; + int len; + + if ( flen == FLEN_ERROR ) { + return NULL; + } + + len = strlen( (const char *) buf ) + 1; + if ( len == 1 ) { + flen += 2; + *bp += 2; + return NULL; + } + len += len & 1; + s = _pico_alloc( len ); + if ( !s ) { + flen = FLEN_ERROR; + return NULL; + } + + memcpy( s, buf, len ); + flen += len; + *bp += len; + return s; } diff --git a/libs/picomodel/lwo/lwo2.c b/libs/picomodel/lwo/lwo2.c index 9e45bfa1..1bbc7a36 100644 --- a/libs/picomodel/lwo/lwo2.c +++ b/libs/picomodel/lwo/lwo2.c @@ -1,11 +1,11 @@ /* -====================================================================== -lwo2.c + ====================================================================== + lwo2.c -The entry point for loading LightWave object files. + The entry point for loading LightWave object files. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" @@ -17,292 +17,348 @@ Ernie Wright 17 Sep 00 /* -====================================================================== -lwFreeLayer() - -Free memory used by an lwLayer. -====================================================================== */ - -void lwFreeLayer( lwLayer *layer ) -{ - if ( layer ) { - if ( layer->name ) _pico_free( layer->name ); - lwFreePoints( &layer->point ); - lwFreePolygons( &layer->polygon ); - lwListFree( layer->vmap, (void *) lwFreeVMap ); - _pico_free( layer ); - } + ====================================================================== + lwFreeLayer() + + Free memory used by an lwLayer. + ====================================================================== */ + +void lwFreeLayer( lwLayer *layer ){ + if ( layer ) { + if ( layer->name ) { + _pico_free( layer->name ); + } + lwFreePoints( &layer->point ); + lwFreePolygons( &layer->polygon ); + lwListFree( layer->vmap, (void *) lwFreeVMap ); + _pico_free( layer ); + } } /* -====================================================================== -lwFreeObject() - -Free memory used by an lwObject. -====================================================================== */ - -void lwFreeObject( lwObject *object ) -{ - if ( object ) { - lwListFree( object->layer, (void *) lwFreeLayer ); - lwListFree( object->env, (void *) lwFreeEnvelope ); - lwListFree( object->clip, (void *) lwFreeClip ); - lwListFree( object->surf, (void *) lwFreeSurface ); - lwFreeTags( &object->taglist ); - _pico_free( object ); - } + ====================================================================== + lwFreeObject() + + Free memory used by an lwObject. + ====================================================================== */ + +void lwFreeObject( lwObject *object ){ + if ( object ) { + lwListFree( object->layer, (void *) lwFreeLayer ); + lwListFree( object->env, (void *) lwFreeEnvelope ); + lwListFree( object->clip, (void *) lwFreeClip ); + lwListFree( object->surf, (void *) lwFreeSurface ); + lwFreeTags( &object->taglist ); + _pico_free( object ); + } } /* -====================================================================== -lwGetObject() + ====================================================================== + lwGetObject() -Returns the contents of a LightWave object, given its filename, or -NULL if the file couldn't be loaded. On failure, failID and failpos -can be used to diagnose the cause. + Returns the contents of a LightWave object, given its filename, or + NULL if the file couldn't be loaded. On failure, failID and failpos + can be used to diagnose the cause. -1. If the file isn't an LWO2 or an LWOB, failpos will contain 12 and + 1. If the file isn't an LWO2 or an LWOB, failpos will contain 12 and failID will be unchanged. -2. If an error occurs while reading, failID will contain the most + 2. If an error occurs while reading, failID will contain the most recently read IFF chunk ID, and failpos will contain the value returned by _pico_memstream_tell() at the time of the failure. -3. If the file couldn't be opened, or an error occurs while reading + 3. If the file couldn't be opened, or an error occurs while reading the first 12 bytes, both failID and failpos will be unchanged. -If you don't need this information, failID and failpos can be NULL. -====================================================================== */ - -lwObject *lwGetObject( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) -{ - lwObject *object; - lwLayer *layer; - lwNode *node; - unsigned int id, formsize, type; - int i, rlen, cksize; - - /* open the file */ - - if ( !fp ) return NULL; - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return NULL; - } - - /* is this a LW object? */ - - if ( id != ID_FORM ) { - if ( failpos ) *failpos = 12; - return NULL; - } - - if ( type != ID_LWO2 ) { - if ( type == ID_LWOB ) - return lwGetObject5( filename, fp, failID, failpos ); - else { - if ( failpos ) *failpos = 12; - return NULL; - } - } - - /* allocate an object and a default layer */ - - object = _pico_calloc( 1, sizeof( lwObject )); - if ( !object ) goto Fail; - - layer = _pico_calloc( 1, sizeof( lwLayer )); - if ( !layer ) goto Fail; - object->layer = layer; - - /* get the first chunk header */ - - id = getU4( fp ); - cksize = getU4( fp ); - if ( 0 > get_flen() ) goto Fail; - - /* process chunks as they're encountered */ - - while ( 1 ) { - cksize += cksize & 1; - - switch ( id ) - { - case ID_LAYR: - if ( object->nlayers > 0 ) { - layer = _pico_calloc( 1, sizeof( lwLayer )); - if ( !layer ) goto Fail; - lwListAdd( (void **) &object->layer, layer ); - } - object->nlayers++; - - set_flen( 0 ); - layer->index = getU2( fp ); - layer->flags = getU2( fp ); - layer->pivot[ 0 ] = getF4( fp ); - layer->pivot[ 1 ] = getF4( fp ); - layer->pivot[ 2 ] = getF4( fp ); - layer->name = getS0( fp ); - - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) goto Fail; - if ( rlen <= cksize - 2 ) - layer->parent = getU2( fp ); - rlen = get_flen(); - if ( rlen < cksize ) - _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); - break; - - case ID_PNTS: - if ( !lwGetPoints( fp, cksize, &layer->point )) - goto Fail; - break; - - case ID_POLS: - if ( !lwGetPolygons( fp, cksize, &layer->polygon, - layer->point.offset )) - goto Fail; - break; - - case ID_VMAP: - case ID_VMAD: - node = ( lwNode * ) lwGetVMap( fp, cksize, layer->point.offset, - layer->polygon.offset, id == ID_VMAD ); - if ( !node ) goto Fail; - lwListAdd( (void **) &layer->vmap, node ); - layer->nvmaps++; - break; - - case ID_PTAG: - if ( !lwGetPolygonTags( fp, cksize, &object->taglist, - &layer->polygon )) - goto Fail; - break; - - case ID_BBOX: - set_flen( 0 ); - for ( i = 0; i < 6; i++ ) - layer->bbox[ i ] = getF4( fp ); - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) goto Fail; - if ( rlen < cksize ) - _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); - break; - - case ID_TAGS: - if ( !lwGetTags( fp, cksize, &object->taglist )) - goto Fail; - break; - - case ID_ENVL: - node = ( lwNode * ) lwGetEnvelope( fp, cksize ); - if ( !node ) goto Fail; - lwListAdd( (void **) &object->env, node ); - object->nenvs++; - break; - - case ID_CLIP: - node = ( lwNode * ) lwGetClip( fp, cksize ); - if ( !node ) goto Fail; - lwListAdd( (void **) &object->clip, node ); - object->nclips++; - break; - - case ID_SURF: - node = ( lwNode * ) lwGetSurface( fp, cksize ); - if ( !node ) goto Fail; - lwListAdd( (void **) &object->surf, node ); - object->nsurfs++; - break; - - case ID_DESC: - case ID_TEXT: - case ID_ICON: - default: - _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); - break; - } - - /* end of the file? */ - - if ( formsize <= (unsigned int) (_pico_memstream_tell( fp ) - 8) ) break; - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - cksize = getU4( fp ); - if ( 8 != get_flen() ) goto Fail; - } - - if ( object->nlayers == 0 ) - object->nlayers = 1; - - layer = object->layer; - while ( layer ) { - lwGetBoundingBox( &layer->point, layer->bbox ); - lwGetPolyNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointPolygons( &layer->point, &layer->polygon )) goto Fail; - if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, - &object->surf, &object->nsurfs )) goto Fail; - lwGetVertNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointVMaps( &layer->point, layer->vmap )) goto Fail; - if ( !lwGetPolyVMaps( &layer->polygon, layer->vmap )) goto Fail; - layer = layer->next; - } - - return object; + If you don't need this information, failID and failpos can be NULL. + ====================================================================== */ + +lwObject *lwGetObject( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ + lwObject *object; + lwLayer *layer; + lwNode *node; + unsigned int id, formsize, type; + int i, rlen, cksize; + + /* open the file */ + + if ( !fp ) { + return NULL; + } + + /* read the first 12 bytes */ + + set_flen( 0 ); + id = getU4( fp ); + formsize = getU4( fp ); + type = getU4( fp ); + if ( 12 != get_flen() ) { + return NULL; + } + + /* is this a LW object? */ + + if ( id != ID_FORM ) { + if ( failpos ) { + *failpos = 12; + } + return NULL; + } + + if ( type != ID_LWO2 ) { + if ( type == ID_LWOB ) { + return lwGetObject5( filename, fp, failID, failpos ); + } + else { + if ( failpos ) { + *failpos = 12; + } + return NULL; + } + } + + /* allocate an object and a default layer */ + + object = _pico_calloc( 1, sizeof( lwObject ) ); + if ( !object ) { + goto Fail; + } + + layer = _pico_calloc( 1, sizeof( lwLayer ) ); + if ( !layer ) { + goto Fail; + } + object->layer = layer; + + /* get the first chunk header */ + + id = getU4( fp ); + cksize = getU4( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + /* process chunks as they're encountered */ + + while ( 1 ) { + cksize += cksize & 1; + + switch ( id ) + { + case ID_LAYR: + if ( object->nlayers > 0 ) { + layer = _pico_calloc( 1, sizeof( lwLayer ) ); + if ( !layer ) { + goto Fail; + } + lwListAdd( (void **) &object->layer, layer ); + } + object->nlayers++; + + set_flen( 0 ); + layer->index = getU2( fp ); + layer->flags = getU2( fp ); + layer->pivot[ 0 ] = getF4( fp ); + layer->pivot[ 1 ] = getF4( fp ); + layer->pivot[ 2 ] = getF4( fp ); + layer->name = getS0( fp ); + + rlen = get_flen(); + if ( rlen < 0 || rlen > cksize ) { + goto Fail; + } + if ( rlen <= cksize - 2 ) { + layer->parent = getU2( fp ); + } + rlen = get_flen(); + if ( rlen < cksize ) { + _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); + } + break; + + case ID_PNTS: + if ( !lwGetPoints( fp, cksize, &layer->point ) ) { + goto Fail; + } + break; + + case ID_POLS: + if ( !lwGetPolygons( fp, cksize, &layer->polygon, + layer->point.offset ) ) { + goto Fail; + } + break; + + case ID_VMAP: + case ID_VMAD: + node = ( lwNode * ) lwGetVMap( fp, cksize, layer->point.offset, + layer->polygon.offset, id == ID_VMAD ); + if ( !node ) { + goto Fail; + } + lwListAdd( (void **) &layer->vmap, node ); + layer->nvmaps++; + break; + + case ID_PTAG: + if ( !lwGetPolygonTags( fp, cksize, &object->taglist, + &layer->polygon ) ) { + goto Fail; + } + break; + + case ID_BBOX: + set_flen( 0 ); + for ( i = 0; i < 6; i++ ) + layer->bbox[ i ] = getF4( fp ); + rlen = get_flen(); + if ( rlen < 0 || rlen > cksize ) { + goto Fail; + } + if ( rlen < cksize ) { + _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); + } + break; + + case ID_TAGS: + if ( !lwGetTags( fp, cksize, &object->taglist ) ) { + goto Fail; + } + break; + + case ID_ENVL: + node = ( lwNode * ) lwGetEnvelope( fp, cksize ); + if ( !node ) { + goto Fail; + } + lwListAdd( (void **) &object->env, node ); + object->nenvs++; + break; + + case ID_CLIP: + node = ( lwNode * ) lwGetClip( fp, cksize ); + if ( !node ) { + goto Fail; + } + lwListAdd( (void **) &object->clip, node ); + object->nclips++; + break; + + case ID_SURF: + node = ( lwNode * ) lwGetSurface( fp, cksize ); + if ( !node ) { + goto Fail; + } + lwListAdd( (void **) &object->surf, node ); + object->nsurfs++; + break; + + case ID_DESC: + case ID_TEXT: + case ID_ICON: + default: + _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); + break; + } + + /* end of the file? */ + + if ( formsize <= (unsigned int) ( _pico_memstream_tell( fp ) - 8 ) ) { + break; + } + + /* get the next chunk header */ + + set_flen( 0 ); + id = getU4( fp ); + cksize = getU4( fp ); + if ( 8 != get_flen() ) { + goto Fail; + } + } + + if ( object->nlayers == 0 ) { + object->nlayers = 1; + } + + layer = object->layer; + while ( layer ) { + lwGetBoundingBox( &layer->point, layer->bbox ); + lwGetPolyNormals( &layer->point, &layer->polygon ); + if ( !lwGetPointPolygons( &layer->point, &layer->polygon ) ) { + goto Fail; + } + if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, + &object->surf, &object->nsurfs ) ) { + goto Fail; + } + lwGetVertNormals( &layer->point, &layer->polygon ); + if ( !lwGetPointVMaps( &layer->point, layer->vmap ) ) { + goto Fail; + } + if ( !lwGetPolyVMaps( &layer->polygon, layer->vmap ) ) { + goto Fail; + } + layer = layer->next; + } + + return object; Fail: - if ( failID ) *failID = id; - if ( fp ) { - if ( failpos ) *failpos = _pico_memstream_tell( fp ); - } - lwFreeObject( object ); - return NULL; + if ( failID ) { + *failID = id; + } + if ( fp ) { + if ( failpos ) { + *failpos = _pico_memstream_tell( fp ); + } + } + lwFreeObject( object ); + return NULL; } -int lwValidateObject( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) -{ - unsigned int id, type; - - /* open the file */ - - if ( !fp ) return PICO_PMV_ERROR_MEMORY; - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - /* formsize = */ getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return PICO_PMV_ERROR_SIZE; - } - - /* is this a LW object? */ - - if ( id != ID_FORM ) { - if ( failpos ) *failpos = 12; - return PICO_PMV_ERROR_SIZE; - } - - if ( type != ID_LWO2 ) { - if ( type == ID_LWOB ) - return lwValidateObject5( filename, fp, failID, failpos ); - else { - if ( failpos ) *failpos = 12; - return PICO_PMV_ERROR_IDENT; - } - } - - return PICO_PMV_OK; +int lwValidateObject( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ + unsigned int id, type; + + /* open the file */ + + if ( !fp ) { + return PICO_PMV_ERROR_MEMORY; + } + + /* read the first 12 bytes */ + + set_flen( 0 ); + id = getU4( fp ); + /* formsize = */ getU4( fp ); + type = getU4( fp ); + if ( 12 != get_flen() ) { + return PICO_PMV_ERROR_SIZE; + } + + /* is this a LW object? */ + + if ( id != ID_FORM ) { + if ( failpos ) { + *failpos = 12; + } + return PICO_PMV_ERROR_SIZE; + } + + if ( type != ID_LWO2 ) { + if ( type == ID_LWOB ) { + return lwValidateObject5( filename, fp, failID, failpos ); + } + else { + if ( failpos ) { + *failpos = 12; + } + return PICO_PMV_ERROR_IDENT; + } + } + + return PICO_PMV_OK; } diff --git a/libs/picomodel/lwo/lwo2.h b/libs/picomodel/lwo/lwo2.h index e5b96115..d055c13e 100644 --- a/libs/picomodel/lwo/lwo2.h +++ b/libs/picomodel/lwo/lwo2.h @@ -1,205 +1,205 @@ /* -====================================================================== -lwo2.h + ====================================================================== + lwo2.h -Definitions and typedefs for LWO2 files. + Definitions and typedefs for LWO2 files. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #ifndef LWO2_H #define LWO2_H /* chunk and subchunk IDs */ -#define LWID_(a,b,c,d) (((a)<<24)|((b)<<16)|((c)<<8)|(d)) +#define LWID_( a,b,c,d ) ( ( ( a ) << 24 ) | ( ( b ) << 16 ) | ( ( c ) << 8 ) | ( d ) ) -#define ID_FORM LWID_('F','O','R','M') -#define ID_LWO2 LWID_('L','W','O','2') -#define ID_LWOB LWID_('L','W','O','B') +#define ID_FORM LWID_( 'F','O','R','M' ) +#define ID_LWO2 LWID_( 'L','W','O','2' ) +#define ID_LWOB LWID_( 'L','W','O','B' ) /* top-level chunks */ -#define ID_LAYR LWID_('L','A','Y','R') -#define ID_TAGS LWID_('T','A','G','S') -#define ID_PNTS LWID_('P','N','T','S') -#define ID_BBOX LWID_('B','B','O','X') -#define ID_VMAP LWID_('V','M','A','P') -#define ID_VMAD LWID_('V','M','A','D') -#define ID_POLS LWID_('P','O','L','S') -#define ID_PTAG LWID_('P','T','A','G') -#define ID_ENVL LWID_('E','N','V','L') -#define ID_CLIP LWID_('C','L','I','P') -#define ID_SURF LWID_('S','U','R','F') -#define ID_DESC LWID_('D','E','S','C') -#define ID_TEXT LWID_('T','E','X','T') -#define ID_ICON LWID_('I','C','O','N') +#define ID_LAYR LWID_( 'L','A','Y','R' ) +#define ID_TAGS LWID_( 'T','A','G','S' ) +#define ID_PNTS LWID_( 'P','N','T','S' ) +#define ID_BBOX LWID_( 'B','B','O','X' ) +#define ID_VMAP LWID_( 'V','M','A','P' ) +#define ID_VMAD LWID_( 'V','M','A','D' ) +#define ID_POLS LWID_( 'P','O','L','S' ) +#define ID_PTAG LWID_( 'P','T','A','G' ) +#define ID_ENVL LWID_( 'E','N','V','L' ) +#define ID_CLIP LWID_( 'C','L','I','P' ) +#define ID_SURF LWID_( 'S','U','R','F' ) +#define ID_DESC LWID_( 'D','E','S','C' ) +#define ID_TEXT LWID_( 'T','E','X','T' ) +#define ID_ICON LWID_( 'I','C','O','N' ) /* polygon types */ -#define ID_FACE LWID_('F','A','C','E') -#define ID_CURV LWID_('C','U','R','V') -#define ID_PTCH LWID_('P','T','C','H') -#define ID_MBAL LWID_('M','B','A','L') -#define ID_BONE LWID_('B','O','N','E') +#define ID_FACE LWID_( 'F','A','C','E' ) +#define ID_CURV LWID_( 'C','U','R','V' ) +#define ID_PTCH LWID_( 'P','T','C','H' ) +#define ID_MBAL LWID_( 'M','B','A','L' ) +#define ID_BONE LWID_( 'B','O','N','E' ) /* polygon tags */ -#define ID_SURF LWID_('S','U','R','F') -#define ID_PART LWID_('P','A','R','T') -#define ID_SMGP LWID_('S','M','G','P') +#define ID_SURF LWID_( 'S','U','R','F' ) +#define ID_PART LWID_( 'P','A','R','T' ) +#define ID_SMGP LWID_( 'S','M','G','P' ) /* envelopes */ -#define ID_PRE LWID_('P','R','E',' ') -#define ID_POST LWID_('P','O','S','T') -#define ID_KEY LWID_('K','E','Y',' ') -#define ID_SPAN LWID_('S','P','A','N') -#define ID_TCB LWID_('T','C','B',' ') -#define ID_HERM LWID_('H','E','R','M') -#define ID_BEZI LWID_('B','E','Z','I') -#define ID_BEZ2 LWID_('B','E','Z','2') -#define ID_LINE LWID_('L','I','N','E') -#define ID_STEP LWID_('S','T','E','P') +#define ID_PRE LWID_( 'P','R','E',' ' ) +#define ID_POST LWID_( 'P','O','S','T' ) +#define ID_KEY LWID_( 'K','E','Y',' ' ) +#define ID_SPAN LWID_( 'S','P','A','N' ) +#define ID_TCB LWID_( 'T','C','B',' ' ) +#define ID_HERM LWID_( 'H','E','R','M' ) +#define ID_BEZI LWID_( 'B','E','Z','I' ) +#define ID_BEZ2 LWID_( 'B','E','Z','2' ) +#define ID_LINE LWID_( 'L','I','N','E' ) +#define ID_STEP LWID_( 'S','T','E','P' ) /* clips */ -#define ID_STIL LWID_('S','T','I','L') -#define ID_ISEQ LWID_('I','S','E','Q') -#define ID_ANIM LWID_('A','N','I','M') -#define ID_XREF LWID_('X','R','E','F') -#define ID_STCC LWID_('S','T','C','C') -#define ID_TIME LWID_('T','I','M','E') -#define ID_CONT LWID_('C','O','N','T') -#define ID_BRIT LWID_('B','R','I','T') -#define ID_SATR LWID_('S','A','T','R') -#define ID_HUE LWID_('H','U','E',' ') -#define ID_GAMM LWID_('G','A','M','M') -#define ID_NEGA LWID_('N','E','G','A') -#define ID_IFLT LWID_('I','F','L','T') -#define ID_PFLT LWID_('P','F','L','T') +#define ID_STIL LWID_( 'S','T','I','L' ) +#define ID_ISEQ LWID_( 'I','S','E','Q' ) +#define ID_ANIM LWID_( 'A','N','I','M' ) +#define ID_XREF LWID_( 'X','R','E','F' ) +#define ID_STCC LWID_( 'S','T','C','C' ) +#define ID_TIME LWID_( 'T','I','M','E' ) +#define ID_CONT LWID_( 'C','O','N','T' ) +#define ID_BRIT LWID_( 'B','R','I','T' ) +#define ID_SATR LWID_( 'S','A','T','R' ) +#define ID_HUE LWID_( 'H','U','E',' ' ) +#define ID_GAMM LWID_( 'G','A','M','M' ) +#define ID_NEGA LWID_( 'N','E','G','A' ) +#define ID_IFLT LWID_( 'I','F','L','T' ) +#define ID_PFLT LWID_( 'P','F','L','T' ) /* surfaces */ -#define ID_COLR LWID_('C','O','L','R') -#define ID_LUMI LWID_('L','U','M','I') -#define ID_DIFF LWID_('D','I','F','F') -#define ID_SPEC LWID_('S','P','E','C') -#define ID_GLOS LWID_('G','L','O','S') -#define ID_REFL LWID_('R','E','F','L') -#define ID_RFOP LWID_('R','F','O','P') -#define ID_RIMG LWID_('R','I','M','G') -#define ID_RSAN LWID_('R','S','A','N') -#define ID_TRAN LWID_('T','R','A','N') -#define ID_TROP LWID_('T','R','O','P') -#define ID_TIMG LWID_('T','I','M','G') -#define ID_RIND LWID_('R','I','N','D') -#define ID_TRNL LWID_('T','R','N','L') -#define ID_BUMP LWID_('B','U','M','P') -#define ID_SMAN LWID_('S','M','A','N') -#define ID_SIDE LWID_('S','I','D','E') -#define ID_CLRH LWID_('C','L','R','H') -#define ID_CLRF LWID_('C','L','R','F') -#define ID_ADTR LWID_('A','D','T','R') -#define ID_SHRP LWID_('S','H','R','P') -#define ID_LINE LWID_('L','I','N','E') -#define ID_LSIZ LWID_('L','S','I','Z') -#define ID_ALPH LWID_('A','L','P','H') -#define ID_AVAL LWID_('A','V','A','L') -#define ID_GVAL LWID_('G','V','A','L') -#define ID_BLOK LWID_('B','L','O','K') +#define ID_COLR LWID_( 'C','O','L','R' ) +#define ID_LUMI LWID_( 'L','U','M','I' ) +#define ID_DIFF LWID_( 'D','I','F','F' ) +#define ID_SPEC LWID_( 'S','P','E','C' ) +#define ID_GLOS LWID_( 'G','L','O','S' ) +#define ID_REFL LWID_( 'R','E','F','L' ) +#define ID_RFOP LWID_( 'R','F','O','P' ) +#define ID_RIMG LWID_( 'R','I','M','G' ) +#define ID_RSAN LWID_( 'R','S','A','N' ) +#define ID_TRAN LWID_( 'T','R','A','N' ) +#define ID_TROP LWID_( 'T','R','O','P' ) +#define ID_TIMG LWID_( 'T','I','M','G' ) +#define ID_RIND LWID_( 'R','I','N','D' ) +#define ID_TRNL LWID_( 'T','R','N','L' ) +#define ID_BUMP LWID_( 'B','U','M','P' ) +#define ID_SMAN LWID_( 'S','M','A','N' ) +#define ID_SIDE LWID_( 'S','I','D','E' ) +#define ID_CLRH LWID_( 'C','L','R','H' ) +#define ID_CLRF LWID_( 'C','L','R','F' ) +#define ID_ADTR LWID_( 'A','D','T','R' ) +#define ID_SHRP LWID_( 'S','H','R','P' ) +#define ID_LINE LWID_( 'L','I','N','E' ) +#define ID_LSIZ LWID_( 'L','S','I','Z' ) +#define ID_ALPH LWID_( 'A','L','P','H' ) +#define ID_AVAL LWID_( 'A','V','A','L' ) +#define ID_GVAL LWID_( 'G','V','A','L' ) +#define ID_BLOK LWID_( 'B','L','O','K' ) /* texture layer */ -#define ID_TYPE LWID_('T','Y','P','E') -#define ID_CHAN LWID_('C','H','A','N') -#define ID_NAME LWID_('N','A','M','E') -#define ID_ENAB LWID_('E','N','A','B') -#define ID_OPAC LWID_('O','P','A','C') -#define ID_FLAG LWID_('F','L','A','G') -#define ID_PROJ LWID_('P','R','O','J') -#define ID_STCK LWID_('S','T','C','K') -#define ID_TAMP LWID_('T','A','M','P') +#define ID_TYPE LWID_( 'T','Y','P','E' ) +#define ID_CHAN LWID_( 'C','H','A','N' ) +#define ID_NAME LWID_( 'N','A','M','E' ) +#define ID_ENAB LWID_( 'E','N','A','B' ) +#define ID_OPAC LWID_( 'O','P','A','C' ) +#define ID_FLAG LWID_( 'F','L','A','G' ) +#define ID_PROJ LWID_( 'P','R','O','J' ) +#define ID_STCK LWID_( 'S','T','C','K' ) +#define ID_TAMP LWID_( 'T','A','M','P' ) /* texture coordinates */ -#define ID_TMAP LWID_('T','M','A','P') -#define ID_AXIS LWID_('A','X','I','S') -#define ID_CNTR LWID_('C','N','T','R') -#define ID_SIZE LWID_('S','I','Z','E') -#define ID_ROTA LWID_('R','O','T','A') -#define ID_OREF LWID_('O','R','E','F') -#define ID_FALL LWID_('F','A','L','L') -#define ID_CSYS LWID_('C','S','Y','S') +#define ID_TMAP LWID_( 'T','M','A','P' ) +#define ID_AXIS LWID_( 'A','X','I','S' ) +#define ID_CNTR LWID_( 'C','N','T','R' ) +#define ID_SIZE LWID_( 'S','I','Z','E' ) +#define ID_ROTA LWID_( 'R','O','T','A' ) +#define ID_OREF LWID_( 'O','R','E','F' ) +#define ID_FALL LWID_( 'F','A','L','L' ) +#define ID_CSYS LWID_( 'C','S','Y','S' ) /* image map */ -#define ID_IMAP LWID_('I','M','A','P') -#define ID_IMAG LWID_('I','M','A','G') -#define ID_WRAP LWID_('W','R','A','P') -#define ID_WRPW LWID_('W','R','P','W') -#define ID_WRPH LWID_('W','R','P','H') -#define ID_VMAP LWID_('V','M','A','P') -#define ID_AAST LWID_('A','A','S','T') -#define ID_PIXB LWID_('P','I','X','B') +#define ID_IMAP LWID_( 'I','M','A','P' ) +#define ID_IMAG LWID_( 'I','M','A','G' ) +#define ID_WRAP LWID_( 'W','R','A','P' ) +#define ID_WRPW LWID_( 'W','R','P','W' ) +#define ID_WRPH LWID_( 'W','R','P','H' ) +#define ID_VMAP LWID_( 'V','M','A','P' ) +#define ID_AAST LWID_( 'A','A','S','T' ) +#define ID_PIXB LWID_( 'P','I','X','B' ) /* procedural */ -#define ID_PROC LWID_('P','R','O','C') -#define ID_COLR LWID_('C','O','L','R') -#define ID_VALU LWID_('V','A','L','U') -#define ID_FUNC LWID_('F','U','N','C') -#define ID_FTPS LWID_('F','T','P','S') -#define ID_ITPS LWID_('I','T','P','S') -#define ID_ETPS LWID_('E','T','P','S') +#define ID_PROC LWID_( 'P','R','O','C' ) +#define ID_COLR LWID_( 'C','O','L','R' ) +#define ID_VALU LWID_( 'V','A','L','U' ) +#define ID_FUNC LWID_( 'F','U','N','C' ) +#define ID_FTPS LWID_( 'F','T','P','S' ) +#define ID_ITPS LWID_( 'I','T','P','S' ) +#define ID_ETPS LWID_( 'E','T','P','S' ) /* gradient */ -#define ID_GRAD LWID_('G','R','A','D') -#define ID_GRST LWID_('G','R','S','T') -#define ID_GREN LWID_('G','R','E','N') -#define ID_PNAM LWID_('P','N','A','M') -#define ID_INAM LWID_('I','N','A','M') -#define ID_GRPT LWID_('G','R','P','T') -#define ID_FKEY LWID_('F','K','E','Y') -#define ID_IKEY LWID_('I','K','E','Y') +#define ID_GRAD LWID_( 'G','R','A','D' ) +#define ID_GRST LWID_( 'G','R','S','T' ) +#define ID_GREN LWID_( 'G','R','E','N' ) +#define ID_PNAM LWID_( 'P','N','A','M' ) +#define ID_INAM LWID_( 'I','N','A','M' ) +#define ID_GRPT LWID_( 'G','R','P','T' ) +#define ID_FKEY LWID_( 'F','K','E','Y' ) +#define ID_IKEY LWID_( 'I','K','E','Y' ) /* shader */ -#define ID_SHDR LWID_('S','H','D','R') -#define ID_DATA LWID_('D','A','T','A') +#define ID_SHDR LWID_( 'S','H','D','R' ) +#define ID_DATA LWID_( 'D','A','T','A' ) /* generic linked list */ typedef struct st_lwNode { - struct st_lwNode *next, *prev; - void *data; + struct st_lwNode *next, *prev; + void *data; } lwNode; /* plug-in reference */ typedef struct st_lwPlugin { - struct st_lwPlugin *next, *prev; - char *ord; - char *name; - int flags; - void *data; + struct st_lwPlugin *next, *prev; + char *ord; + char *name; + int flags; + void *data; } lwPlugin; /* envelopes */ typedef struct st_lwKey { - struct st_lwKey *next, *prev; - float value; - float time; - unsigned int shape; /* ID_TCB, ID_BEZ2, etc. */ - float tension; - float continuity; - float bias; - float param[ 4 ]; + struct st_lwKey *next, *prev; + float value; + float time; + unsigned int shape; /* ID_TCB, ID_BEZ2, etc. */ + float tension; + float continuity; + float bias; + float param[ 4 ]; } lwKey; typedef struct st_lwEnvelope { - struct st_lwEnvelope *next, *prev; - int index; - int type; - char *name; - lwKey *key; /* linked list of keys */ - int nkeys; - int behavior[ 2 ]; /* pre and post (extrapolation) */ - lwPlugin *cfilter; /* linked list of channel filters */ - int ncfilters; + struct st_lwEnvelope *next, *prev; + int index; + int type; + char *name; + lwKey *key; /* linked list of keys */ + int nkeys; + int behavior[ 2 ]; /* pre and post (extrapolation) */ + lwPlugin *cfilter; /* linked list of channel filters */ + int ncfilters; } lwEnvelope; #define BEH_RESET 0 @@ -213,103 +213,103 @@ typedef struct st_lwEnvelope { /* values that can be enveloped */ typedef struct st_lwEParam { - float val; - int eindex; + float val; + int eindex; } lwEParam; typedef struct st_lwVParam { - float val[ 3 ]; - int eindex; + float val[ 3 ]; + int eindex; } lwVParam; /* clips */ typedef struct st_lwClipStill { - char *name; + char *name; } lwClipStill; typedef struct st_lwClipSeq { - char *prefix; /* filename before sequence digits */ - char *suffix; /* after digits, e.g. extensions */ - int digits; - int flags; - int offset; - int start; - int end; + char *prefix; /* filename before sequence digits */ + char *suffix; /* after digits, e.g. extensions */ + int digits; + int flags; + int offset; + int start; + int end; } lwClipSeq; typedef struct st_lwClipAnim { - char *name; - char *server; /* anim loader plug-in */ - void *data; + char *name; + char *server; /* anim loader plug-in */ + void *data; } lwClipAnim; typedef struct st_lwClipXRef { - char *string; - int index; - struct st_lwClip *clip; + char *string; + int index; + struct st_lwClip *clip; } lwClipXRef; typedef struct st_lwClipCycle { - char *name; - int lo; - int hi; + char *name; + int lo; + int hi; } lwClipCycle; typedef struct st_lwClip { - struct st_lwClip *next, *prev; - int index; - unsigned int type; /* ID_STIL, ID_ISEQ, etc. */ - union { - lwClipStill still; - lwClipSeq seq; - lwClipAnim anim; - lwClipXRef xref; - lwClipCycle cycle; - } source; - float start_time; - float duration; - float frame_rate; - lwEParam contrast; - lwEParam brightness; - lwEParam saturation; - lwEParam hue; - lwEParam gamma; - int negative; - lwPlugin *ifilter; /* linked list of image filters */ - int nifilters; - lwPlugin *pfilter; /* linked list of pixel filters */ - int npfilters; + struct st_lwClip *next, *prev; + int index; + unsigned int type; /* ID_STIL, ID_ISEQ, etc. */ + union { + lwClipStill still; + lwClipSeq seq; + lwClipAnim anim; + lwClipXRef xref; + lwClipCycle cycle; + } source; + float start_time; + float duration; + float frame_rate; + lwEParam contrast; + lwEParam brightness; + lwEParam saturation; + lwEParam hue; + lwEParam gamma; + int negative; + lwPlugin *ifilter; /* linked list of image filters */ + int nifilters; + lwPlugin *pfilter; /* linked list of pixel filters */ + int npfilters; } lwClip; /* textures */ typedef struct st_lwTMap { - lwVParam size; - lwVParam center; - lwVParam rotate; - lwVParam falloff; - int fall_type; - char *ref_object; - int coord_sys; + lwVParam size; + lwVParam center; + lwVParam rotate; + lwVParam falloff; + int fall_type; + char *ref_object; + int coord_sys; } lwTMap; typedef struct st_lwImageMap { - int cindex; - int projection; - char *vmap_name; - int axis; - int wrapw_type; - int wraph_type; - lwEParam wrapw; - lwEParam wraph; - float aa_strength; - int aas_flags; - int pblend; - lwEParam stck; - lwEParam amplitude; + int cindex; + int projection; + char *vmap_name; + int axis; + int wrapw_type; + int wraph_type; + lwEParam wrapw; + lwEParam wraph; + float aa_strength; + int aas_flags; + int pblend; + lwEParam stck; + lwEParam amplitude; } lwImageMap; #define PROJ_PLANAR 0 @@ -324,214 +324,214 @@ typedef struct st_lwImageMap { #define WRAP_MIRROR 3 typedef struct st_lwProcedural { - int axis; - float value[ 3 ]; - char *name; - void *data; + int axis; + float value[ 3 ]; + char *name; + void *data; } lwProcedural; typedef struct st_lwGradKey { - struct st_lwGradKey *next, *prev; - float value; - float rgba[ 4 ]; + struct st_lwGradKey *next, *prev; + float value; + float rgba[ 4 ]; } lwGradKey; typedef struct st_lwGradient { - char *paramname; - char *itemname; - float start; - float end; - int repeat; - lwGradKey *key; /* array of gradient keys */ - short *ikey; /* array of interpolation codes */ + char *paramname; + char *itemname; + float start; + float end; + int repeat; + lwGradKey *key; /* array of gradient keys */ + short *ikey; /* array of interpolation codes */ } lwGradient; typedef struct st_lwTexture { - struct st_lwTexture *next, *prev; - char *ord; - unsigned int type; - unsigned int chan; - lwEParam opacity; - short opac_type; - short enabled; - short negative; - short axis; - union { - lwImageMap imap; - lwProcedural proc; - lwGradient grad; - } param; - lwTMap tmap; + struct st_lwTexture *next, *prev; + char *ord; + unsigned int type; + unsigned int chan; + lwEParam opacity; + short opac_type; + short enabled; + short negative; + short axis; + union { + lwImageMap imap; + lwProcedural proc; + lwGradient grad; + } param; + lwTMap tmap; } lwTexture; /* values that can be textured */ typedef struct st_lwTParam { - float val; - int eindex; - lwTexture *tex; /* linked list of texture layers */ + float val; + int eindex; + lwTexture *tex; /* linked list of texture layers */ } lwTParam; typedef struct st_lwCParam { - float rgb[ 3 ]; - int eindex; - lwTexture *tex; /* linked list of texture layers */ + float rgb[ 3 ]; + int eindex; + lwTexture *tex; /* linked list of texture layers */ } lwCParam; /* surfaces */ typedef struct st_lwGlow { - short enabled; - short type; - lwEParam intensity; - lwEParam size; + short enabled; + short type; + lwEParam intensity; + lwEParam size; } Glow; typedef struct st_lwRMap { - lwTParam val; - int options; - int cindex; - float seam_angle; + lwTParam val; + int options; + int cindex; + float seam_angle; } lwRMap; typedef struct st_lwLine { - short enabled; - unsigned short flags; - lwEParam size; + short enabled; + unsigned short flags; + lwEParam size; } lwLine; typedef struct st_lwSurface { - struct st_lwSurface *next, *prev; - char *name; - char *srcname; - lwCParam color; - lwTParam luminosity; - lwTParam diffuse; - lwTParam specularity; - lwTParam glossiness; - lwRMap reflection; - lwRMap transparency; - lwTParam eta; - lwTParam translucency; - lwTParam bump; - float smooth; - int sideflags; - float alpha; - int alpha_mode; - lwEParam color_hilite; - lwEParam color_filter; - lwEParam add_trans; - lwEParam dif_sharp; - lwEParam glow; - lwLine line; - lwPlugin *shader; /* linked list of shaders */ - int nshaders; + struct st_lwSurface *next, *prev; + char *name; + char *srcname; + lwCParam color; + lwTParam luminosity; + lwTParam diffuse; + lwTParam specularity; + lwTParam glossiness; + lwRMap reflection; + lwRMap transparency; + lwTParam eta; + lwTParam translucency; + lwTParam bump; + float smooth; + int sideflags; + float alpha; + int alpha_mode; + lwEParam color_hilite; + lwEParam color_filter; + lwEParam add_trans; + lwEParam dif_sharp; + lwEParam glow; + lwLine line; + lwPlugin *shader; /* linked list of shaders */ + int nshaders; } lwSurface; /* vertex maps */ typedef struct st_lwVMap { - struct st_lwVMap *next, *prev; - char *name; - unsigned int type; - int dim; - int nverts; - int perpoly; - int *vindex; /* array of point indexes */ - int *pindex; /* array of polygon indexes */ - float **val; + struct st_lwVMap *next, *prev; + char *name; + unsigned int type; + int dim; + int nverts; + int perpoly; + int *vindex; /* array of point indexes */ + int *pindex; /* array of polygon indexes */ + float **val; } lwVMap; typedef struct st_lwVMapPt { - lwVMap *vmap; - int index; /* vindex or pindex element */ + lwVMap *vmap; + int index; /* vindex or pindex element */ } lwVMapPt; /* points and polygons */ typedef struct st_lwPoint { - float pos[ 3 ]; - int npols; /* number of polygons sharing the point */ - int *pol; /* array of polygon indexes */ - int nvmaps; - lwVMapPt *vm; /* array of vmap references */ + float pos[ 3 ]; + int npols; /* number of polygons sharing the point */ + int *pol; /* array of polygon indexes */ + int nvmaps; + lwVMapPt *vm; /* array of vmap references */ } lwPoint; typedef struct st_lwPolVert { - int index; /* index into the point array */ - float norm[ 3 ]; - int nvmaps; - lwVMapPt *vm; /* array of vmap references */ + int index; /* index into the point array */ + float norm[ 3 ]; + int nvmaps; + lwVMapPt *vm; /* array of vmap references */ } lwPolVert; typedef struct st_lwPolygon { - lwSurface *surf; - int part; /* part index */ - int smoothgrp; /* smoothing group */ - int flags; - unsigned int type; - float norm[ 3 ]; - int nverts; - lwPolVert *v; /* array of vertex records */ + lwSurface *surf; + int part; /* part index */ + int smoothgrp; /* smoothing group */ + int flags; + unsigned int type; + float norm[ 3 ]; + int nverts; + lwPolVert *v; /* array of vertex records */ } lwPolygon; typedef struct st_lwPointList { - int count; - int offset; /* only used during reading */ - lwPoint *pt; /* array of points */ + int count; + int offset; /* only used during reading */ + lwPoint *pt; /* array of points */ } lwPointList; typedef struct st_lwPolygonList { - int count; - int offset; /* only used during reading */ - int vcount; /* total number of vertices */ - int voffset; /* only used during reading */ - lwPolygon *pol; /* array of polygons */ + int count; + int offset; /* only used during reading */ + int vcount; /* total number of vertices */ + int voffset; /* only used during reading */ + lwPolygon *pol; /* array of polygons */ } lwPolygonList; /* geometry layers */ typedef struct st_lwLayer { - struct st_lwLayer *next, *prev; - char *name; - int index; - int parent; - int flags; - float pivot[ 3 ]; - float bbox[ 6 ]; - lwPointList point; - lwPolygonList polygon; - int nvmaps; - lwVMap *vmap; /* linked list of vmaps */ + struct st_lwLayer *next, *prev; + char *name; + int index; + int parent; + int flags; + float pivot[ 3 ]; + float bbox[ 6 ]; + lwPointList point; + lwPolygonList polygon; + int nvmaps; + lwVMap *vmap; /* linked list of vmaps */ } lwLayer; /* tag strings */ typedef struct st_lwTagList { - int count; - int offset; /* only used during reading */ - char **tag; /* array of strings */ + int count; + int offset; /* only used during reading */ + char **tag; /* array of strings */ } lwTagList; /* an object */ typedef struct st_lwObject { - lwLayer *layer; /* linked list of layers */ - lwEnvelope *env; /* linked list of envelopes */ - lwClip *clip; /* linked list of clips */ - lwSurface *surf; /* linked list of surfaces */ - lwTagList taglist; - int nlayers; - int nenvs; - int nclips; - int nsurfs; + lwLayer *layer; /* linked list of layers */ + lwEnvelope *env; /* linked list of envelopes */ + lwClip *clip; /* linked list of clips */ + lwSurface *surf; /* linked list of surfaces */ + lwTagList taglist; + int nlayers; + int nenvs; + int nclips; + int nsurfs; } lwObject; @@ -547,24 +547,24 @@ int lwValidateObject( const char *filename, picoMemStream_t *fp, unsigned int *f void lwFreePoints( lwPointList *point ); void lwFreePolygons( lwPolygonList *plist ); int lwGetPoints( picoMemStream_t *fp, int cksize, lwPointList *point ); -void lwGetBoundingBox( lwPointList *point, float bbox[] ); +void lwGetBoundingBox( lwPointList * point, float bbox[] ); int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ); int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ); void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ); int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ); int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, - lwSurface **surf, int *nsurfs ); + lwSurface **surf, int *nsurfs ); void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ); void lwFreeTags( lwTagList *tlist ); int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ); int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, - lwPolygonList *plist ); + lwPolygonList *plist ); /* vmap.c */ void lwFreeVMap( lwVMap *vmap ); lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, - int perpoly ); + int perpoly ); int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ); int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ); @@ -605,17 +605,17 @@ int lwValidateObject5( const char *filename, picoMemStream_t *fp, unsigned int * /* list.c */ -void lwListFree( void *list, void ( *freeNode )( void * )); +void lwListFree( void *list, void ( *freeNode )( void * ) ); void lwListAdd( void **list, void *node ); void lwListInsert( void **vlist, void *vitem, - int ( *compare )( void *, void * )); + int ( *compare )( void *, void * ) ); /* vecmath.c */ float dot( float a[], float b[] ); void cross( float a[], float b[], float c[] ); void normalize( float v[] ); -#define vecangle( a, b ) ( float ) acos( dot( a, b )) +#define vecangle( a, b ) ( float ) acos( dot( a, b ) ) /* lwio.c */ @@ -643,7 +643,7 @@ float sgetF4( unsigned char **bp ); char *sgetS0( unsigned char **bp ); #ifndef __BIG_ENDIAN__ - void revbytes( void *bp, int elsize, int elcount ); +void revbytes( void *bp, int elsize, int elcount ); #else #define revbytes( b, s, c ) #endif diff --git a/libs/picomodel/lwo/lwob.c b/libs/picomodel/lwo/lwob.c index cb2a70ea..e0256c09 100644 --- a/libs/picomodel/lwo/lwob.c +++ b/libs/picomodel/lwo/lwob.c @@ -1,12 +1,12 @@ /* -====================================================================== -lwob.c + ====================================================================== + lwob.c -Functions for an LWOB reader. LWOB is the LightWave object format -for versions of LW prior to 6.0. + Functions for an LWOB reader. LWOB is the LightWave object format + for versions of LW prior to 6.0. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" @@ -19,722 +19,849 @@ Ernie Wright 17 Sep 00 /* IDs specific to LWOB */ -#define ID_SRFS LWID_('S','R','F','S') -#define ID_FLAG LWID_('F','L','A','G') -#define ID_VLUM LWID_('V','L','U','M') -#define ID_VDIF LWID_('V','D','I','F') -#define ID_VSPC LWID_('V','S','P','C') -#define ID_RFLT LWID_('R','F','L','T') -#define ID_BTEX LWID_('B','T','E','X') -#define ID_CTEX LWID_('C','T','E','X') -#define ID_DTEX LWID_('D','T','E','X') -#define ID_LTEX LWID_('L','T','E','X') -#define ID_RTEX LWID_('R','T','E','X') -#define ID_STEX LWID_('S','T','E','X') -#define ID_TTEX LWID_('T','T','E','X') -#define ID_TFLG LWID_('T','F','L','G') -#define ID_TSIZ LWID_('T','S','I','Z') -#define ID_TCTR LWID_('T','C','T','R') -#define ID_TFAL LWID_('T','F','A','L') -#define ID_TVEL LWID_('T','V','E','L') -#define ID_TCLR LWID_('T','C','L','R') -#define ID_TVAL LWID_('T','V','A','L') -#define ID_TAMP LWID_('T','A','M','P') -#define ID_TIMG LWID_('T','I','M','G') -#define ID_TAAS LWID_('T','A','A','S') -#define ID_TREF LWID_('T','R','E','F') -#define ID_TOPC LWID_('T','O','P','C') -#define ID_SDAT LWID_('S','D','A','T') -#define ID_TFP0 LWID_('T','F','P','0') -#define ID_TFP1 LWID_('T','F','P','1') +#define ID_SRFS LWID_( 'S','R','F','S' ) +#define ID_FLAG LWID_( 'F','L','A','G' ) +#define ID_VLUM LWID_( 'V','L','U','M' ) +#define ID_VDIF LWID_( 'V','D','I','F' ) +#define ID_VSPC LWID_( 'V','S','P','C' ) +#define ID_RFLT LWID_( 'R','F','L','T' ) +#define ID_BTEX LWID_( 'B','T','E','X' ) +#define ID_CTEX LWID_( 'C','T','E','X' ) +#define ID_DTEX LWID_( 'D','T','E','X' ) +#define ID_LTEX LWID_( 'L','T','E','X' ) +#define ID_RTEX LWID_( 'R','T','E','X' ) +#define ID_STEX LWID_( 'S','T','E','X' ) +#define ID_TTEX LWID_( 'T','T','E','X' ) +#define ID_TFLG LWID_( 'T','F','L','G' ) +#define ID_TSIZ LWID_( 'T','S','I','Z' ) +#define ID_TCTR LWID_( 'T','C','T','R' ) +#define ID_TFAL LWID_( 'T','F','A','L' ) +#define ID_TVEL LWID_( 'T','V','E','L' ) +#define ID_TCLR LWID_( 'T','C','L','R' ) +#define ID_TVAL LWID_( 'T','V','A','L' ) +#define ID_TAMP LWID_( 'T','A','M','P' ) +#define ID_TIMG LWID_( 'T','I','M','G' ) +#define ID_TAAS LWID_( 'T','A','A','S' ) +#define ID_TREF LWID_( 'T','R','E','F' ) +#define ID_TOPC LWID_( 'T','O','P','C' ) +#define ID_SDAT LWID_( 'S','D','A','T' ) +#define ID_TFP0 LWID_( 'T','F','P','0' ) +#define ID_TFP1 LWID_( 'T','F','P','1' ) /* -====================================================================== -add_clip() - -Add a clip to the clip list. Used to store the contents of an RIMG or -TIMG surface subchunk. -====================================================================== */ - -static int add_clip( char *s, lwClip **clist, int *nclips ) -{ - lwClip *clip; - char *p; - - clip = _pico_calloc( 1, sizeof( lwClip )); - if ( !clip ) return 0; - - clip->contrast.val = 1.0f; - clip->brightness.val = 1.0f; - clip->saturation.val = 1.0f; - clip->gamma.val = 1.0f; - - if ((p = strstr( s, "(sequence)" ))) { - p[ -1 ] = 0; - clip->type = ID_ISEQ; - clip->source.seq.prefix = s; - clip->source.seq.digits = 3; - } - else { - clip->type = ID_STIL; - clip->source.still.name = s; - } - - (*nclips)++; - clip->index = *nclips; - - lwListAdd( (void *) clist, clip ); - - return clip->index; + ====================================================================== + add_clip() + + Add a clip to the clip list. Used to store the contents of an RIMG or + TIMG surface subchunk. + ====================================================================== */ + +static int add_clip( char *s, lwClip **clist, int *nclips ){ + lwClip *clip; + char *p; + + clip = _pico_calloc( 1, sizeof( lwClip ) ); + if ( !clip ) { + return 0; + } + + clip->contrast.val = 1.0f; + clip->brightness.val = 1.0f; + clip->saturation.val = 1.0f; + clip->gamma.val = 1.0f; + + if ( ( p = strstr( s, "(sequence)" ) ) ) { + p[ -1 ] = 0; + clip->type = ID_ISEQ; + clip->source.seq.prefix = s; + clip->source.seq.digits = 3; + } + else { + clip->type = ID_STIL; + clip->source.still.name = s; + } + + ( *nclips )++; + clip->index = *nclips; + + lwListAdd( (void *) clist, clip ); + + return clip->index; } /* -====================================================================== -add_tvel() - -Add a triple of envelopes to simulate the old texture velocity -parameters. -====================================================================== */ - -static int add_tvel( float pos[], float vel[], lwEnvelope **elist, int *nenvs ) -{ - lwEnvelope *env; - lwKey *key0, *key1; - int i; - - for ( i = 0; i < 3; i++ ) { - env = _pico_calloc( 1, sizeof( lwEnvelope )); - key0 = _pico_calloc( 1, sizeof( lwKey )); - key1 = _pico_calloc( 1, sizeof( lwKey )); - if ( !env || !key0 || !key1 ) return 0; - - key0->next = key1; - key0->value = pos[ i ]; - key0->time = 0.0f; - key1->prev = key0; - key1->value = pos[ i ] + vel[ i ] * 30.0f; - key1->time = 1.0f; - key0->shape = key1->shape = ID_LINE; - - env->index = *nenvs + i + 1; - env->type = 0x0301 + i; - env->name = _pico_alloc( 11 ); - if ( env->name ) { - strcpy( env->name, "Position.X" ); - env->name[ 9 ] += i; - } - env->key = key0; - env->nkeys = 2; - env->behavior[ 0 ] = BEH_LINEAR; - env->behavior[ 1 ] = BEH_LINEAR; - - lwListAdd( (void *) elist, env ); - } - - *nenvs += 3; - return env->index - 2; + ====================================================================== + add_tvel() + + Add a triple of envelopes to simulate the old texture velocity + parameters. + ====================================================================== */ + +static int add_tvel( float pos[], float vel[], lwEnvelope **elist, int *nenvs ){ + lwEnvelope *env; + lwKey *key0, *key1; + int i; + + for ( i = 0; i < 3; i++ ) { + env = _pico_calloc( 1, sizeof( lwEnvelope ) ); + key0 = _pico_calloc( 1, sizeof( lwKey ) ); + key1 = _pico_calloc( 1, sizeof( lwKey ) ); + if ( !env || !key0 || !key1 ) { + return 0; + } + + key0->next = key1; + key0->value = pos[ i ]; + key0->time = 0.0f; + key1->prev = key0; + key1->value = pos[ i ] + vel[ i ] * 30.0f; + key1->time = 1.0f; + key0->shape = key1->shape = ID_LINE; + + env->index = *nenvs + i + 1; + env->type = 0x0301 + i; + env->name = _pico_alloc( 11 ); + if ( env->name ) { + strcpy( env->name, "Position.X" ); + env->name[ 9 ] += i; + } + env->key = key0; + env->nkeys = 2; + env->behavior[ 0 ] = BEH_LINEAR; + env->behavior[ 1 ] = BEH_LINEAR; + + lwListAdd( (void *) elist, env ); + } + + *nenvs += 3; + return env->index - 2; } /* -====================================================================== -get_texture() - -Create a new texture for BTEX, CTEX, etc. subchunks. -====================================================================== */ - -static lwTexture *get_texture( char *s ) -{ - lwTexture *tex; - - tex = _pico_calloc( 1, sizeof( lwTexture )); - if ( !tex ) return NULL; - - tex->tmap.size.val[ 0 ] = - tex->tmap.size.val[ 1 ] = - tex->tmap.size.val[ 2 ] = 1.0f; - tex->opacity.val = 1.0f; - tex->enabled = 1; - - if ( strstr( s, "Image Map" )) { - tex->type = ID_IMAP; - if ( strstr( s, "Planar" )) tex->param.imap.projection = 0; - else if ( strstr( s, "Cylindrical" )) tex->param.imap.projection = 1; - else if ( strstr( s, "Spherical" )) tex->param.imap.projection = 2; - else if ( strstr( s, "Cubic" )) tex->param.imap.projection = 3; - else if ( strstr( s, "Front" )) tex->param.imap.projection = 4; - tex->param.imap.aa_strength = 1.0f; - tex->param.imap.amplitude.val = 1.0f; - _pico_free( s ); - } - else { - tex->type = ID_PROC; - tex->param.proc.name = s; - } - - return tex; + ====================================================================== + get_texture() + + Create a new texture for BTEX, CTEX, etc. subchunks. + ====================================================================== */ + +static lwTexture *get_texture( char *s ){ + lwTexture *tex; + + tex = _pico_calloc( 1, sizeof( lwTexture ) ); + if ( !tex ) { + return NULL; + } + + tex->tmap.size.val[ 0 ] = + tex->tmap.size.val[ 1 ] = + tex->tmap.size.val[ 2 ] = 1.0f; + tex->opacity.val = 1.0f; + tex->enabled = 1; + + if ( strstr( s, "Image Map" ) ) { + tex->type = ID_IMAP; + if ( strstr( s, "Planar" ) ) { + tex->param.imap.projection = 0; + } + else if ( strstr( s, "Cylindrical" ) ) { + tex->param.imap.projection = 1; + } + else if ( strstr( s, "Spherical" ) ) { + tex->param.imap.projection = 2; + } + else if ( strstr( s, "Cubic" ) ) { + tex->param.imap.projection = 3; + } + else if ( strstr( s, "Front" ) ) { + tex->param.imap.projection = 4; + } + tex->param.imap.aa_strength = 1.0f; + tex->param.imap.amplitude.val = 1.0f; + _pico_free( s ); + } + else { + tex->type = ID_PROC; + tex->param.proc.name = s; + } + + return tex; } /* -====================================================================== -lwGetSurface5() - -Read an lwSurface from an LWOB file. -====================================================================== */ - -lwSurface *lwGetSurface5( picoMemStream_t *fp, int cksize, lwObject *obj ) -{ - lwSurface *surf; - lwTexture *tex = NULL; - lwPlugin *shdr = NULL; - char *s; - float v[ 3 ]; - unsigned int id, flags; - unsigned short sz; - int pos, rlen, i; - - - /* allocate the Surface structure */ - - surf = _pico_calloc( 1, sizeof( lwSurface )); - if ( !surf ) goto Fail; - - /* non-zero defaults */ - - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* name */ - - surf->name = getS0( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_COLR: - surf->color.rgb[ 0 ] = getU1( fp ) / 255.0f; - surf->color.rgb[ 1 ] = getU1( fp ) / 255.0f; - surf->color.rgb[ 2 ] = getU1( fp ) / 255.0f; - break; - - case ID_FLAG: - flags = getU2( fp ); - if ( flags & 4 ) surf->smooth = 1.56207f; - if ( flags & 8 ) surf->color_hilite.val = 1.0f; - if ( flags & 16 ) surf->color_filter.val = 1.0f; - if ( flags & 128 ) surf->dif_sharp.val = 0.5f; - if ( flags & 256 ) surf->sideflags = 3; - if ( flags & 512 ) surf->add_trans.val = 1.0f; - break; - - case ID_LUMI: - surf->luminosity.val = getI2( fp ) / 256.0f; - break; - - case ID_VLUM: - surf->luminosity.val = getF4( fp ); - break; - - case ID_DIFF: - surf->diffuse.val = getI2( fp ) / 256.0f; - break; - - case ID_VDIF: - surf->diffuse.val = getF4( fp ); - break; - - case ID_SPEC: - surf->specularity.val = getI2( fp ) / 256.0f; - break; - - case ID_VSPC: - surf->specularity.val = getF4( fp ); - break; - - case ID_GLOS: - surf->glossiness.val = ( float ) log( getU2( fp )) / 20.7944f; - break; - - case ID_SMAN: - surf->smooth = getF4( fp ); - break; - - case ID_REFL: - surf->reflection.val.val = getI2( fp ) / 256.0f; - break; - - case ID_RFLT: - surf->reflection.options = getU2( fp ); - break; - - case ID_RIMG: - s = getS0( fp ); - surf->reflection.cindex = add_clip( s, &obj->clip, &obj->nclips ); - surf->reflection.options = 3; - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4( fp ); - break; - - case ID_TRAN: - surf->transparency.val.val = getI2( fp ) / 256.0f; - break; - - case ID_RIND: - surf->eta.val = getF4( fp ); - break; - - case ID_BTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->bump.tex, tex ); - break; - - case ID_CTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->color.tex, tex ); - break; - - case ID_DTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->diffuse.tex, tex ); - break; - - case ID_LTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->luminosity.tex, tex ); - break; - - case ID_RTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->reflection.val.tex, tex ); - break; - - case ID_STEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->specularity.tex, tex ); - break; - - case ID_TTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->transparency.val.tex, tex ); - break; - - case ID_TFLG: - if(!tex) goto Fail; - flags = getU2( fp ); - - i = -1; - if ( flags & 1 ) i = 0; - if ( flags & 2 ) i = 1; - if ( flags & 4 ) i = 2; - if(i < 0) goto Fail; - tex->axis = i; - if ( tex->type == ID_IMAP ) - tex->param.imap.axis = i; - else - tex->param.proc.axis = i; - - if ( flags & 8 ) tex->tmap.coord_sys = 1; - if ( flags & 16 ) tex->negative = 1; - if ( flags & 32 ) tex->param.imap.pblend = 1; - if ( flags & 64 ) { - tex->param.imap.aa_strength = 1.0f; - tex->param.imap.aas_flags = 1; - } - break; - - case ID_TSIZ: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.size.val[ i ] = getF4( fp ); - break; - - case ID_TCTR: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.center.val[ i ] = getF4( fp ); - break; - - case ID_TFAL: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.falloff.val[ i ] = getF4( fp ); - break; - - case ID_TVEL: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - v[ i ] = getF4( fp ); - tex->tmap.center.eindex = add_tvel( tex->tmap.center.val, v, - &obj->env, &obj->nenvs ); - break; - - case ID_TCLR: - if(!tex) goto Fail; - if ( tex->type == ID_PROC ) - for ( i = 0; i < 3; i++ ) - tex->param.proc.value[ i ] = getU1( fp ) / 255.0f; - break; - - case ID_TVAL: - if(!tex) goto Fail; - tex->param.proc.value[ 0 ] = getI2( fp ) / 256.0f; - break; - - case ID_TAMP: - if(!tex) goto Fail; - if ( tex->type == ID_IMAP ) - tex->param.imap.amplitude.val = getF4( fp ); - break; - - case ID_TIMG: - if(!tex) goto Fail; - s = getS0( fp ); - tex->param.imap.cindex = add_clip( s, &obj->clip, &obj->nclips ); - break; - - case ID_TAAS: - if(!tex) goto Fail; - tex->param.imap.aa_strength = getF4( fp ); - tex->param.imap.aas_flags = 1; - break; - - case ID_TREF: - if(!tex) goto Fail; - tex->tmap.ref_object = getbytes( fp, sz ); - break; - - case ID_TOPC: - if(!tex) goto Fail; - tex->opacity.val = getF4( fp ); - break; - - case ID_TFP0: - if(!tex) goto Fail; - if ( tex->type == ID_IMAP ) - tex->param.imap.wrapw.val = getF4( fp ); - break; - - case ID_TFP1: - if(!tex) goto Fail; - if ( tex->type == ID_IMAP ) - tex->param.imap.wraph.val = getF4( fp ); - break; - - case ID_SHDR: - shdr = _pico_calloc( 1, sizeof( lwPlugin )); - if ( !shdr ) goto Fail; - shdr->name = getbytes( fp, sz ); - lwListAdd( (void *) &surf->shader, shdr ); - surf->nshaders++; - break; - - case ID_SDAT: - if(!shdr) goto Fail; - shdr->data = getbytes( fp, sz ); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the SURF chunk? */ - - if ( cksize <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) goto Fail; - } - - return surf; + ====================================================================== + lwGetSurface5() + + Read an lwSurface from an LWOB file. + ====================================================================== */ + +lwSurface *lwGetSurface5( picoMemStream_t *fp, int cksize, lwObject *obj ){ + lwSurface *surf; + lwTexture *tex = NULL; + lwPlugin *shdr = NULL; + char *s; + float v[ 3 ]; + unsigned int id, flags; + unsigned short sz; + int pos, rlen, i; + + + /* allocate the Surface structure */ + + surf = _pico_calloc( 1, sizeof( lwSurface ) ); + if ( !surf ) { + goto Fail; + } + + /* non-zero defaults */ + + surf->color.rgb[ 0 ] = 0.78431f; + surf->color.rgb[ 1 ] = 0.78431f; + surf->color.rgb[ 2 ] = 0.78431f; + surf->diffuse.val = 1.0f; + surf->glossiness.val = 0.4f; + surf->bump.val = 1.0f; + surf->eta.val = 1.0f; + surf->sideflags = 1; + + /* remember where we started */ + + set_flen( 0 ); + pos = _pico_memstream_tell( fp ); + + /* name */ + + surf->name = getS0( fp ); + + /* first subchunk header */ + + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + /* process subchunks as they're encountered */ + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_COLR: + surf->color.rgb[ 0 ] = getU1( fp ) / 255.0f; + surf->color.rgb[ 1 ] = getU1( fp ) / 255.0f; + surf->color.rgb[ 2 ] = getU1( fp ) / 255.0f; + break; + + case ID_FLAG: + flags = getU2( fp ); + if ( flags & 4 ) { + surf->smooth = 1.56207f; + } + if ( flags & 8 ) { + surf->color_hilite.val = 1.0f; + } + if ( flags & 16 ) { + surf->color_filter.val = 1.0f; + } + if ( flags & 128 ) { + surf->dif_sharp.val = 0.5f; + } + if ( flags & 256 ) { + surf->sideflags = 3; + } + if ( flags & 512 ) { + surf->add_trans.val = 1.0f; + } + break; + + case ID_LUMI: + surf->luminosity.val = getI2( fp ) / 256.0f; + break; + + case ID_VLUM: + surf->luminosity.val = getF4( fp ); + break; + + case ID_DIFF: + surf->diffuse.val = getI2( fp ) / 256.0f; + break; + + case ID_VDIF: + surf->diffuse.val = getF4( fp ); + break; + + case ID_SPEC: + surf->specularity.val = getI2( fp ) / 256.0f; + break; + + case ID_VSPC: + surf->specularity.val = getF4( fp ); + break; + + case ID_GLOS: + surf->glossiness.val = ( float ) log( getU2( fp ) ) / 20.7944f; + break; + + case ID_SMAN: + surf->smooth = getF4( fp ); + break; + + case ID_REFL: + surf->reflection.val.val = getI2( fp ) / 256.0f; + break; + + case ID_RFLT: + surf->reflection.options = getU2( fp ); + break; + + case ID_RIMG: + s = getS0( fp ); + surf->reflection.cindex = add_clip( s, &obj->clip, &obj->nclips ); + surf->reflection.options = 3; + break; + + case ID_RSAN: + surf->reflection.seam_angle = getF4( fp ); + break; + + case ID_TRAN: + surf->transparency.val.val = getI2( fp ) / 256.0f; + break; + + case ID_RIND: + surf->eta.val = getF4( fp ); + break; + + case ID_BTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->bump.tex, tex ); + break; + + case ID_CTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->color.tex, tex ); + break; + + case ID_DTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->diffuse.tex, tex ); + break; + + case ID_LTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->luminosity.tex, tex ); + break; + + case ID_RTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->reflection.val.tex, tex ); + break; + + case ID_STEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->specularity.tex, tex ); + break; + + case ID_TTEX: + s = getbytes( fp, sz ); + tex = get_texture( s ); + lwListAdd( (void *) &surf->transparency.val.tex, tex ); + break; + + case ID_TFLG: + if ( !tex ) { + goto Fail; + } + flags = getU2( fp ); + + i = -1; + if ( flags & 1 ) { + i = 0; + } + if ( flags & 2 ) { + i = 1; + } + if ( flags & 4 ) { + i = 2; + } + if ( i < 0 ) { + goto Fail; + } + tex->axis = i; + if ( tex->type == ID_IMAP ) { + tex->param.imap.axis = i; + } + else{ + tex->param.proc.axis = i; + } + + if ( flags & 8 ) { + tex->tmap.coord_sys = 1; + } + if ( flags & 16 ) { + tex->negative = 1; + } + if ( flags & 32 ) { + tex->param.imap.pblend = 1; + } + if ( flags & 64 ) { + tex->param.imap.aa_strength = 1.0f; + tex->param.imap.aas_flags = 1; + } + break; + + case ID_TSIZ: + if ( !tex ) { + goto Fail; + } + for ( i = 0; i < 3; i++ ) + tex->tmap.size.val[ i ] = getF4( fp ); + break; + + case ID_TCTR: + if ( !tex ) { + goto Fail; + } + for ( i = 0; i < 3; i++ ) + tex->tmap.center.val[ i ] = getF4( fp ); + break; + + case ID_TFAL: + if ( !tex ) { + goto Fail; + } + for ( i = 0; i < 3; i++ ) + tex->tmap.falloff.val[ i ] = getF4( fp ); + break; + + case ID_TVEL: + if ( !tex ) { + goto Fail; + } + for ( i = 0; i < 3; i++ ) + v[ i ] = getF4( fp ); + tex->tmap.center.eindex = add_tvel( tex->tmap.center.val, v, + &obj->env, &obj->nenvs ); + break; + + case ID_TCLR: + if ( !tex ) { + goto Fail; + } + if ( tex->type == ID_PROC ) { + for ( i = 0; i < 3; i++ ) + tex->param.proc.value[ i ] = getU1( fp ) / 255.0f; + } + break; + + case ID_TVAL: + if ( !tex ) { + goto Fail; + } + tex->param.proc.value[ 0 ] = getI2( fp ) / 256.0f; + break; + + case ID_TAMP: + if ( !tex ) { + goto Fail; + } + if ( tex->type == ID_IMAP ) { + tex->param.imap.amplitude.val = getF4( fp ); + } + break; + + case ID_TIMG: + if ( !tex ) { + goto Fail; + } + s = getS0( fp ); + tex->param.imap.cindex = add_clip( s, &obj->clip, &obj->nclips ); + break; + + case ID_TAAS: + if ( !tex ) { + goto Fail; + } + tex->param.imap.aa_strength = getF4( fp ); + tex->param.imap.aas_flags = 1; + break; + + case ID_TREF: + if ( !tex ) { + goto Fail; + } + tex->tmap.ref_object = getbytes( fp, sz ); + break; + + case ID_TOPC: + if ( !tex ) { + goto Fail; + } + tex->opacity.val = getF4( fp ); + break; + + case ID_TFP0: + if ( !tex ) { + goto Fail; + } + if ( tex->type == ID_IMAP ) { + tex->param.imap.wrapw.val = getF4( fp ); + } + break; + + case ID_TFP1: + if ( !tex ) { + goto Fail; + } + if ( tex->type == ID_IMAP ) { + tex->param.imap.wraph.val = getF4( fp ); + } + break; + + case ID_SHDR: + shdr = _pico_calloc( 1, sizeof( lwPlugin ) ); + if ( !shdr ) { + goto Fail; + } + shdr->name = getbytes( fp, sz ); + lwListAdd( (void *) &surf->shader, shdr ); + surf->nshaders++; + break; + + case ID_SDAT: + if ( !shdr ) { + goto Fail; + } + shdr->data = getbytes( fp, sz ); + break; + + default: + break; + } + + /* error while reading current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the SURF chunk? */ + + if ( cksize <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + goto Fail; + } + } + + return surf; Fail: - if ( surf ) lwFreeSurface( surf ); - return NULL; + if ( surf ) { + lwFreeSurface( surf ); + } + return NULL; } /* -====================================================================== -lwGetPolygons5() - -Read polygon records from a POLS chunk in an LWOB file. The polygons -are added to the array in the lwPolygonList. -====================================================================== */ - -int lwGetPolygons5( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ) -{ - lwPolygon *pp; - lwPolVert *pv; - unsigned char *buf, *bp; - int i, j, nv, nverts, npols; - - - if ( cksize == 0 ) return 1; - - /* read the whole chunk */ - - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) goto Fail; - - /* count the polygons and vertices */ - - nverts = 0; - npols = 0; - bp = buf; - - while ( bp < buf + cksize ) { - nv = sgetU2( &bp ); - nverts += nv; - npols++; - bp += 2 * nv; - i = sgetI2( &bp ); - if ( i < 0 ) bp += 2; /* detail polygons */ - } - - if ( !lwAllocPolygons( plist, npols, nverts )) - goto Fail; - - /* fill in the new polygons */ - - bp = buf; - pp = plist->pol + plist->offset; - pv = plist->pol[ 0 ].v + plist->voffset; - - for ( i = 0; i < npols; i++ ) { - nv = sgetU2( &bp ); - - pp->nverts = nv; - pp->type = ID_FACE; - if ( !pp->v ) pp->v = pv; - for ( j = 0; j < nv; j++ ) - pv[ j ].index = sgetU2( &bp ) + ptoffset; - j = sgetI2( &bp ); - if ( j < 0 ) { - j = -j; - bp += 2; - } - j -= 1; - pp->surf = ( lwSurface * ) (size_t) j; - - pp++; - pv += nv; - } - - _pico_free( buf ); - return 1; + ====================================================================== + lwGetPolygons5() + + Read polygon records from a POLS chunk in an LWOB file. The polygons + are added to the array in the lwPolygonList. + ====================================================================== */ + +int lwGetPolygons5( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ){ + lwPolygon *pp; + lwPolVert *pv; + unsigned char *buf, *bp; + int i, j, nv, nverts, npols; + + + if ( cksize == 0 ) { + return 1; + } + + /* read the whole chunk */ + + set_flen( 0 ); + buf = getbytes( fp, cksize ); + if ( !buf ) { + goto Fail; + } + + /* count the polygons and vertices */ + + nverts = 0; + npols = 0; + bp = buf; + + while ( bp < buf + cksize ) { + nv = sgetU2( &bp ); + nverts += nv; + npols++; + bp += 2 * nv; + i = sgetI2( &bp ); + if ( i < 0 ) { + bp += 2; /* detail polygons */ + } + } + + if ( !lwAllocPolygons( plist, npols, nverts ) ) { + goto Fail; + } + + /* fill in the new polygons */ + + bp = buf; + pp = plist->pol + plist->offset; + pv = plist->pol[ 0 ].v + plist->voffset; + + for ( i = 0; i < npols; i++ ) { + nv = sgetU2( &bp ); + + pp->nverts = nv; + pp->type = ID_FACE; + if ( !pp->v ) { + pp->v = pv; + } + for ( j = 0; j < nv; j++ ) + pv[ j ].index = sgetU2( &bp ) + ptoffset; + j = sgetI2( &bp ); + if ( j < 0 ) { + j = -j; + bp += 2; + } + j -= 1; + pp->surf = ( lwSurface * ) (size_t) j; + + pp++; + pv += nv; + } + + _pico_free( buf ); + return 1; Fail: - if ( buf ) _pico_free( buf ); - lwFreePolygons( plist ); - return 0; + if ( buf ) { + _pico_free( buf ); + } + lwFreePolygons( plist ); + return 0; } /* -====================================================================== -getLWObject5() + ====================================================================== + getLWObject5() -Returns the contents of an LWOB, given its filename, or NULL if the -file couldn't be loaded. On failure, failID and failpos can be used -to diagnose the cause. + Returns the contents of an LWOB, given its filename, or NULL if the + file couldn't be loaded. On failure, failID and failpos can be used + to diagnose the cause. -1. If the file isn't an LWOB, failpos will contain 12 and failID will + 1. If the file isn't an LWOB, failpos will contain 12 and failID will be unchanged. -2. If an error occurs while reading an LWOB, failID will contain the + 2. If an error occurs while reading an LWOB, failID will contain the most recently read IFF chunk ID, and failpos will contain the value returned by _pico_memstream_tell() at the time of the failure. -3. If the file couldn't be opened, or an error occurs while reading + 3. If the file couldn't be opened, or an error occurs while reading the first 12 bytes, both failID and failpos will be unchanged. -If you don't need this information, failID and failpos can be NULL. -====================================================================== */ - -lwObject *lwGetObject5( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) -{ - lwObject *object; - lwLayer *layer; - lwNode *node; - unsigned int id, formsize, type, cksize; - - - /* open the file */ - - if ( !fp ) return NULL; - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return NULL; - } - - /* LWOB? */ - - if ( id != ID_FORM || type != ID_LWOB ) { - if ( failpos ) *failpos = 12; - return NULL; - } - - /* allocate an object and a default layer */ - - object = _pico_calloc( 1, sizeof( lwObject )); - if ( !object ) goto Fail; - - layer = _pico_calloc( 1, sizeof( lwLayer )); - if ( !layer ) goto Fail; - object->layer = layer; - object->nlayers = 1; - - /* get the first chunk header */ - - id = getU4( fp ); - cksize = getU4( fp ); - if ( 0 > get_flen() ) goto Fail; - - /* process chunks as they're encountered */ - - while ( 1 ) { - cksize += cksize & 1; - - switch ( id ) - { - case ID_PNTS: - if ( !lwGetPoints( fp, cksize, &layer->point )) - goto Fail; - break; - - case ID_POLS: - if ( !lwGetPolygons5( fp, cksize, &layer->polygon, - layer->point.offset )) - goto Fail; - break; - - case ID_SRFS: - if ( !lwGetTags( fp, cksize, &object->taglist )) - goto Fail; - break; - - case ID_SURF: - node = ( lwNode * ) lwGetSurface5( fp, cksize, object ); - if ( !node ) goto Fail; - lwListAdd( (void *) &object->surf, node ); - object->nsurfs++; - break; - - default: - _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); - break; - } - - /* end of the file? */ - - if ( formsize <= (unsigned int) (_pico_memstream_tell( fp ) - 8) ) break; - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - cksize = getU4( fp ); - if ( 8 != get_flen() ) goto Fail; - } - - lwGetBoundingBox( &layer->point, layer->bbox ); - lwGetPolyNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointPolygons( &layer->point, &layer->polygon )) goto Fail; - if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, - &object->surf, &object->nsurfs )) goto Fail; - lwGetVertNormals( &layer->point, &layer->polygon ); - - return object; + If you don't need this information, failID and failpos can be NULL. + ====================================================================== */ + +lwObject *lwGetObject5( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ + lwObject *object; + lwLayer *layer; + lwNode *node; + unsigned int id, formsize, type, cksize; + + + /* open the file */ + + if ( !fp ) { + return NULL; + } + + /* read the first 12 bytes */ + + set_flen( 0 ); + id = getU4( fp ); + formsize = getU4( fp ); + type = getU4( fp ); + if ( 12 != get_flen() ) { + return NULL; + } + + /* LWOB? */ + + if ( id != ID_FORM || type != ID_LWOB ) { + if ( failpos ) { + *failpos = 12; + } + return NULL; + } + + /* allocate an object and a default layer */ + + object = _pico_calloc( 1, sizeof( lwObject ) ); + if ( !object ) { + goto Fail; + } + + layer = _pico_calloc( 1, sizeof( lwLayer ) ); + if ( !layer ) { + goto Fail; + } + object->layer = layer; + object->nlayers = 1; + + /* get the first chunk header */ + + id = getU4( fp ); + cksize = getU4( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + /* process chunks as they're encountered */ + + while ( 1 ) { + cksize += cksize & 1; + + switch ( id ) + { + case ID_PNTS: + if ( !lwGetPoints( fp, cksize, &layer->point ) ) { + goto Fail; + } + break; + + case ID_POLS: + if ( !lwGetPolygons5( fp, cksize, &layer->polygon, + layer->point.offset ) ) { + goto Fail; + } + break; + + case ID_SRFS: + if ( !lwGetTags( fp, cksize, &object->taglist ) ) { + goto Fail; + } + break; + + case ID_SURF: + node = ( lwNode * ) lwGetSurface5( fp, cksize, object ); + if ( !node ) { + goto Fail; + } + lwListAdd( (void *) &object->surf, node ); + object->nsurfs++; + break; + + default: + _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); + break; + } + + /* end of the file? */ + + if ( formsize <= (unsigned int) ( _pico_memstream_tell( fp ) - 8 ) ) { + break; + } + + /* get the next chunk header */ + + set_flen( 0 ); + id = getU4( fp ); + cksize = getU4( fp ); + if ( 8 != get_flen() ) { + goto Fail; + } + } + + lwGetBoundingBox( &layer->point, layer->bbox ); + lwGetPolyNormals( &layer->point, &layer->polygon ); + if ( !lwGetPointPolygons( &layer->point, &layer->polygon ) ) { + goto Fail; + } + if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, + &object->surf, &object->nsurfs ) ) { + goto Fail; + } + lwGetVertNormals( &layer->point, &layer->polygon ); + + return object; Fail: - if ( failID ) *failID = id; - if ( fp ) { - if ( failpos ) *failpos = _pico_memstream_tell( fp ); - } - lwFreeObject( object ); - return NULL; + if ( failID ) { + *failID = id; + } + if ( fp ) { + if ( failpos ) { + *failpos = _pico_memstream_tell( fp ); + } + } + lwFreeObject( object ); + return NULL; } -int lwValidateObject5( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) -{ - unsigned int id, type; +int lwValidateObject5( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ + unsigned int id, type; - /* open the file */ + /* open the file */ - if ( !fp ) return PICO_PMV_ERROR_MEMORY; + if ( !fp ) { + return PICO_PMV_ERROR_MEMORY; + } - /* read the first 12 bytes */ + /* read the first 12 bytes */ - set_flen( 0 ); - id = getU4( fp ); - /* formsize = */ getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return PICO_PMV_ERROR_SIZE; - } + set_flen( 0 ); + id = getU4( fp ); + /* formsize = */ getU4( fp ); + type = getU4( fp ); + if ( 12 != get_flen() ) { + return PICO_PMV_ERROR_SIZE; + } - /* LWOB? */ + /* LWOB? */ - if ( id != ID_FORM || type != ID_LWOB ) { - if ( failpos ) *failpos = 12; - return PICO_PMV_ERROR_IDENT; - } + if ( id != ID_FORM || type != ID_LWOB ) { + if ( failpos ) { + *failpos = 12; + } + return PICO_PMV_ERROR_IDENT; + } - return PICO_PMV_OK; + return PICO_PMV_OK; } diff --git a/libs/picomodel/lwo/pntspols.c b/libs/picomodel/lwo/pntspols.c index 31475819..fc2f642e 100644 --- a/libs/picomodel/lwo/pntspols.c +++ b/libs/picomodel/lwo/pntspols.c @@ -1,537 +1,588 @@ /* -====================================================================== -pntspols.c + ====================================================================== + pntspols.c -Point and polygon functions for an LWO2 reader. + Point and polygon functions for an LWO2 reader. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwFreePoints() - -Free the memory used by an lwPointList. -====================================================================== */ - -void lwFreePoints( lwPointList *point ) -{ - int i; - - if ( point ) { - if ( point->pt ) { - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].pol ) _pico_free( point->pt[ i ].pol ); - if ( point->pt[ i ].vm ) _pico_free( point->pt[ i ].vm ); - } - _pico_free( point->pt ); - } - memset( point, 0, sizeof( lwPointList )); - } + ====================================================================== + lwFreePoints() + + Free the memory used by an lwPointList. + ====================================================================== */ + +void lwFreePoints( lwPointList *point ){ + int i; + + if ( point ) { + if ( point->pt ) { + for ( i = 0; i < point->count; i++ ) { + if ( point->pt[ i ].pol ) { + _pico_free( point->pt[ i ].pol ); + } + if ( point->pt[ i ].vm ) { + _pico_free( point->pt[ i ].vm ); + } + } + _pico_free( point->pt ); + } + memset( point, 0, sizeof( lwPointList ) ); + } } /* -====================================================================== -lwFreePolygons() - -Free the memory used by an lwPolygonList. -====================================================================== */ - -void lwFreePolygons( lwPolygonList *plist ) -{ - int i, j; - - if ( plist ) { - if ( plist->pol ) { - for ( i = 0; i < plist->count; i++ ) { - if ( plist->pol[ i ].v ) { - for ( j = 0; j < plist->pol[ i ].nverts; j++ ) - if ( plist->pol[ i ].v[ j ].vm ) - _pico_free( plist->pol[ i ].v[ j ].vm ); - } - } - if ( plist->pol[ 0 ].v ) - _pico_free( plist->pol[ 0 ].v ); - _pico_free( plist->pol ); - } - memset( plist, 0, sizeof( lwPolygonList )); - } + ====================================================================== + lwFreePolygons() + + Free the memory used by an lwPolygonList. + ====================================================================== */ + +void lwFreePolygons( lwPolygonList *plist ){ + int i, j; + + if ( plist ) { + if ( plist->pol ) { + for ( i = 0; i < plist->count; i++ ) { + if ( plist->pol[ i ].v ) { + for ( j = 0; j < plist->pol[ i ].nverts; j++ ) + if ( plist->pol[ i ].v[ j ].vm ) { + _pico_free( plist->pol[ i ].v[ j ].vm ); + } + } + } + if ( plist->pol[ 0 ].v ) { + _pico_free( plist->pol[ 0 ].v ); + } + _pico_free( plist->pol ); + } + memset( plist, 0, sizeof( lwPolygonList ) ); + } } /* -====================================================================== -lwGetPoints() + ====================================================================== + lwGetPoints() -Read point records from a PNTS chunk in an LWO2 file. The points are -added to the array in the lwPointList. -====================================================================== */ + Read point records from a PNTS chunk in an LWO2 file. The points are + added to the array in the lwPointList. + ====================================================================== */ -int lwGetPoints( picoMemStream_t *fp, int cksize, lwPointList *point ) -{ - float *f; - int np, i, j; +int lwGetPoints( picoMemStream_t *fp, int cksize, lwPointList *point ){ + float *f; + int np, i, j; - if ( cksize == 1 ) return 1; + if ( cksize == 1 ) { + return 1; + } - /* extend the point array to hold the new points */ + /* extend the point array to hold the new points */ - np = cksize / 12; - point->offset = point->count; - point->count += np; - if ( !_pico_realloc( (void *) &point->pt, (point->count - np) * sizeof( lwPoint ), point->count * sizeof( lwPoint )) ) - return 0; - memset( &point->pt[ point->offset ], 0, np * sizeof( lwPoint )); + np = cksize / 12; + point->offset = point->count; + point->count += np; + if ( !_pico_realloc( (void *) &point->pt, ( point->count - np ) * sizeof( lwPoint ), point->count * sizeof( lwPoint ) ) ) { + return 0; + } + memset( &point->pt[ point->offset ], 0, np * sizeof( lwPoint ) ); - /* read the whole chunk */ + /* read the whole chunk */ - f = ( float * ) getbytes( fp, cksize ); - if ( !f ) return 0; - revbytes( f, 4, np * 3 ); + f = ( float * ) getbytes( fp, cksize ); + if ( !f ) { + return 0; + } + revbytes( f, 4, np * 3 ); - /* assign position values */ + /* assign position values */ - for ( i = 0, j = 0; i < np; i++, j += 3 ) { - point->pt[ i ].pos[ 0 ] = f[ j ]; - point->pt[ i ].pos[ 1 ] = f[ j + 1 ]; - point->pt[ i ].pos[ 2 ] = f[ j + 2 ]; - } + for ( i = 0, j = 0; i < np; i++, j += 3 ) { + point->pt[ i ].pos[ 0 ] = f[ j ]; + point->pt[ i ].pos[ 1 ] = f[ j + 1 ]; + point->pt[ i ].pos[ 2 ] = f[ j + 2 ]; + } - _pico_free( f ); - return 1; + _pico_free( f ); + return 1; } /* -====================================================================== -lwGetBoundingBox() - -Calculate the bounding box for a point list, but only if the bounding -box hasn't already been initialized. -====================================================================== */ - -void lwGetBoundingBox( lwPointList *point, float bbox[] ) -{ - int i, j; - - if ( point->count == 0 ) return; - - for ( i = 0; i < 6; i++ ) - if ( bbox[ i ] != 0.0f ) return; - - bbox[ 0 ] = bbox[ 1 ] = bbox[ 2 ] = 1e20f; - bbox[ 3 ] = bbox[ 4 ] = bbox[ 5 ] = -1e20f; - for ( i = 0; i < point->count; i++ ) { - for ( j = 0; j < 3; j++ ) { - if ( bbox[ j ] > point->pt[ i ].pos[ j ] ) - bbox[ j ] = point->pt[ i ].pos[ j ]; - if ( bbox[ j + 3 ] < point->pt[ i ].pos[ j ] ) - bbox[ j + 3 ] = point->pt[ i ].pos[ j ]; - } - } + ====================================================================== + lwGetBoundingBox() + + Calculate the bounding box for a point list, but only if the bounding + box hasn't already been initialized. + ====================================================================== */ + +void lwGetBoundingBox( lwPointList *point, float bbox[] ){ + int i, j; + + if ( point->count == 0 ) { + return; + } + + for ( i = 0; i < 6; i++ ) + if ( bbox[ i ] != 0.0f ) { + return; + } + + bbox[ 0 ] = bbox[ 1 ] = bbox[ 2 ] = 1e20f; + bbox[ 3 ] = bbox[ 4 ] = bbox[ 5 ] = -1e20f; + for ( i = 0; i < point->count; i++ ) { + for ( j = 0; j < 3; j++ ) { + if ( bbox[ j ] > point->pt[ i ].pos[ j ] ) { + bbox[ j ] = point->pt[ i ].pos[ j ]; + } + if ( bbox[ j + 3 ] < point->pt[ i ].pos[ j ] ) { + bbox[ j + 3 ] = point->pt[ i ].pos[ j ]; + } + } + } } /* -====================================================================== -lwAllocPolygons() + ====================================================================== + lwAllocPolygons() -Allocate or extend the polygon arrays to hold new records. -====================================================================== */ + Allocate or extend the polygon arrays to hold new records. + ====================================================================== */ -int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ) -{ - int i; +int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ){ + int i; - plist->offset = plist->count; - plist->count += npols; - if ( !_pico_realloc( (void *) &plist->pol, (plist->count - npols) * sizeof( lwPolygon ), plist->count * sizeof( lwPolygon )) ) - return 0; - memset( plist->pol + plist->offset, 0, npols * sizeof( lwPolygon )); + plist->offset = plist->count; + plist->count += npols; + if ( !_pico_realloc( (void *) &plist->pol, ( plist->count - npols ) * sizeof( lwPolygon ), plist->count * sizeof( lwPolygon ) ) ) { + return 0; + } + memset( plist->pol + plist->offset, 0, npols * sizeof( lwPolygon ) ); - plist->voffset = plist->vcount; - plist->vcount += nverts; - if ( !_pico_realloc( (void *) &plist->pol[ 0 ].v, (plist->vcount - nverts) * sizeof( lwPolVert ), plist->vcount * sizeof( lwPolVert )) ) - return 0; - memset( plist->pol[ 0 ].v + plist->voffset, 0, nverts * sizeof( lwPolVert )); + plist->voffset = plist->vcount; + plist->vcount += nverts; + if ( !_pico_realloc( (void *) &plist->pol[ 0 ].v, ( plist->vcount - nverts ) * sizeof( lwPolVert ), plist->vcount * sizeof( lwPolVert ) ) ) { + return 0; + } + memset( plist->pol[ 0 ].v + plist->voffset, 0, nverts * sizeof( lwPolVert ) ); - /* fix up the old vertex pointers */ + /* fix up the old vertex pointers */ - for ( i = 1; i < plist->offset; i++ ) - plist->pol[ i ].v = plist->pol[ i - 1 ].v + plist->pol[ i - 1 ].nverts; + for ( i = 1; i < plist->offset; i++ ) + plist->pol[ i ].v = plist->pol[ i - 1 ].v + plist->pol[ i - 1 ].nverts; - return 1; + return 1; } /* -====================================================================== -lwGetPolygons() - -Read polygon records from a POLS chunk in an LWO2 file. The polygons -are added to the array in the lwPolygonList. -====================================================================== */ - -int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ) -{ - lwPolygon *pp; - lwPolVert *pv; - unsigned char *buf, *bp; - int i, j, flags, nv, nverts, npols; - unsigned int type; - - - if ( cksize == 0 ) return 1; - - /* read the whole chunk */ - - set_flen( 0 ); - type = getU4( fp ); - buf = getbytes( fp, cksize - 4 ); - if ( cksize != get_flen() ) goto Fail; - - /* count the polygons and vertices */ - - nverts = 0; - npols = 0; - bp = buf; - - while ( bp < buf + cksize - 4 ) { - nv = sgetU2( &bp ); - nv &= 0x03FF; - nverts += nv; - npols++; - for ( i = 0; i < nv; i++ ) - j = sgetVX( &bp ); - } - - if ( !lwAllocPolygons( plist, npols, nverts )) - goto Fail; - - /* fill in the new polygons */ - - bp = buf; - pp = plist->pol + plist->offset; - pv = plist->pol[ 0 ].v + plist->voffset; - - for ( i = 0; i < npols; i++ ) { - nv = sgetU2( &bp ); - flags = nv & 0xFC00; - nv &= 0x03FF; - - pp->nverts = nv; - pp->flags = flags; - pp->type = type; - if ( !pp->v ) pp->v = pv; - for ( j = 0; j < nv; j++ ) - pp->v[ j ].index = sgetVX( &bp ) + ptoffset; - - pp++; - pv += nv; - } - - _pico_free( buf ); - return 1; + ====================================================================== + lwGetPolygons() + + Read polygon records from a POLS chunk in an LWO2 file. The polygons + are added to the array in the lwPolygonList. + ====================================================================== */ + +int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ){ + lwPolygon *pp; + lwPolVert *pv; + unsigned char *buf, *bp; + int i, j, flags, nv, nverts, npols; + unsigned int type; + + + if ( cksize == 0 ) { + return 1; + } + + /* read the whole chunk */ + + set_flen( 0 ); + type = getU4( fp ); + buf = getbytes( fp, cksize - 4 ); + if ( cksize != get_flen() ) { + goto Fail; + } + + /* count the polygons and vertices */ + + nverts = 0; + npols = 0; + bp = buf; + + while ( bp < buf + cksize - 4 ) { + nv = sgetU2( &bp ); + nv &= 0x03FF; + nverts += nv; + npols++; + for ( i = 0; i < nv; i++ ) + j = sgetVX( &bp ); + } + + if ( !lwAllocPolygons( plist, npols, nverts ) ) { + goto Fail; + } + + /* fill in the new polygons */ + + bp = buf; + pp = plist->pol + plist->offset; + pv = plist->pol[ 0 ].v + plist->voffset; + + for ( i = 0; i < npols; i++ ) { + nv = sgetU2( &bp ); + flags = nv & 0xFC00; + nv &= 0x03FF; + + pp->nverts = nv; + pp->flags = flags; + pp->type = type; + if ( !pp->v ) { + pp->v = pv; + } + for ( j = 0; j < nv; j++ ) + pp->v[ j ].index = sgetVX( &bp ) + ptoffset; + + pp++; + pv += nv; + } + + _pico_free( buf ); + return 1; Fail: - if ( buf ) _pico_free( buf ); - lwFreePolygons( plist ); - return 0; + if ( buf ) { + _pico_free( buf ); + } + lwFreePolygons( plist ); + return 0; } /* -====================================================================== -lwGetPolyNormals() - -Calculate the polygon normals. By convention, LW's polygon normals -are found as the cross product of the first and last edges. It's -undefined for one- and two-point polygons. -====================================================================== */ - -void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ) -{ - int i, j; - float p1[ 3 ], p2[ 3 ], pn[ 3 ], v1[ 3 ], v2[ 3 ]; - - for ( i = 0; i < polygon->count; i++ ) { - if ( polygon->pol[ i ].nverts < 3 ) continue; - for ( j = 0; j < 3; j++ ) { - p1[ j ] = point->pt[ polygon->pol[ i ].v[ 0 ].index ].pos[ j ]; - p2[ j ] = point->pt[ polygon->pol[ i ].v[ 1 ].index ].pos[ j ]; - pn[ j ] = point->pt[ polygon->pol[ i ].v[ - polygon->pol[ i ].nverts - 1 ].index ].pos[ j ]; - } - - for ( j = 0; j < 3; j++ ) { - v1[ j ] = p2[ j ] - p1[ j ]; - v2[ j ] = pn[ j ] - p1[ j ]; - } - - cross( v1, v2, polygon->pol[ i ].norm ); - normalize( polygon->pol[ i ].norm ); - } + ====================================================================== + lwGetPolyNormals() + + Calculate the polygon normals. By convention, LW's polygon normals + are found as the cross product of the first and last edges. It's + undefined for one- and two-point polygons. + ====================================================================== */ + +void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ){ + int i, j; + float p1[ 3 ], p2[ 3 ], pn[ 3 ], v1[ 3 ], v2[ 3 ]; + + for ( i = 0; i < polygon->count; i++ ) { + if ( polygon->pol[ i ].nverts < 3 ) { + continue; + } + for ( j = 0; j < 3; j++ ) { + p1[ j ] = point->pt[ polygon->pol[ i ].v[ 0 ].index ].pos[ j ]; + p2[ j ] = point->pt[ polygon->pol[ i ].v[ 1 ].index ].pos[ j ]; + pn[ j ] = point->pt[ polygon->pol[ i ].v[ + polygon->pol[ i ].nverts - 1 ].index ].pos[ j ]; + } + + for ( j = 0; j < 3; j++ ) { + v1[ j ] = p2[ j ] - p1[ j ]; + v2[ j ] = pn[ j ] - p1[ j ]; + } + + cross( v1, v2, polygon->pol[ i ].norm ); + normalize( polygon->pol[ i ].norm ); + } } /* -====================================================================== -lwGetPointPolygons() - -For each point, fill in the indexes of the polygons that share the -point. Returns 0 if any of the memory allocations fail, otherwise -returns 1. -====================================================================== */ - -int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ) -{ - int i, j, k; - - /* count the number of polygons per point */ - - for ( i = 0; i < polygon->count; i++ ) - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) - ++point->pt[ polygon->pol[ i ].v[ j ].index ].npols; - - /* alloc per-point polygon arrays */ - - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].npols == 0 ) continue; - point->pt[ i ].pol = _pico_calloc( point->pt[ i ].npols, sizeof( int )); - if ( !point->pt[ i ].pol ) return 0; - point->pt[ i ].npols = 0; - } - - /* fill in polygon array for each point */ - - for ( i = 0; i < polygon->count; i++ ) { - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { - k = polygon->pol[ i ].v[ j ].index; - point->pt[ k ].pol[ point->pt[ k ].npols ] = i; - ++point->pt[ k ].npols; - } - } - - return 1; + ====================================================================== + lwGetPointPolygons() + + For each point, fill in the indexes of the polygons that share the + point. Returns 0 if any of the memory allocations fail, otherwise + returns 1. + ====================================================================== */ + +int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ){ + int i, j, k; + + /* count the number of polygons per point */ + + for ( i = 0; i < polygon->count; i++ ) + for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) + ++point->pt[ polygon->pol[ i ].v[ j ].index ].npols; + + /* alloc per-point polygon arrays */ + + for ( i = 0; i < point->count; i++ ) { + if ( point->pt[ i ].npols == 0 ) { + continue; + } + point->pt[ i ].pol = _pico_calloc( point->pt[ i ].npols, sizeof( int ) ); + if ( !point->pt[ i ].pol ) { + return 0; + } + point->pt[ i ].npols = 0; + } + + /* fill in polygon array for each point */ + + for ( i = 0; i < polygon->count; i++ ) { + for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { + k = polygon->pol[ i ].v[ j ].index; + point->pt[ k ].pol[ point->pt[ k ].npols ] = i; + ++point->pt[ k ].npols; + } + } + + return 1; } /* -====================================================================== -lwResolvePolySurfaces() + ====================================================================== + lwResolvePolySurfaces() -Convert tag indexes into actual lwSurface pointers. If any polygons -point to tags for which no corresponding surface can be found, a -default surface is created. -====================================================================== */ + Convert tag indexes into actual lwSurface pointers. If any polygons + point to tags for which no corresponding surface can be found, a + default surface is created. + ====================================================================== */ int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, - lwSurface **surf, int *nsurfs ) -{ - lwSurface **s, *st; - int i, index; - - if ( tlist->count == 0 ) return 1; - - s = _pico_calloc( tlist->count, sizeof( lwSurface * )); - if ( !s ) return 0; - - for ( i = 0; i < tlist->count; i++ ) { - st = *surf; - while ( st ) { - if ( !strcmp( st->name, tlist->tag[ i ] )) { - s[ i ] = st; - break; - } - st = st->next; - } - } - - for ( i = 0; i < polygon->count; i++ ) { - index = ( size_t ) polygon->pol[ i ].surf; - if ( index < 0 || index > tlist->count ) return 0; - if ( !s[ index ] ) { - s[ index ] = lwDefaultSurface(); - if ( !s[ index ] ) return 0; - s[ index ]->name = _pico_alloc( strlen( tlist->tag[ index ] ) + 1 ); - if ( !s[ index ]->name ) return 0; - strcpy( s[ index ]->name, tlist->tag[ index ] ); - lwListAdd( (void *) surf, s[ index ] ); - *nsurfs = *nsurfs + 1; - } - polygon->pol[ i ].surf = s[ index ]; - } - - _pico_free( s ); - return 1; + lwSurface **surf, int *nsurfs ){ + lwSurface **s, *st; + int i, index; + + if ( tlist->count == 0 ) { + return 1; + } + + s = _pico_calloc( tlist->count, sizeof( lwSurface * ) ); + if ( !s ) { + return 0; + } + + for ( i = 0; i < tlist->count; i++ ) { + st = *surf; + while ( st ) { + if ( !strcmp( st->name, tlist->tag[ i ] ) ) { + s[ i ] = st; + break; + } + st = st->next; + } + } + + for ( i = 0; i < polygon->count; i++ ) { + index = ( size_t ) polygon->pol[ i ].surf; + if ( index < 0 || index > tlist->count ) { + return 0; + } + if ( !s[ index ] ) { + s[ index ] = lwDefaultSurface(); + if ( !s[ index ] ) { + return 0; + } + s[ index ]->name = _pico_alloc( strlen( tlist->tag[ index ] ) + 1 ); + if ( !s[ index ]->name ) { + return 0; + } + strcpy( s[ index ]->name, tlist->tag[ index ] ); + lwListAdd( (void *) surf, s[ index ] ); + *nsurfs = *nsurfs + 1; + } + polygon->pol[ i ].surf = s[ index ]; + } + + _pico_free( s ); + return 1; } /* -====================================================================== -lwGetVertNormals() - -Calculate the vertex normals. For each polygon vertex, sum the -normals of the polygons that share the point. If the normals of the -current and adjacent polygons form an angle greater than the max -smoothing angle for the current polygon's surface, the normal of the -adjacent polygon is excluded from the sum. It's also excluded if the -polygons aren't in the same smoothing group. - -Assumes that lwGetPointPolygons(), lwGetPolyNormals() and -lwResolvePolySurfaces() have already been called. -====================================================================== */ - -void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ) -{ - int j, k, n, g, h, p; - float a; - - for ( j = 0; j < polygon->count; j++ ) { - for ( n = 0; n < polygon->pol[ j ].nverts; n++ ) { - for ( k = 0; k < 3; k++ ) - polygon->pol[ j ].v[ n ].norm[ k ] = polygon->pol[ j ].norm[ k ]; - - if ( polygon->pol[ j ].surf->smooth <= 0 ) continue; - - p = polygon->pol[ j ].v[ n ].index; - - for ( g = 0; g < point->pt[ p ].npols; g++ ) { - h = point->pt[ p ].pol[ g ]; - if ( h == j ) continue; - - if ( polygon->pol[ j ].smoothgrp != polygon->pol[ h ].smoothgrp ) - continue; - a = vecangle( polygon->pol[ j ].norm, polygon->pol[ h ].norm ); - if ( a > polygon->pol[ j ].surf->smooth ) continue; - - for ( k = 0; k < 3; k++ ) - polygon->pol[ j ].v[ n ].norm[ k ] += polygon->pol[ h ].norm[ k ]; - } - - normalize( polygon->pol[ j ].v[ n ].norm ); - } - } + ====================================================================== + lwGetVertNormals() + + Calculate the vertex normals. For each polygon vertex, sum the + normals of the polygons that share the point. If the normals of the + current and adjacent polygons form an angle greater than the max + smoothing angle for the current polygon's surface, the normal of the + adjacent polygon is excluded from the sum. It's also excluded if the + polygons aren't in the same smoothing group. + + Assumes that lwGetPointPolygons(), lwGetPolyNormals() and + lwResolvePolySurfaces() have already been called. + ====================================================================== */ + +void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ){ + int j, k, n, g, h, p; + float a; + + for ( j = 0; j < polygon->count; j++ ) { + for ( n = 0; n < polygon->pol[ j ].nverts; n++ ) { + for ( k = 0; k < 3; k++ ) + polygon->pol[ j ].v[ n ].norm[ k ] = polygon->pol[ j ].norm[ k ]; + + if ( polygon->pol[ j ].surf->smooth <= 0 ) { + continue; + } + + p = polygon->pol[ j ].v[ n ].index; + + for ( g = 0; g < point->pt[ p ].npols; g++ ) { + h = point->pt[ p ].pol[ g ]; + if ( h == j ) { + continue; + } + + if ( polygon->pol[ j ].smoothgrp != polygon->pol[ h ].smoothgrp ) { + continue; + } + a = vecangle( polygon->pol[ j ].norm, polygon->pol[ h ].norm ); + if ( a > polygon->pol[ j ].surf->smooth ) { + continue; + } + + for ( k = 0; k < 3; k++ ) + polygon->pol[ j ].v[ n ].norm[ k ] += polygon->pol[ h ].norm[ k ]; + } + + normalize( polygon->pol[ j ].v[ n ].norm ); + } + } } /* -====================================================================== -lwFreeTags() - -Free memory used by an lwTagList. -====================================================================== */ - -void lwFreeTags( lwTagList *tlist ) -{ - int i; - - if ( tlist ) { - if ( tlist->tag ) { - for ( i = 0; i < tlist->count; i++ ) - if ( tlist->tag[ i ] ) _pico_free( tlist->tag[ i ] ); - _pico_free( tlist->tag ); - } - memset( tlist, 0, sizeof( lwTagList )); - } + ====================================================================== + lwFreeTags() + + Free memory used by an lwTagList. + ====================================================================== */ + +void lwFreeTags( lwTagList *tlist ){ + int i; + + if ( tlist ) { + if ( tlist->tag ) { + for ( i = 0; i < tlist->count; i++ ) + if ( tlist->tag[ i ] ) { + _pico_free( tlist->tag[ i ] ); + } + _pico_free( tlist->tag ); + } + memset( tlist, 0, sizeof( lwTagList ) ); + } } /* -====================================================================== -lwGetTags() + ====================================================================== + lwGetTags() -Read tag strings from a TAGS chunk in an LWO2 file. The tags are -added to the lwTagList array. -====================================================================== */ + Read tag strings from a TAGS chunk in an LWO2 file. The tags are + added to the lwTagList array. + ====================================================================== */ -int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ) -{ - char *buf, *bp; - int i, len, ntags; +int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ){ + char *buf, *bp; + int i, len, ntags; - if ( cksize == 0 ) return 1; + if ( cksize == 0 ) { + return 1; + } - /* read the whole chunk */ + /* read the whole chunk */ - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) return 0; + set_flen( 0 ); + buf = getbytes( fp, cksize ); + if ( !buf ) { + return 0; + } - /* count the strings */ + /* count the strings */ - ntags = 0; - bp = buf; - while ( bp < buf + cksize ) { - len = strlen( bp ) + 1; - len += len & 1; - bp += len; - ++ntags; - } + ntags = 0; + bp = buf; + while ( bp < buf + cksize ) { + len = strlen( bp ) + 1; + len += len & 1; + bp += len; + ++ntags; + } - /* expand the string array to hold the new tags */ + /* expand the string array to hold the new tags */ - tlist->offset = tlist->count; - tlist->count += ntags; - if ( !_pico_realloc( (void *) &tlist->tag, (tlist->count - ntags) * sizeof( char * ), tlist->count * sizeof( char * )) ) - goto Fail; - memset( &tlist->tag[ tlist->offset ], 0, ntags * sizeof( char * )); + tlist->offset = tlist->count; + tlist->count += ntags; + if ( !_pico_realloc( (void *) &tlist->tag, ( tlist->count - ntags ) * sizeof( char * ), tlist->count * sizeof( char * ) ) ) { + goto Fail; + } + memset( &tlist->tag[ tlist->offset ], 0, ntags * sizeof( char * ) ); - /* copy the new tags to the tag array */ + /* copy the new tags to the tag array */ - bp = buf; - for ( i = 0; i < ntags; i++ ) - tlist->tag[ i + tlist->offset ] = sgetS0( (unsigned char **) &bp ); + bp = buf; + for ( i = 0; i < ntags; i++ ) + tlist->tag[ i + tlist->offset ] = sgetS0( (unsigned char **) &bp ); - _pico_free( buf ); - return 1; + _pico_free( buf ); + return 1; Fail: - if ( buf ) _pico_free( buf ); - return 0; + if ( buf ) { + _pico_free( buf ); + } + return 0; } /* -====================================================================== -lwGetPolygonTags() + ====================================================================== + lwGetPolygonTags() -Read polygon tags from a PTAG chunk in an LWO2 file. -====================================================================== */ + Read polygon tags from a PTAG chunk in an LWO2 file. + ====================================================================== */ int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, - lwPolygonList *plist ) -{ - unsigned int type; - int rlen = 0, i, j; - - set_flen( 0 ); - type = getU4( fp ); - rlen = get_flen(); - if ( rlen < 0 ) return 0; - - if ( type != ID_SURF && type != ID_PART && type != ID_SMGP ) { - _pico_memstream_seek( fp, cksize - 4, PICO_SEEK_CUR ); - return 1; - } - - while ( rlen < cksize ) { - i = getVX( fp ) + plist->offset; - j = getVX( fp ) + tlist->offset; - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) return 0; - - switch ( type ) { - case ID_SURF: plist->pol[ i ].surf = ( lwSurface * ) (size_t) j; break; - case ID_PART: plist->pol[ i ].part = j; break; - case ID_SMGP: plist->pol[ i ].smoothgrp = j; break; - } - } - - return 1; + lwPolygonList *plist ){ + unsigned int type; + int rlen = 0, i, j; + + set_flen( 0 ); + type = getU4( fp ); + rlen = get_flen(); + if ( rlen < 0 ) { + return 0; + } + + if ( type != ID_SURF && type != ID_PART && type != ID_SMGP ) { + _pico_memstream_seek( fp, cksize - 4, PICO_SEEK_CUR ); + return 1; + } + + while ( rlen < cksize ) { + i = getVX( fp ) + plist->offset; + j = getVX( fp ) + tlist->offset; + rlen = get_flen(); + if ( rlen < 0 || rlen > cksize ) { + return 0; + } + + switch ( type ) { + case ID_SURF: plist->pol[ i ].surf = ( lwSurface * ) (size_t) j; break; + case ID_PART: plist->pol[ i ].part = j; break; + case ID_SMGP: plist->pol[ i ].smoothgrp = j; break; + } + } + + return 1; } diff --git a/libs/picomodel/lwo/surface.c b/libs/picomodel/lwo/surface.c index 6b2bbe62..4b350024 100644 --- a/libs/picomodel/lwo/surface.c +++ b/libs/picomodel/lwo/surface.c @@ -1,1005 +1,1107 @@ /* -====================================================================== -surface.c + ====================================================================== + surface.c -Surface functions for an LWO2 reader. + Surface functions for an LWO2 reader. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwFreePlugin() - -Free the memory used by an lwPlugin. -====================================================================== */ - -void lwFreePlugin( lwPlugin *p ) -{ - if ( p ) { - if ( p->ord ) _pico_free( p->ord ); - if ( p->name ) _pico_free( p->name ); - if ( p->data ) _pico_free( p->data ); - _pico_free( p ); - } + ====================================================================== + lwFreePlugin() + + Free the memory used by an lwPlugin. + ====================================================================== */ + +void lwFreePlugin( lwPlugin *p ){ + if ( p ) { + if ( p->ord ) { + _pico_free( p->ord ); + } + if ( p->name ) { + _pico_free( p->name ); + } + if ( p->data ) { + _pico_free( p->data ); + } + _pico_free( p ); + } } /* -====================================================================== -lwFreeTexture() - -Free the memory used by an lwTexture. -====================================================================== */ - -void lwFreeTexture( lwTexture *t ) -{ - if ( t ) { - if ( t->ord ) _pico_free( t->ord ); - switch ( t->type ) { - case ID_IMAP: - if ( t->param.imap.vmap_name ) _pico_free( t->param.imap.vmap_name ); - if ( t->tmap.ref_object ) _pico_free( t->tmap.ref_object ); - break; - case ID_PROC: - if ( t->param.proc.name ) _pico_free( t->param.proc.name ); - if ( t->param.proc.data ) _pico_free( t->param.proc.data ); - break; - case ID_GRAD: - if ( t->param.grad.key ) _pico_free( t->param.grad.key ); - if ( t->param.grad.ikey ) _pico_free( t->param.grad.ikey ); - break; - } - _pico_free( t ); - } + ====================================================================== + lwFreeTexture() + + Free the memory used by an lwTexture. + ====================================================================== */ + +void lwFreeTexture( lwTexture *t ){ + if ( t ) { + if ( t->ord ) { + _pico_free( t->ord ); + } + switch ( t->type ) { + case ID_IMAP: + if ( t->param.imap.vmap_name ) { + _pico_free( t->param.imap.vmap_name ); + } + if ( t->tmap.ref_object ) { + _pico_free( t->tmap.ref_object ); + } + break; + case ID_PROC: + if ( t->param.proc.name ) { + _pico_free( t->param.proc.name ); + } + if ( t->param.proc.data ) { + _pico_free( t->param.proc.data ); + } + break; + case ID_GRAD: + if ( t->param.grad.key ) { + _pico_free( t->param.grad.key ); + } + if ( t->param.grad.ikey ) { + _pico_free( t->param.grad.ikey ); + } + break; + } + _pico_free( t ); + } } /* -====================================================================== -lwFreeSurface() - -Free the memory used by an lwSurface. -====================================================================== */ - -void lwFreeSurface( lwSurface *surf ) -{ - if ( surf ) { - if ( surf->name ) _pico_free( surf->name ); - if ( surf->srcname ) _pico_free( surf->srcname ); - - lwListFree( surf->shader, (void *) lwFreePlugin ); - - lwListFree( surf->color.tex, (void *) lwFreeTexture ); - lwListFree( surf->luminosity.tex, (void *) lwFreeTexture ); - lwListFree( surf->diffuse.tex, (void *) lwFreeTexture ); - lwListFree( surf->specularity.tex, (void *) lwFreeTexture ); - lwListFree( surf->glossiness.tex, (void *) lwFreeTexture ); - lwListFree( surf->reflection.val.tex, (void *) lwFreeTexture ); - lwListFree( surf->transparency.val.tex, (void *) lwFreeTexture ); - lwListFree( surf->eta.tex, (void *) lwFreeTexture ); - lwListFree( surf->translucency.tex, (void *) lwFreeTexture ); - lwListFree( surf->bump.tex, (void *) lwFreeTexture ); - - _pico_free( surf ); - } + ====================================================================== + lwFreeSurface() + + Free the memory used by an lwSurface. + ====================================================================== */ + +void lwFreeSurface( lwSurface *surf ){ + if ( surf ) { + if ( surf->name ) { + _pico_free( surf->name ); + } + if ( surf->srcname ) { + _pico_free( surf->srcname ); + } + + lwListFree( surf->shader, (void *) lwFreePlugin ); + + lwListFree( surf->color.tex, (void *) lwFreeTexture ); + lwListFree( surf->luminosity.tex, (void *) lwFreeTexture ); + lwListFree( surf->diffuse.tex, (void *) lwFreeTexture ); + lwListFree( surf->specularity.tex, (void *) lwFreeTexture ); + lwListFree( surf->glossiness.tex, (void *) lwFreeTexture ); + lwListFree( surf->reflection.val.tex, (void *) lwFreeTexture ); + lwListFree( surf->transparency.val.tex, (void *) lwFreeTexture ); + lwListFree( surf->eta.tex, (void *) lwFreeTexture ); + lwListFree( surf->translucency.tex, (void *) lwFreeTexture ); + lwListFree( surf->bump.tex, (void *) lwFreeTexture ); + + _pico_free( surf ); + } } /* -====================================================================== -lwGetTHeader() + ====================================================================== + lwGetTHeader() -Read a texture map header from a SURF.BLOK in an LWO2 file. This is -the first subchunk in a BLOK, and its contents are common to all three -texture types. -====================================================================== */ + Read a texture map header from a SURF.BLOK in an LWO2 file. This is + the first subchunk in a BLOK, and its contents are common to all three + texture types. + ====================================================================== */ -int lwGetTHeader( picoMemStream_t *fp, int hsz, lwTexture *tex ) -{ - unsigned int id; - unsigned short sz; - int pos, rlen; +int lwGetTHeader( picoMemStream_t *fp, int hsz, lwTexture *tex ){ + unsigned int id; + unsigned short sz; + int pos, rlen; - /* remember where we started */ + /* remember where we started */ - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); + set_flen( 0 ); + pos = _pico_memstream_tell( fp ); - /* ordinal string */ + /* ordinal string */ - tex->ord = getS0( fp ); + tex->ord = getS0( fp ); - /* first subchunk header */ + /* first subchunk header */ - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) return 0; + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + return 0; + } - /* process subchunks as they're encountered */ + /* process subchunks as they're encountered */ - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); - switch ( id ) { - case ID_CHAN: - tex->chan = getU4( fp ); - break; + switch ( id ) { + case ID_CHAN: + tex->chan = getU4( fp ); + break; - case ID_OPAC: - tex->opac_type = getU2( fp ); - tex->opacity.val = getF4( fp ); - tex->opacity.eindex = getVX( fp ); - break; + case ID_OPAC: + tex->opac_type = getU2( fp ); + tex->opacity.val = getF4( fp ); + tex->opacity.eindex = getVX( fp ); + break; - case ID_ENAB: - tex->enabled = getU2( fp ); - break; + case ID_ENAB: + tex->enabled = getU2( fp ); + break; - case ID_NEGA: - tex->negative = getU2( fp ); - break; + case ID_NEGA: + tex->negative = getU2( fp ); + break; - case ID_AXIS: - tex->axis = getU2( fp ); - break; + case ID_AXIS: + tex->axis = getU2( fp ); + break; - default: - break; - } + default: + break; + } - /* error while reading current subchunk? */ + /* error while reading current subchunk? */ - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) return 0; + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + return 0; + } - /* skip unread parts of the current subchunk */ + /* skip unread parts of the current subchunk */ - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } - /* end of the texture header subchunk? */ + /* end of the texture header subchunk? */ - if ( hsz <= _pico_memstream_tell( fp ) - pos ) - break; + if ( hsz <= _pico_memstream_tell( fp ) - pos ) { + break; + } - /* get the next subchunk header */ + /* get the next subchunk header */ - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) return 0; - } + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + return 0; + } + } - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; + set_flen( _pico_memstream_tell( fp ) - pos ); + return 1; } /* -====================================================================== -lwGetTMap() - -Read a texture map from a SURF.BLOK in an LWO2 file. The TMAP -defines the mapping from texture to world or object coordinates. -====================================================================== */ - -int lwGetTMap( picoMemStream_t *fp, int tmapsz, lwTMap *tmap ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos, i; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) return 0; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_SIZE: - for ( i = 0; i < 3; i++ ) - tmap->size.val[ i ] = getF4( fp ); - tmap->size.eindex = getVX( fp ); - break; - - case ID_CNTR: - for ( i = 0; i < 3; i++ ) - tmap->center.val[ i ] = getF4( fp ); - tmap->center.eindex = getVX( fp ); - break; - - case ID_ROTA: - for ( i = 0; i < 3; i++ ) - tmap->rotate.val[ i ] = getF4( fp ); - tmap->rotate.eindex = getVX( fp ); - break; - - case ID_FALL: - tmap->fall_type = getU2( fp ); - for ( i = 0; i < 3; i++ ) - tmap->falloff.val[ i ] = getF4( fp ); - tmap->falloff.eindex = getVX( fp ); - break; - - case ID_OREF: - tmap->ref_object = getS0( fp ); - break; - - case ID_CSYS: - tmap->coord_sys = getU2( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the TMAP subchunk? */ - - if ( tmapsz <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) return 0; - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; + ====================================================================== + lwGetTMap() + + Read a texture map from a SURF.BLOK in an LWO2 file. The TMAP + defines the mapping from texture to world or object coordinates. + ====================================================================== */ + +int lwGetTMap( picoMemStream_t *fp, int tmapsz, lwTMap *tmap ){ + unsigned int id; + unsigned short sz; + int rlen, pos, i; + + pos = _pico_memstream_tell( fp ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + return 0; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_SIZE: + for ( i = 0; i < 3; i++ ) + tmap->size.val[ i ] = getF4( fp ); + tmap->size.eindex = getVX( fp ); + break; + + case ID_CNTR: + for ( i = 0; i < 3; i++ ) + tmap->center.val[ i ] = getF4( fp ); + tmap->center.eindex = getVX( fp ); + break; + + case ID_ROTA: + for ( i = 0; i < 3; i++ ) + tmap->rotate.val[ i ] = getF4( fp ); + tmap->rotate.eindex = getVX( fp ); + break; + + case ID_FALL: + tmap->fall_type = getU2( fp ); + for ( i = 0; i < 3; i++ ) + tmap->falloff.val[ i ] = getF4( fp ); + tmap->falloff.eindex = getVX( fp ); + break; + + case ID_OREF: + tmap->ref_object = getS0( fp ); + break; + + case ID_CSYS: + tmap->coord_sys = getU2( fp ); + break; + + default: + break; + } + + /* error while reading the current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + return 0; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the TMAP subchunk? */ + + if ( tmapsz <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + return 0; + } + } + + set_flen( _pico_memstream_tell( fp ) - pos ); + return 1; } /* -====================================================================== -lwGetImageMap() - -Read an lwImageMap from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -int lwGetImageMap( picoMemStream_t *fp, int rsz, lwTexture *tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) return 0; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap )) return 0; - break; - - case ID_PROJ: - tex->param.imap.projection = getU2( fp ); - break; - - case ID_VMAP: - tex->param.imap.vmap_name = getS0( fp ); - break; - - case ID_AXIS: - tex->param.imap.axis = getU2( fp ); - break; - - case ID_IMAG: - tex->param.imap.cindex = getVX( fp ); - break; - - case ID_WRAP: - tex->param.imap.wrapw_type = getU2( fp ); - tex->param.imap.wraph_type = getU2( fp ); - break; - - case ID_WRPW: - tex->param.imap.wrapw.val = getF4( fp ); - tex->param.imap.wrapw.eindex = getVX( fp ); - break; - - case ID_WRPH: - tex->param.imap.wraph.val = getF4( fp ); - tex->param.imap.wraph.eindex = getVX( fp ); - break; - - case ID_AAST: - tex->param.imap.aas_flags = getU2( fp ); - tex->param.imap.aa_strength = getF4( fp ); - break; - - case ID_PIXB: - tex->param.imap.pblend = getU2( fp ); - break; - - case ID_STCK: - tex->param.imap.stck.val = getF4( fp ); - tex->param.imap.stck.eindex = getVX( fp ); - break; - - case ID_TAMP: - tex->param.imap.amplitude.val = getF4( fp ); - tex->param.imap.amplitude.eindex = getVX( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the image map? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) return 0; - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; + ====================================================================== + lwGetImageMap() + + Read an lwImageMap from a SURF.BLOK in an LWO2 file. + ====================================================================== */ + +int lwGetImageMap( picoMemStream_t *fp, int rsz, lwTexture *tex ){ + unsigned int id; + unsigned short sz; + int rlen, pos; + + pos = _pico_memstream_tell( fp ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + return 0; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_TMAP: + if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { + return 0; + } + break; + + case ID_PROJ: + tex->param.imap.projection = getU2( fp ); + break; + + case ID_VMAP: + tex->param.imap.vmap_name = getS0( fp ); + break; + + case ID_AXIS: + tex->param.imap.axis = getU2( fp ); + break; + + case ID_IMAG: + tex->param.imap.cindex = getVX( fp ); + break; + + case ID_WRAP: + tex->param.imap.wrapw_type = getU2( fp ); + tex->param.imap.wraph_type = getU2( fp ); + break; + + case ID_WRPW: + tex->param.imap.wrapw.val = getF4( fp ); + tex->param.imap.wrapw.eindex = getVX( fp ); + break; + + case ID_WRPH: + tex->param.imap.wraph.val = getF4( fp ); + tex->param.imap.wraph.eindex = getVX( fp ); + break; + + case ID_AAST: + tex->param.imap.aas_flags = getU2( fp ); + tex->param.imap.aa_strength = getF4( fp ); + break; + + case ID_PIXB: + tex->param.imap.pblend = getU2( fp ); + break; + + case ID_STCK: + tex->param.imap.stck.val = getF4( fp ); + tex->param.imap.stck.eindex = getVX( fp ); + break; + + case ID_TAMP: + tex->param.imap.amplitude.val = getF4( fp ); + tex->param.imap.amplitude.eindex = getVX( fp ); + break; + + default: + break; + } + + /* error while reading the current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + return 0; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the image map? */ + + if ( rsz <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + return 0; + } + } + + set_flen( _pico_memstream_tell( fp ) - pos ); + return 1; } /* -====================================================================== -lwGetProcedural() - -Read an lwProcedural from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -int lwGetProcedural( picoMemStream_t *fp, int rsz, lwTexture *tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) return 0; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap )) return 0; - break; - - case ID_AXIS: - tex->param.proc.axis = getU2( fp ); - break; - - case ID_VALU: - tex->param.proc.value[ 0 ] = getF4( fp ); - if ( sz >= 8 ) tex->param.proc.value[ 1 ] = getF4( fp ); - if ( sz >= 12 ) tex->param.proc.value[ 2 ] = getF4( fp ); - break; - - case ID_FUNC: - tex->param.proc.name = getS0( fp ); - rlen = get_flen(); - tex->param.proc.data = getbytes( fp, sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the procedural block? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) return 0; - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; + ====================================================================== + lwGetProcedural() + + Read an lwProcedural from a SURF.BLOK in an LWO2 file. + ====================================================================== */ + +int lwGetProcedural( picoMemStream_t *fp, int rsz, lwTexture *tex ){ + unsigned int id; + unsigned short sz; + int rlen, pos; + + pos = _pico_memstream_tell( fp ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + return 0; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_TMAP: + if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { + return 0; + } + break; + + case ID_AXIS: + tex->param.proc.axis = getU2( fp ); + break; + + case ID_VALU: + tex->param.proc.value[ 0 ] = getF4( fp ); + if ( sz >= 8 ) { + tex->param.proc.value[ 1 ] = getF4( fp ); + } + if ( sz >= 12 ) { + tex->param.proc.value[ 2 ] = getF4( fp ); + } + break; + + case ID_FUNC: + tex->param.proc.name = getS0( fp ); + rlen = get_flen(); + tex->param.proc.data = getbytes( fp, sz - rlen ); + break; + + default: + break; + } + + /* error while reading the current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + return 0; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the procedural block? */ + + if ( rsz <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + return 0; + } + } + + set_flen( _pico_memstream_tell( fp ) - pos ); + return 1; } /* -====================================================================== -lwGetGradient() - -Read an lwGradient from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -int lwGetGradient( picoMemStream_t *fp, int rsz, lwTexture *tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos, i, j, nkeys; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) return 0; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap )) return 0; - break; - - case ID_PNAM: - tex->param.grad.paramname = getS0( fp ); - break; - - case ID_INAM: - tex->param.grad.itemname = getS0( fp ); - break; - - case ID_GRST: - tex->param.grad.start = getF4( fp ); - break; - - case ID_GREN: - tex->param.grad.end = getF4( fp ); - break; - - case ID_GRPT: - tex->param.grad.repeat = getU2( fp ); - break; - - case ID_FKEY: - nkeys = sz / sizeof( lwGradKey ); - tex->param.grad.key = _pico_calloc( nkeys, sizeof( lwGradKey )); - if ( !tex->param.grad.key ) return 0; - for ( i = 0; i < nkeys; i++ ) { - tex->param.grad.key[ i ].value = getF4( fp ); - for ( j = 0; j < 4; j++ ) - tex->param.grad.key[ i ].rgba[ j ] = getF4( fp ); - } - break; - - case ID_IKEY: - nkeys = sz / 2; - tex->param.grad.ikey = _pico_calloc( nkeys, sizeof( short )); - if ( !tex->param.grad.ikey ) return 0; - for ( i = 0; i < nkeys; i++ ) - tex->param.grad.ikey[ i ] = getU2( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the gradient? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) return 0; - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; + ====================================================================== + lwGetGradient() + + Read an lwGradient from a SURF.BLOK in an LWO2 file. + ====================================================================== */ + +int lwGetGradient( picoMemStream_t *fp, int rsz, lwTexture *tex ){ + unsigned int id; + unsigned short sz; + int rlen, pos, i, j, nkeys; + + pos = _pico_memstream_tell( fp ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + return 0; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_TMAP: + if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { + return 0; + } + break; + + case ID_PNAM: + tex->param.grad.paramname = getS0( fp ); + break; + + case ID_INAM: + tex->param.grad.itemname = getS0( fp ); + break; + + case ID_GRST: + tex->param.grad.start = getF4( fp ); + break; + + case ID_GREN: + tex->param.grad.end = getF4( fp ); + break; + + case ID_GRPT: + tex->param.grad.repeat = getU2( fp ); + break; + + case ID_FKEY: + nkeys = sz / sizeof( lwGradKey ); + tex->param.grad.key = _pico_calloc( nkeys, sizeof( lwGradKey ) ); + if ( !tex->param.grad.key ) { + return 0; + } + for ( i = 0; i < nkeys; i++ ) { + tex->param.grad.key[ i ].value = getF4( fp ); + for ( j = 0; j < 4; j++ ) + tex->param.grad.key[ i ].rgba[ j ] = getF4( fp ); + } + break; + + case ID_IKEY: + nkeys = sz / 2; + tex->param.grad.ikey = _pico_calloc( nkeys, sizeof( short ) ); + if ( !tex->param.grad.ikey ) { + return 0; + } + for ( i = 0; i < nkeys; i++ ) + tex->param.grad.ikey[ i ] = getU2( fp ); + break; + + default: + break; + } + + /* error while reading the current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + return 0; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the gradient? */ + + if ( rsz <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + return 0; + } + } + + set_flen( _pico_memstream_tell( fp ) - pos ); + return 1; } /* -====================================================================== -lwGetTexture() - -Read an lwTexture from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwTexture *lwGetTexture( picoMemStream_t *fp, int bloksz, unsigned int type ) -{ - lwTexture *tex; - unsigned short sz; - int ok; - - tex = _pico_calloc( 1, sizeof( lwTexture )); - if ( !tex ) return NULL; - - tex->type = type; - tex->tmap.size.val[ 0 ] = - tex->tmap.size.val[ 1 ] = - tex->tmap.size.val[ 2 ] = 1.0f; - tex->opacity.val = 1.0f; - tex->enabled = 1; - - sz = getU2( fp ); - if ( !lwGetTHeader( fp, sz, tex )) { - _pico_free( tex ); - return NULL; - } - - sz = bloksz - sz - 6; - switch ( type ) { - case ID_IMAP: ok = lwGetImageMap( fp, sz, tex ); break; - case ID_PROC: ok = lwGetProcedural( fp, sz, tex ); break; - case ID_GRAD: ok = lwGetGradient( fp, sz, tex ); break; - default: - ok = !_pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); - } - - if ( !ok ) { - lwFreeTexture( tex ); - return NULL; - } - - set_flen( bloksz ); - return tex; + ====================================================================== + lwGetTexture() + + Read an lwTexture from a SURF.BLOK in an LWO2 file. + ====================================================================== */ + +lwTexture *lwGetTexture( picoMemStream_t *fp, int bloksz, unsigned int type ){ + lwTexture *tex; + unsigned short sz; + int ok; + + tex = _pico_calloc( 1, sizeof( lwTexture ) ); + if ( !tex ) { + return NULL; + } + + tex->type = type; + tex->tmap.size.val[ 0 ] = + tex->tmap.size.val[ 1 ] = + tex->tmap.size.val[ 2 ] = 1.0f; + tex->opacity.val = 1.0f; + tex->enabled = 1; + + sz = getU2( fp ); + if ( !lwGetTHeader( fp, sz, tex ) ) { + _pico_free( tex ); + return NULL; + } + + sz = bloksz - sz - 6; + switch ( type ) { + case ID_IMAP: ok = lwGetImageMap( fp, sz, tex ); break; + case ID_PROC: ok = lwGetProcedural( fp, sz, tex ); break; + case ID_GRAD: ok = lwGetGradient( fp, sz, tex ); break; + default: + ok = !_pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); + } + + if ( !ok ) { + lwFreeTexture( tex ); + return NULL; + } + + set_flen( bloksz ); + return tex; } /* -====================================================================== -lwGetShader() - -Read a shader record from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwPlugin *lwGetShader( picoMemStream_t *fp, int bloksz ) -{ - lwPlugin *shdr; - unsigned int id; - unsigned short sz; - int hsz, rlen, pos; - - shdr = _pico_calloc( 1, sizeof( lwPlugin )); - if ( !shdr ) return NULL; - - pos = _pico_memstream_tell( fp ); - set_flen( 0 ); - hsz = getU2( fp ); - shdr->ord = getS0( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - while ( hsz > 0 ) { - sz += sz & 1; - hsz -= sz; - if ( id == ID_ENAB ) { - shdr->flags = getU2( fp ); - break; - } - else { - _pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); - id = getU4( fp ); - sz = getU2( fp ); - } - } - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_FUNC: - shdr->name = getS0( fp ); - rlen = get_flen(); - shdr->data = getbytes( fp, sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the shader block? */ - - if ( bloksz <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) goto Fail; - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return shdr; + ====================================================================== + lwGetShader() + + Read a shader record from a SURF.BLOK in an LWO2 file. + ====================================================================== */ + +lwPlugin *lwGetShader( picoMemStream_t *fp, int bloksz ){ + lwPlugin *shdr; + unsigned int id; + unsigned short sz; + int hsz, rlen, pos; + + shdr = _pico_calloc( 1, sizeof( lwPlugin ) ); + if ( !shdr ) { + return NULL; + } + + pos = _pico_memstream_tell( fp ); + set_flen( 0 ); + hsz = getU2( fp ); + shdr->ord = getS0( fp ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + while ( hsz > 0 ) { + sz += sz & 1; + hsz -= sz; + if ( id == ID_ENAB ) { + shdr->flags = getU2( fp ); + break; + } + else { + _pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); + id = getU4( fp ); + sz = getU2( fp ); + } + } + + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_FUNC: + shdr->name = getS0( fp ); + rlen = get_flen(); + shdr->data = getbytes( fp, sz - rlen ); + break; + + default: + break; + } + + /* error while reading the current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the shader block? */ + + if ( bloksz <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + goto Fail; + } + } + + set_flen( _pico_memstream_tell( fp ) - pos ); + return shdr; Fail: - lwFreePlugin( shdr ); - return NULL; + lwFreePlugin( shdr ); + return NULL; } /* -====================================================================== -compare_textures() -compare_shaders() + ====================================================================== + compare_textures() + compare_shaders() -Callbacks for the lwListInsert() function, which is called to add -textures to surface channels and shaders to surfaces. -====================================================================== */ + Callbacks for the lwListInsert() function, which is called to add + textures to surface channels and shaders to surfaces. + ====================================================================== */ -static int compare_textures( lwTexture *a, lwTexture *b ) -{ - return strcmp( a->ord, b->ord ); +static int compare_textures( lwTexture *a, lwTexture *b ){ + return strcmp( a->ord, b->ord ); } -static int compare_shaders( lwPlugin *a, lwPlugin *b ) -{ - return strcmp( a->ord, b->ord ); +static int compare_shaders( lwPlugin *a, lwPlugin *b ){ + return strcmp( a->ord, b->ord ); } /* -====================================================================== -add_texture() - -Finds the surface channel (lwTParam or lwCParam) to which a texture is -applied, then calls lwListInsert(). -====================================================================== */ - -static int add_texture( lwSurface *surf, lwTexture *tex ) -{ - lwTexture **list; - - switch ( tex->chan ) { - case ID_COLR: list = &surf->color.tex; break; - case ID_LUMI: list = &surf->luminosity.tex; break; - case ID_DIFF: list = &surf->diffuse.tex; break; - case ID_SPEC: list = &surf->specularity.tex; break; - case ID_GLOS: list = &surf->glossiness.tex; break; - case ID_REFL: list = &surf->reflection.val.tex; break; - case ID_TRAN: list = &surf->transparency.val.tex; break; - case ID_RIND: list = &surf->eta.tex; break; - case ID_TRNL: list = &surf->translucency.tex; break; - case ID_BUMP: list = &surf->bump.tex; break; - default: return 0; - } - - lwListInsert( (void **) list, tex, ( void *) compare_textures ); - return 1; + ====================================================================== + add_texture() + + Finds the surface channel (lwTParam or lwCParam) to which a texture is + applied, then calls lwListInsert(). + ====================================================================== */ + +static int add_texture( lwSurface *surf, lwTexture *tex ){ + lwTexture **list; + + switch ( tex->chan ) { + case ID_COLR: list = &surf->color.tex; break; + case ID_LUMI: list = &surf->luminosity.tex; break; + case ID_DIFF: list = &surf->diffuse.tex; break; + case ID_SPEC: list = &surf->specularity.tex; break; + case ID_GLOS: list = &surf->glossiness.tex; break; + case ID_REFL: list = &surf->reflection.val.tex; break; + case ID_TRAN: list = &surf->transparency.val.tex; break; + case ID_RIND: list = &surf->eta.tex; break; + case ID_TRNL: list = &surf->translucency.tex; break; + case ID_BUMP: list = &surf->bump.tex; break; + default: return 0; + } + + lwListInsert( (void **) list, tex, ( void *) compare_textures ); + return 1; } /* -====================================================================== -lwDefaultSurface() - -Allocate and initialize a surface. -====================================================================== */ - -lwSurface *lwDefaultSurface( void ) -{ - lwSurface *surf; - - surf = _pico_calloc( 1, sizeof( lwSurface )); - if ( !surf ) return NULL; - - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - return surf; + ====================================================================== + lwDefaultSurface() + + Allocate and initialize a surface. + ====================================================================== */ + +lwSurface *lwDefaultSurface( void ){ + lwSurface *surf; + + surf = _pico_calloc( 1, sizeof( lwSurface ) ); + if ( !surf ) { + return NULL; + } + + surf->color.rgb[ 0 ] = 0.78431f; + surf->color.rgb[ 1 ] = 0.78431f; + surf->color.rgb[ 2 ] = 0.78431f; + surf->diffuse.val = 1.0f; + surf->glossiness.val = 0.4f; + surf->bump.val = 1.0f; + surf->eta.val = 1.0f; + surf->sideflags = 1; + + return surf; } /* -====================================================================== -lwGetSurface() - -Read an lwSurface from an LWO2 file. -====================================================================== */ - -lwSurface *lwGetSurface( picoMemStream_t *fp, int cksize ) -{ - lwSurface *surf; - lwTexture *tex; - lwPlugin *shdr; - unsigned int id, type; - unsigned short sz; - int pos, rlen; - - - /* allocate the Surface structure */ + ====================================================================== + lwGetSurface() + + Read an lwSurface from an LWO2 file. + ====================================================================== */ + +lwSurface *lwGetSurface( picoMemStream_t *fp, int cksize ){ + lwSurface *surf; + lwTexture *tex; + lwPlugin *shdr; + unsigned int id, type; + unsigned short sz; + int pos, rlen; - surf = _pico_calloc( 1, sizeof( lwSurface )); - if ( !surf ) goto Fail; - - /* non-zero defaults */ - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* names */ - - surf->name = getS0( fp ); - surf->srcname = getS0( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) goto Fail; - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_COLR: - surf->color.rgb[ 0 ] = getF4( fp ); - surf->color.rgb[ 1 ] = getF4( fp ); - surf->color.rgb[ 2 ] = getF4( fp ); - surf->color.eindex = getVX( fp ); - break; - - case ID_LUMI: - surf->luminosity.val = getF4( fp ); - surf->luminosity.eindex = getVX( fp ); - break; - - case ID_DIFF: - surf->diffuse.val = getF4( fp ); - surf->diffuse.eindex = getVX( fp ); - break; - - case ID_SPEC: - surf->specularity.val = getF4( fp ); - surf->specularity.eindex = getVX( fp ); - break; - - case ID_GLOS: - surf->glossiness.val = getF4( fp ); - surf->glossiness.eindex = getVX( fp ); - break; - - case ID_REFL: - surf->reflection.val.val = getF4( fp ); - surf->reflection.val.eindex = getVX( fp ); - break; - - case ID_RFOP: - surf->reflection.options = getU2( fp ); - break; - - case ID_RIMG: - surf->reflection.cindex = getVX( fp ); - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4( fp ); - break; - - case ID_TRAN: - surf->transparency.val.val = getF4( fp ); - surf->transparency.val.eindex = getVX( fp ); - break; - - case ID_TROP: - surf->transparency.options = getU2( fp ); - break; - - case ID_TIMG: - surf->transparency.cindex = getVX( fp ); - break; - - case ID_RIND: - surf->eta.val = getF4( fp ); - surf->eta.eindex = getVX( fp ); - break; - - case ID_TRNL: - surf->translucency.val = getF4( fp ); - surf->translucency.eindex = getVX( fp ); - break; - - case ID_BUMP: - surf->bump.val = getF4( fp ); - surf->bump.eindex = getVX( fp ); - break; - - case ID_SMAN: - surf->smooth = getF4( fp ); - break; - - case ID_SIDE: - surf->sideflags = getU2( fp ); - break; - - case ID_CLRH: - surf->color_hilite.val = getF4( fp ); - surf->color_hilite.eindex = getVX( fp ); - break; - - case ID_CLRF: - surf->color_filter.val = getF4( fp ); - surf->color_filter.eindex = getVX( fp ); - break; - - case ID_ADTR: - surf->add_trans.val = getF4( fp ); - surf->add_trans.eindex = getVX( fp ); - break; - - case ID_SHRP: - surf->dif_sharp.val = getF4( fp ); - surf->dif_sharp.eindex = getVX( fp ); - break; - - case ID_GVAL: - surf->glow.val = getF4( fp ); - surf->glow.eindex = getVX( fp ); - break; - - case ID_LINE: - surf->line.enabled = 1; - if ( sz >= 2 ) surf->line.flags = getU2( fp ); - if ( sz >= 6 ) surf->line.size.val = getF4( fp ); - if ( sz >= 8 ) surf->line.size.eindex = getVX( fp ); - break; - - case ID_ALPH: - surf->alpha_mode = getU2( fp ); - surf->alpha = getF4( fp ); - break; - - case ID_AVAL: - surf->alpha = getF4( fp ); - break; - - case ID_BLOK: - type = getU4( fp ); - - switch ( type ) { - case ID_IMAP: - case ID_PROC: - case ID_GRAD: - tex = lwGetTexture( fp, sz - 4, type ); - if ( !tex ) goto Fail; - if ( !add_texture( surf, tex )) - lwFreeTexture( tex ); - set_flen( 4 + get_flen() ); - break; - case ID_SHDR: - shdr = lwGetShader( fp, sz - 4 ); - if ( !shdr ) goto Fail; - lwListInsert( (void **) &surf->shader, shdr, (void *) compare_shaders ); - ++surf->nshaders; - set_flen( 4 + get_flen() ); - break; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - - /* end of the SURF chunk? */ - - if ( cksize <= _pico_memstream_tell( fp ) - pos ) - break; - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) goto Fail; - } - - return surf; + /* allocate the Surface structure */ + + surf = _pico_calloc( 1, sizeof( lwSurface ) ); + if ( !surf ) { + goto Fail; + } + + /* non-zero defaults */ + + surf->color.rgb[ 0 ] = 0.78431f; + surf->color.rgb[ 1 ] = 0.78431f; + surf->color.rgb[ 2 ] = 0.78431f; + surf->diffuse.val = 1.0f; + surf->glossiness.val = 0.4f; + surf->bump.val = 1.0f; + surf->eta.val = 1.0f; + surf->sideflags = 1; + + /* remember where we started */ + + set_flen( 0 ); + pos = _pico_memstream_tell( fp ); + + /* names */ + + surf->name = getS0( fp ); + surf->srcname = getS0( fp ); + + /* first subchunk header */ + + id = getU4( fp ); + sz = getU2( fp ); + if ( 0 > get_flen() ) { + goto Fail; + } + + /* process subchunks as they're encountered */ + + while ( 1 ) { + sz += sz & 1; + set_flen( 0 ); + + switch ( id ) { + case ID_COLR: + surf->color.rgb[ 0 ] = getF4( fp ); + surf->color.rgb[ 1 ] = getF4( fp ); + surf->color.rgb[ 2 ] = getF4( fp ); + surf->color.eindex = getVX( fp ); + break; + + case ID_LUMI: + surf->luminosity.val = getF4( fp ); + surf->luminosity.eindex = getVX( fp ); + break; + + case ID_DIFF: + surf->diffuse.val = getF4( fp ); + surf->diffuse.eindex = getVX( fp ); + break; + + case ID_SPEC: + surf->specularity.val = getF4( fp ); + surf->specularity.eindex = getVX( fp ); + break; + + case ID_GLOS: + surf->glossiness.val = getF4( fp ); + surf->glossiness.eindex = getVX( fp ); + break; + + case ID_REFL: + surf->reflection.val.val = getF4( fp ); + surf->reflection.val.eindex = getVX( fp ); + break; + + case ID_RFOP: + surf->reflection.options = getU2( fp ); + break; + + case ID_RIMG: + surf->reflection.cindex = getVX( fp ); + break; + + case ID_RSAN: + surf->reflection.seam_angle = getF4( fp ); + break; + + case ID_TRAN: + surf->transparency.val.val = getF4( fp ); + surf->transparency.val.eindex = getVX( fp ); + break; + + case ID_TROP: + surf->transparency.options = getU2( fp ); + break; + + case ID_TIMG: + surf->transparency.cindex = getVX( fp ); + break; + + case ID_RIND: + surf->eta.val = getF4( fp ); + surf->eta.eindex = getVX( fp ); + break; + + case ID_TRNL: + surf->translucency.val = getF4( fp ); + surf->translucency.eindex = getVX( fp ); + break; + + case ID_BUMP: + surf->bump.val = getF4( fp ); + surf->bump.eindex = getVX( fp ); + break; + + case ID_SMAN: + surf->smooth = getF4( fp ); + break; + + case ID_SIDE: + surf->sideflags = getU2( fp ); + break; + + case ID_CLRH: + surf->color_hilite.val = getF4( fp ); + surf->color_hilite.eindex = getVX( fp ); + break; + + case ID_CLRF: + surf->color_filter.val = getF4( fp ); + surf->color_filter.eindex = getVX( fp ); + break; + + case ID_ADTR: + surf->add_trans.val = getF4( fp ); + surf->add_trans.eindex = getVX( fp ); + break; + + case ID_SHRP: + surf->dif_sharp.val = getF4( fp ); + surf->dif_sharp.eindex = getVX( fp ); + break; + + case ID_GVAL: + surf->glow.val = getF4( fp ); + surf->glow.eindex = getVX( fp ); + break; + + case ID_LINE: + surf->line.enabled = 1; + if ( sz >= 2 ) { + surf->line.flags = getU2( fp ); + } + if ( sz >= 6 ) { + surf->line.size.val = getF4( fp ); + } + if ( sz >= 8 ) { + surf->line.size.eindex = getVX( fp ); + } + break; + + case ID_ALPH: + surf->alpha_mode = getU2( fp ); + surf->alpha = getF4( fp ); + break; + + case ID_AVAL: + surf->alpha = getF4( fp ); + break; + + case ID_BLOK: + type = getU4( fp ); + + switch ( type ) { + case ID_IMAP: + case ID_PROC: + case ID_GRAD: + tex = lwGetTexture( fp, sz - 4, type ); + if ( !tex ) { + goto Fail; + } + if ( !add_texture( surf, tex ) ) { + lwFreeTexture( tex ); + } + set_flen( 4 + get_flen() ); + break; + case ID_SHDR: + shdr = lwGetShader( fp, sz - 4 ); + if ( !shdr ) { + goto Fail; + } + lwListInsert( (void **) &surf->shader, shdr, (void *) compare_shaders ); + ++surf->nshaders; + set_flen( 4 + get_flen() ); + break; + } + break; + + default: + break; + } + + /* error while reading current subchunk? */ + + rlen = get_flen(); + if ( rlen < 0 || rlen > sz ) { + goto Fail; + } + + /* skip unread parts of the current subchunk */ + + if ( rlen < sz ) { + _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); + } + + /* end of the SURF chunk? */ + + if ( cksize <= _pico_memstream_tell( fp ) - pos ) { + break; + } + + /* get the next subchunk header */ + + set_flen( 0 ); + id = getU4( fp ); + sz = getU2( fp ); + if ( 6 != get_flen() ) { + goto Fail; + } + } + + return surf; Fail: - if ( surf ) lwFreeSurface( surf ); - return NULL; + if ( surf ) { + lwFreeSurface( surf ); + } + return NULL; } diff --git a/libs/picomodel/lwo/vecmath.c b/libs/picomodel/lwo/vecmath.c index eaa1e8fc..f4ada601 100644 --- a/libs/picomodel/lwo/vecmath.c +++ b/libs/picomodel/lwo/vecmath.c @@ -1,37 +1,34 @@ /* -====================================================================== -vecmath.c + ====================================================================== + vecmath.c -Basic vector and matrix functions. + Basic vector and matrix functions. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include -float dot( float a[], float b[] ) -{ - return a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ]; +float dot( float a[], float b[] ){ + return a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ]; } -void cross( float a[], float b[], float c[] ) -{ - c[ 0 ] = a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ]; - c[ 1 ] = a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ]; - c[ 2 ] = a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ]; +void cross( float a[], float b[], float c[] ){ + c[ 0 ] = a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ]; + c[ 1 ] = a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ]; + c[ 2 ] = a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ]; } -void normalize( float v[] ) -{ - float r; +void normalize( float v[] ){ + float r; - r = ( float ) sqrt( dot( v, v )); - if ( r > 0 ) { - v[ 0 ] /= r; - v[ 1 ] /= r; - v[ 2 ] /= r; - } + r = ( float ) sqrt( dot( v, v ) ); + if ( r > 0 ) { + v[ 0 ] /= r; + v[ 1 ] /= r; + v[ 2 ] /= r; + } } diff --git a/libs/picomodel/lwo/vmap.c b/libs/picomodel/lwo/vmap.c index 69f87cf9..89765725 100644 --- a/libs/picomodel/lwo/vmap.c +++ b/libs/picomodel/lwo/vmap.c @@ -1,243 +1,266 @@ /* -====================================================================== -vmap.c + ====================================================================== + vmap.c -Vertex map functions for an LWO2 reader. + Vertex map functions for an LWO2 reader. -Ernie Wright 17 Sep 00 -====================================================================== */ + Ernie Wright 17 Sep 00 + ====================================================================== */ #include "../picointernal.h" #include "lwo2.h" /* -====================================================================== -lwFreeVMap() - -Free memory used by an lwVMap. -====================================================================== */ - -void lwFreeVMap( lwVMap *vmap ) -{ - if ( vmap ) { - if ( vmap->name ) _pico_free( vmap->name ); - if ( vmap->vindex ) _pico_free( vmap->vindex ); - if ( vmap->pindex ) _pico_free( vmap->pindex ); - if ( vmap->val ) { - if ( vmap->val[ 0 ] ) _pico_free( vmap->val[ 0 ] ); - _pico_free( vmap->val ); - } - _pico_free( vmap ); - } + ====================================================================== + lwFreeVMap() + + Free memory used by an lwVMap. + ====================================================================== */ + +void lwFreeVMap( lwVMap *vmap ){ + if ( vmap ) { + if ( vmap->name ) { + _pico_free( vmap->name ); + } + if ( vmap->vindex ) { + _pico_free( vmap->vindex ); + } + if ( vmap->pindex ) { + _pico_free( vmap->pindex ); + } + if ( vmap->val ) { + if ( vmap->val[ 0 ] ) { + _pico_free( vmap->val[ 0 ] ); + } + _pico_free( vmap->val ); + } + _pico_free( vmap ); + } } /* -====================================================================== -lwGetVMap() + ====================================================================== + lwGetVMap() -Read an lwVMap from a VMAP or VMAD chunk in an LWO2. -====================================================================== */ + Read an lwVMap from a VMAP or VMAD chunk in an LWO2. + ====================================================================== */ lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, - int perpoly ) -{ - unsigned char *buf, *bp; - lwVMap *vmap; - float *f; - int i, j, npts, rlen; - - - /* read the whole chunk */ - - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) return NULL; - - vmap = _pico_calloc( 1, sizeof( lwVMap )); - if ( !vmap ) { - _pico_free( buf ); - return NULL; - } - - /* initialize the vmap */ - - vmap->perpoly = perpoly; - - bp = buf; - set_flen( 0 ); - vmap->type = sgetU4( &bp ); - vmap->dim = sgetU2( &bp ); - vmap->name = sgetS0( &bp ); - rlen = get_flen(); - - /* count the vmap records */ - - npts = 0; - while ( bp < buf + cksize ) { - i = sgetVX( &bp ); - if ( perpoly ) - i = sgetVX( &bp ); - bp += vmap->dim * sizeof( float ); - ++npts; - } - - /* allocate the vmap */ - - vmap->nverts = npts; - vmap->vindex = _pico_calloc( npts, sizeof( int )); - if ( !vmap->vindex ) goto Fail; - if ( perpoly ) { - vmap->pindex = _pico_calloc( npts, sizeof( int )); - if ( !vmap->pindex ) goto Fail; - } - - if ( vmap->dim > 0 ) { - vmap->val = _pico_calloc( npts, sizeof( float * )); - if ( !vmap->val ) goto Fail; - f = _pico_alloc( npts * vmap->dim * sizeof( float )); - if ( !f ) goto Fail; - for ( i = 0; i < npts; i++ ) - vmap->val[ i ] = f + i * vmap->dim; - } - - /* fill in the vmap values */ - - bp = buf + rlen; - for ( i = 0; i < npts; i++ ) { - vmap->vindex[ i ] = sgetVX( &bp ); - if ( perpoly ) - vmap->pindex[ i ] = sgetVX( &bp ); - for ( j = 0; j < vmap->dim; j++ ) - vmap->val[ i ][ j ] = sgetF4( &bp ); - } - - _pico_free( buf ); - return vmap; + int perpoly ){ + unsigned char *buf, *bp; + lwVMap *vmap; + float *f; + int i, j, npts, rlen; + + + /* read the whole chunk */ + + set_flen( 0 ); + buf = getbytes( fp, cksize ); + if ( !buf ) { + return NULL; + } + + vmap = _pico_calloc( 1, sizeof( lwVMap ) ); + if ( !vmap ) { + _pico_free( buf ); + return NULL; + } + + /* initialize the vmap */ + + vmap->perpoly = perpoly; + + bp = buf; + set_flen( 0 ); + vmap->type = sgetU4( &bp ); + vmap->dim = sgetU2( &bp ); + vmap->name = sgetS0( &bp ); + rlen = get_flen(); + + /* count the vmap records */ + + npts = 0; + while ( bp < buf + cksize ) { + i = sgetVX( &bp ); + if ( perpoly ) { + i = sgetVX( &bp ); + } + bp += vmap->dim * sizeof( float ); + ++npts; + } + + /* allocate the vmap */ + + vmap->nverts = npts; + vmap->vindex = _pico_calloc( npts, sizeof( int ) ); + if ( !vmap->vindex ) { + goto Fail; + } + if ( perpoly ) { + vmap->pindex = _pico_calloc( npts, sizeof( int ) ); + if ( !vmap->pindex ) { + goto Fail; + } + } + + if ( vmap->dim > 0 ) { + vmap->val = _pico_calloc( npts, sizeof( float * ) ); + if ( !vmap->val ) { + goto Fail; + } + f = _pico_alloc( npts * vmap->dim * sizeof( float ) ); + if ( !f ) { + goto Fail; + } + for ( i = 0; i < npts; i++ ) + vmap->val[ i ] = f + i * vmap->dim; + } + + /* fill in the vmap values */ + + bp = buf + rlen; + for ( i = 0; i < npts; i++ ) { + vmap->vindex[ i ] = sgetVX( &bp ); + if ( perpoly ) { + vmap->pindex[ i ] = sgetVX( &bp ); + } + for ( j = 0; j < vmap->dim; j++ ) + vmap->val[ i ][ j ] = sgetF4( &bp ); + } + + _pico_free( buf ); + return vmap; Fail: - if ( buf ) _pico_free( buf ); - lwFreeVMap( vmap ); - return NULL; + if ( buf ) { + _pico_free( buf ); + } + lwFreeVMap( vmap ); + return NULL; } /* -====================================================================== -lwGetPointVMaps() - -Fill in the lwVMapPt structure for each point. -====================================================================== */ - -int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ) -{ - lwVMap *vm; - int i, j, n; - - /* count the number of vmap values for each point */ - - vm = vmap; - while ( vm ) { - if ( !vm->perpoly ) - for ( i = 0; i < vm->nverts; i++ ) - ++point->pt[ vm->vindex[ i ]].nvmaps; - vm = vm->next; - } - - /* allocate vmap references for each mapped point */ - - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].nvmaps ) { - point->pt[ i ].vm = _pico_calloc( point->pt[ i ].nvmaps, sizeof( lwVMapPt )); - if ( !point->pt[ i ].vm ) return 0; - point->pt[ i ].nvmaps = 0; - } - } - - /* fill in vmap references for each mapped point */ - - vm = vmap; - while ( vm ) { - if ( !vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - j = vm->vindex[ i ]; - n = point->pt[ j ].nvmaps; - point->pt[ j ].vm[ n ].vmap = vm; - point->pt[ j ].vm[ n ].index = i; - ++point->pt[ j ].nvmaps; - } - } - vm = vm->next; - } - - return 1; + ====================================================================== + lwGetPointVMaps() + + Fill in the lwVMapPt structure for each point. + ====================================================================== */ + +int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ){ + lwVMap *vm; + int i, j, n; + + /* count the number of vmap values for each point */ + + vm = vmap; + while ( vm ) { + if ( !vm->perpoly ) { + for ( i = 0; i < vm->nverts; i++ ) + ++point->pt[ vm->vindex[ i ]].nvmaps; + } + vm = vm->next; + } + + /* allocate vmap references for each mapped point */ + + for ( i = 0; i < point->count; i++ ) { + if ( point->pt[ i ].nvmaps ) { + point->pt[ i ].vm = _pico_calloc( point->pt[ i ].nvmaps, sizeof( lwVMapPt ) ); + if ( !point->pt[ i ].vm ) { + return 0; + } + point->pt[ i ].nvmaps = 0; + } + } + + /* fill in vmap references for each mapped point */ + + vm = vmap; + while ( vm ) { + if ( !vm->perpoly ) { + for ( i = 0; i < vm->nverts; i++ ) { + j = vm->vindex[ i ]; + n = point->pt[ j ].nvmaps; + point->pt[ j ].vm[ n ].vmap = vm; + point->pt[ j ].vm[ n ].index = i; + ++point->pt[ j ].nvmaps; + } + } + vm = vm->next; + } + + return 1; } /* -====================================================================== -lwGetPolyVMaps() - -Fill in the lwVMapPt structure for each polygon vertex. -====================================================================== */ - -int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ) -{ - lwVMap *vm; - lwPolVert *pv; - int i, j; - - /* count the number of vmap values for each polygon vertex */ - - vm = vmap; - while ( vm ) { - if ( vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { - pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; - if ( vm->vindex[ i ] == pv->index ) { - ++pv->nvmaps; - break; - } - } - } - } - vm = vm->next; - } - - /* allocate vmap references for each mapped vertex */ - - for ( i = 0; i < polygon->count; i++ ) { - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { - pv = &polygon->pol[ i ].v[ j ]; - if ( pv->nvmaps ) { - pv->vm = _pico_calloc( pv->nvmaps, sizeof( lwVMapPt )); - if ( !pv->vm ) return 0; - pv->nvmaps = 0; - } - } - } - - /* fill in vmap references for each mapped point */ - - vm = vmap; - while ( vm ) { - if ( vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { - pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; - if ( vm->vindex[ i ] == pv->index ) { - pv->vm[ pv->nvmaps ].vmap = vm; - pv->vm[ pv->nvmaps ].index = i; - ++pv->nvmaps; - break; - } - } - } - } - vm = vm->next; - } - - return 1; + ====================================================================== + lwGetPolyVMaps() + + Fill in the lwVMapPt structure for each polygon vertex. + ====================================================================== */ + +int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ){ + lwVMap *vm; + lwPolVert *pv; + int i, j; + + /* count the number of vmap values for each polygon vertex */ + + vm = vmap; + while ( vm ) { + if ( vm->perpoly ) { + for ( i = 0; i < vm->nverts; i++ ) { + for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { + pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; + if ( vm->vindex[ i ] == pv->index ) { + ++pv->nvmaps; + break; + } + } + } + } + vm = vm->next; + } + + /* allocate vmap references for each mapped vertex */ + + for ( i = 0; i < polygon->count; i++ ) { + for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { + pv = &polygon->pol[ i ].v[ j ]; + if ( pv->nvmaps ) { + pv->vm = _pico_calloc( pv->nvmaps, sizeof( lwVMapPt ) ); + if ( !pv->vm ) { + return 0; + } + pv->nvmaps = 0; + } + } + } + + /* fill in vmap references for each mapped point */ + + vm = vmap; + while ( vm ) { + if ( vm->perpoly ) { + for ( i = 0; i < vm->nverts; i++ ) { + for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { + pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; + if ( vm->vindex[ i ] == pv->index ) { + pv->vm[ pv->nvmaps ].vmap = vm; + pv->vm[ pv->nvmaps ].index = i; + ++pv->nvmaps; + break; + } + } + } + } + vm = vm->next; + } + + return 1; } diff --git a/libs/picomodel/picointernal.c b/libs/picomodel/picointernal.c index f08a9962..e1bf9d1b 100644 --- a/libs/picomodel/picointernal.c +++ b/libs/picomodel/picointernal.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -50,39 +50,41 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* function pointers */ -void *(*_pico_ptr_malloc )( size_t ) = malloc; -void (*_pico_ptr_free )( void* ) = free; -void (*_pico_ptr_load_file )( const char*, unsigned char**, int* ) = NULL; -void (*_pico_ptr_free_file )( void* ) = NULL; -void (*_pico_ptr_print )( int, const char* ) = NULL; +void *( *_pico_ptr_malloc )( size_t ) = malloc; +void ( *_pico_ptr_free )( void* ) = free; +void ( *_pico_ptr_load_file )( const char*, unsigned char**, int* ) = NULL; +void ( *_pico_ptr_free_file )( void* ) = NULL; +void ( *_pico_ptr_print )( int, const char* ) = NULL; typedef union { - float f; - char c[4]; + float f; + char c[4]; } floatSwapUnion; /* _pico_alloc: * kludged memory allocation wrapper */ -void *_pico_alloc( size_t size ) -{ +void *_pico_alloc( size_t size ){ void *ptr; /* some sanity checks */ - if( size == 0 ) + if ( size == 0 ) { return NULL; - if (_pico_ptr_malloc == NULL) + } + if ( _pico_ptr_malloc == NULL ) { return NULL; + } /* allocate memory */ - ptr = _pico_ptr_malloc(size); - if (ptr == NULL) + ptr = _pico_ptr_malloc( size ); + if ( ptr == NULL ) { return NULL; + } /* zero out allocated memory */ - memset(ptr,0,size); + memset( ptr,0,size ); /* return pointer to allocated memory */ return ptr; @@ -91,23 +93,25 @@ void *_pico_alloc( size_t size ) /* _pico_calloc: * _pico_calloc wrapper */ -void *_pico_calloc( size_t num, size_t size ) -{ +void *_pico_calloc( size_t num, size_t size ){ void *ptr; /* some sanity checks */ - if( num == 0 || size == 0 ) + if ( num == 0 || size == 0 ) { return NULL; - if (_pico_ptr_malloc == NULL) + } + if ( _pico_ptr_malloc == NULL ) { return NULL; + } /* allocate memory */ - ptr = _pico_ptr_malloc(num*size); - if (ptr == NULL) + ptr = _pico_ptr_malloc( num * size ); + if ( ptr == NULL ) { return NULL; + } /* zero out allocated memory */ - memset(ptr,0,num*size); + memset( ptr,0,num * size ); /* return pointer to allocated memory */ return ptr; @@ -117,30 +121,32 @@ void *_pico_calloc( size_t num, size_t size ) * memory reallocation wrapper (note: only grows, * but never shrinks or frees) */ -void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ) -{ +void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ){ void *ptr2; - + /* sanity checks */ - if( ptr == NULL ) + if ( ptr == NULL ) { return NULL; - if( newSize < oldSize ) + } + if ( newSize < oldSize ) { return *ptr; - if (_pico_ptr_malloc == NULL) + } + if ( _pico_ptr_malloc == NULL ) { return NULL; + } /* allocate new pointer */ ptr2 = _pico_alloc( newSize ); - if( ptr2 == NULL ) + if ( ptr2 == NULL ) { return NULL; + } /* copy */ - if( *ptr != NULL ) - { + if ( *ptr != NULL ) { memcpy( ptr2, *ptr, oldSize ); _pico_free( *ptr ); } - + /* fix up and return */ *ptr = ptr2; return *ptr; @@ -155,18 +161,19 @@ void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ) * as custom clone size (the string is cropped to fit into mem * if needed). -sea */ -char *_pico_clone_alloc( const char *str ) -{ - char* cloned; +char *_pico_clone_alloc( const char *str ){ + char* cloned; /* sanity check */ - if (str == NULL) - return NULL; + if ( str == NULL ) { + return NULL; + } /* allocate memory */ - cloned = _pico_alloc( strlen(str) + 1 ); - if (cloned == NULL) + cloned = _pico_alloc( strlen( str ) + 1 ); + if ( cloned == NULL ) { return NULL; + } /* copy input string to cloned string */ strcpy( cloned, str ); @@ -178,31 +185,29 @@ char *_pico_clone_alloc( const char *str ) /* _pico_free: * wrapper around the free function pointer */ -void _pico_free( void *ptr ) -{ +void _pico_free( void *ptr ){ /* sanity checks */ - if( ptr == NULL ) + if ( ptr == NULL ) { return; - if (_pico_ptr_free == NULL) + } + if ( _pico_ptr_free == NULL ) { return; + } /* free the allocated memory */ - _pico_ptr_free( ptr ); + _pico_ptr_free( ptr ); } /* _pico_load_file: * wrapper around the loadfile function pointer */ -void _pico_load_file( const char *name, unsigned char **buffer, int *bufSize ) -{ +void _pico_load_file( const char *name, unsigned char **buffer, int *bufSize ){ /* sanity checks */ - if( name == NULL ) - { + if ( name == NULL ) { *bufSize = -1; return; } - if (_pico_ptr_load_file == NULL) - { + if ( _pico_ptr_load_file == NULL ) { *bufSize = -1; return; } @@ -214,15 +219,14 @@ void _pico_load_file( const char *name, unsigned char **buffer, int *bufSize ) /* _pico_free_file: * wrapper around the file free function pointer */ -void _pico_free_file( void *buffer ) -{ +void _pico_free_file( void *buffer ){ /* sanity checks */ - if( buffer == NULL ) + if ( buffer == NULL ) { return; + } /* use default free */ - if( _pico_ptr_free_file == NULL ) - { + if ( _pico_ptr_free_file == NULL ) { free( buffer ); return; } @@ -233,16 +237,17 @@ void _pico_free_file( void *buffer ) /* _pico_printf: * wrapper around the print function pointer -sea */ -void _pico_printf( int level, const char *format, ...) -{ - char str[4096]; - va_list argptr; +void _pico_printf( int level, const char *format, ... ){ + char str[4096]; + va_list argptr; /* sanity checks */ - if( format == NULL ) + if ( format == NULL ) { return; - if (_pico_ptr_print == NULL) + } + if ( _pico_ptr_print == NULL ) { return; + } /* format string */ va_start( argptr,format ); @@ -250,8 +255,9 @@ void _pico_printf( int level, const char *format, ...) va_end( argptr ); /* remove linefeeds */ - if (str[ strlen(str)-1 ] == '\n') - str[ strlen(str)-1 ] = '\0'; + if ( str[ strlen( str ) - 1 ] == '\n' ) { + str[ strlen( str ) - 1 ] = '\0'; + } /* do the actual call */ _pico_ptr_print( level,str ); @@ -261,11 +267,11 @@ void _pico_printf( int level, const char *format, ...) * trims everything after the first whitespace-delimited token */ -void _pico_first_token( char *str ) -{ - if( !str || !*str ) +void _pico_first_token( char *str ){ + if ( !str || !*str ) { return; - while( *str && !isspace( *str ) ) + } + while ( *str && !isspace( *str ) ) str++; *str = '\0'; } @@ -273,53 +279,53 @@ void _pico_first_token( char *str ) /* _pico_strltrim: * left trims the given string -sea */ -char *_pico_strltrim( char *str ) -{ +char *_pico_strltrim( char *str ){ char *str1 = str, *str2 = str; - while (isspace(*str2)) str2++; - if( str2 != str ) - while( *str2 != '\0' ) /* fix: ydnar */ + while ( isspace( *str2 ) ) str2++; + if ( str2 != str ) { + while ( *str2 != '\0' ) /* fix: ydnar */ *str1++ = *str2++; + } return str; } /* _pico_strrtrim: * right trims the given string -sea */ -char *_pico_strrtrim( char *str ) -{ - if (str && *str) - { +char *_pico_strrtrim( char *str ){ + if ( str && *str ) { char *str1 = str; int allspace = 1; - while (*str1) + while ( *str1 ) { - if (allspace && !isspace(*str1)) allspace = 0; + if ( allspace && !isspace( *str1 ) ) { + allspace = 0; + } str1++; } - if (allspace) *str = '\0'; + if ( allspace ) { + *str = '\0'; + } else { str1--; - while ((isspace(*str1)) && (str1 >= str)) + while ( ( isspace( *str1 ) ) && ( str1 >= str ) ) *str1-- = '\0'; } } - return str; + return str; } /* _pico_strlwr: * pico internal string-to-lower routine. */ -char *_pico_strlwr( char *str ) -{ +char *_pico_strlwr( char *str ){ char *cp; - for (cp=str; *cp; ++cp) + for ( cp = str; *cp; ++cp ) { - if ('A' <= *cp && *cp <= 'Z') - { - *cp += ('a' - 'A'); + if ( 'A' <= *cp && *cp <= 'Z' ) { + *cp += ( 'a' - 'A' ); } } return str; @@ -328,79 +334,74 @@ char *_pico_strlwr( char *str ) /* _pico_strchcount: * counts how often the given char appears in str. -sea */ -int _pico_strchcount( char *str, int ch ) -{ +int _pico_strchcount( char *str, int ch ){ int count = 0; - while (*str++) if (*str == ch) count++; + while ( *str++ ) if ( *str == ch ) { + count++; + } return count; } -void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ) -{ +void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ){ int i; - for (i=0; i<3; i++) + for ( i = 0; i < 3; i++ ) { mins[i] = +999999; maxs[i] = -999999; } } -void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ) -{ +void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ){ int i; - for (i=0; i<3; i++) + for ( i = 0; i < 3; i++ ) { float value = p[i]; - if (value < mins[i]) mins[i] = value; - if (value > maxs[i]) maxs[i] = value; + if ( value < mins[i] ) { + mins[i] = value; + } + if ( value > maxs[i] ) { + maxs[i] = value; + } } } -void _pico_zero_vec( picoVec3_t vec ) -{ +void _pico_zero_vec( picoVec3_t vec ){ vec[ 0 ] = vec[ 1 ] = vec[ 2 ] = 0; } -void _pico_zero_vec2( picoVec2_t vec ) -{ +void _pico_zero_vec2( picoVec2_t vec ){ vec[ 0 ] = vec[ 1 ] = 0; } -void _pico_zero_vec4( picoVec4_t vec ) -{ +void _pico_zero_vec4( picoVec4_t vec ){ vec[ 0 ] = vec[ 1 ] = vec[ 2 ] = vec[ 3 ] = 0; } -void _pico_set_vec( picoVec3_t v, float a, float b, float c ) -{ +void _pico_set_vec( picoVec3_t v, float a, float b, float c ){ v[ 0 ] = a; v[ 1 ] = b; v[ 2 ] = c; } -void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ) -{ +void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ){ v[ 0 ] = a; v[ 1 ] = b; v[ 2 ] = c; v[ 3 ] = d; } -void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ) -{ +void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ){ dest[ 0 ] = src[ 0 ]; dest[ 1 ] = src[ 1 ]; dest[ 2 ] = src[ 2 ]; } -void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ) -{ +void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ){ dest[ 0 ] = src[ 0 ]; dest[ 1 ] = src[ 1 ]; } -void _pico_copy_vec4( picoVec4_t src, picoVec4_t dest ) -{ +void _pico_copy_vec4( picoVec4_t src, picoVec4_t dest ){ dest[ 0 ] = src[ 0 ]; dest[ 1 ] = src[ 1 ]; dest[ 2 ] = src[ 2 ]; @@ -408,12 +409,13 @@ void _pico_copy_vec4( picoVec4_t src, picoVec4_t dest ) } /* ydnar */ -picoVec_t _pico_normalize_vec( picoVec3_t vec ) -{ - double len, ilen; - +picoVec_t _pico_normalize_vec( picoVec3_t vec ){ + double len, ilen; + len = sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] + vec[ 2 ] * vec[ 2 ] ); - if( len == 0.0 ) return 0.0; + if ( len == 0.0 ) { + return 0.0; + } ilen = 1.0 / len; vec[ 0 ] *= (picoVec_t) ilen; vec[ 1 ] *= (picoVec_t) ilen; @@ -421,50 +423,43 @@ picoVec_t _pico_normalize_vec( picoVec3_t vec ) return (picoVec_t) len; } -void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ) -{ +void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ dest[ 0 ] = a[ 0 ] + b[ 0 ]; dest[ 1 ] = a[ 1 ] + b[ 1 ]; dest[ 2 ] = a[ 2 ] + b[ 2 ]; } -void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ) -{ +void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ dest[ 0 ] = a[ 0 ] - b[ 0 ]; dest[ 1 ] = a[ 1 ] - b[ 1 ]; dest[ 2 ] = a[ 2 ] - b[ 2 ]; } -void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ) -{ +void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ){ dest[ 0 ] = v[ 0 ] * scale; dest[ 1 ] = v[ 1 ] * scale; dest[ 2 ] = v[ 2 ] * scale; } -void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ) -{ +void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ){ dest[ 0 ] = v[ 0 ] * scale; dest[ 1 ] = v[ 1 ] * scale; dest[ 2 ] = v[ 2 ] * scale; dest[ 3 ] = v[ 3 ] * scale; } -picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ) -{ +picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ){ return a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ]; } -void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ) -{ +void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ dest[ 0 ] = a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ]; dest[ 1 ] = a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ]; dest[ 2 ] = a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ]; } -picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ) -{ - picoVec3_t ba, ca; +picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ){ + picoVec3_t ba, ca; _pico_subtract_vec( b, a, ba ); _pico_subtract_vec( c, a, ca ); @@ -474,16 +469,14 @@ picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVe } /* separate from _pico_set_vec4 */ -void _pico_set_color( picoColor_t c, int r, int g, int b, int a ) -{ +void _pico_set_color( picoColor_t c, int r, int g, int b, int a ){ c[ 0 ] = r; c[ 1 ] = g; c[ 2 ] = b; c[ 3 ] = a; } -void _pico_copy_color( picoColor_t src, picoColor_t dest ) -{ +void _pico_copy_color( picoColor_t src, picoColor_t dest ){ dest[ 0 ] = src[ 0 ]; dest[ 1 ] = src[ 1 ]; dest[ 2 ] = src[ 2 ]; @@ -492,26 +485,23 @@ void _pico_copy_color( picoColor_t src, picoColor_t dest ) #ifdef __BIG_ENDIAN__ -int _pico_big_long ( int src ) { return src; } +int _pico_big_long( int src ) { return src; } short _pico_big_short( short src ) { return src; } float _pico_big_float( float src ) { return src; } -int _pico_little_long( int src ) -{ - return ((src & 0xFF000000) >> 24) | - ((src & 0x00FF0000) >> 8) | - ((src & 0x0000FF00) << 8) | - ((src & 0x000000FF) << 24); +int _pico_little_long( int src ){ + return ( ( src & 0xFF000000 ) >> 24 ) | + ( ( src & 0x00FF0000 ) >> 8 ) | + ( ( src & 0x0000FF00 ) << 8 ) | + ( ( src & 0x000000FF ) << 24 ); } -short _pico_little_short( short src ) -{ - return ((src & 0xFF00) >> 8) | - ((src & 0x00FF) << 8); +short _pico_little_short( short src ){ + return ( ( src & 0xFF00 ) >> 8 ) | + ( ( src & 0x00FF ) << 8 ); } -float _pico_little_float( float src ) -{ +float _pico_little_float( float src ){ floatSwapUnion in,out; in.f = src; out.c[ 0 ] = in.c[ 3 ]; @@ -522,26 +512,23 @@ float _pico_little_float( float src ) } #else /*__BIG_ENDIAN__*/ -int _pico_little_long ( int src ) { return src; } +int _pico_little_long( int src ) { return src; } short _pico_little_short( short src ) { return src; } float _pico_little_float( float src ) { return src; } - -int _pico_big_long( int src ) -{ - return ((src & 0xFF000000) >> 24) | - ((src & 0x00FF0000) >> 8) | - ((src & 0x0000FF00) << 8) | - ((src & 0x000000FF) << 24); + +int _pico_big_long( int src ){ + return ( ( src & 0xFF000000 ) >> 24 ) | + ( ( src & 0x00FF0000 ) >> 8 ) | + ( ( src & 0x0000FF00 ) << 8 ) | + ( ( src & 0x000000FF ) << 24 ); } - -short _pico_big_short( short src ) -{ - return ((src & 0xFF00) >> 8) | - ((src & 0x00FF) << 8); + +short _pico_big_short( short src ){ + return ( ( src & 0xFF00 ) >> 8 ) | + ( ( src & 0x00FF ) << 8 ); } - -float _pico_big_float( float src ) -{ + +float _pico_big_float( float src ){ floatSwapUnion in,out; in.f = src; out.c[ 0 ] = in.c[ 3 ]; @@ -555,31 +542,35 @@ float _pico_big_float( float src ) /* _pico_stristr: * case-insensitive strstr. -sea */ -const char *_pico_stristr( const char *str, const char *substr ) -{ - const size_t sublen = strlen(substr); - while (*str) +const char *_pico_stristr( const char *str, const char *substr ){ + const size_t sublen = strlen( substr ); + while ( *str ) { - if (!_pico_strnicmp(str,substr,sublen)) break; + if ( !_pico_strnicmp( str,substr,sublen ) ) { + break; + } str++; } - if (!(*str)) str = NULL; + if ( !( *str ) ) { + str = NULL; + } return str; } /* -_pico_unixify() -changes dos \ style path separators to / -*/ + _pico_unixify() + changes dos \ style path separators to / + */ -void _pico_unixify( char *path ) -{ - if( path == NULL ) +void _pico_unixify( char *path ){ + if ( path == NULL ) { return; - while( *path ) + } + while ( *path ) { - if( *path == '\\' ) + if ( *path == '\\' ) { *path = '/'; + } path++; } } @@ -589,22 +580,19 @@ void _pico_unixify( char *path ) * the directory separators to un*x style. returns 1 on success * or 0 when 'destSize' was exceeded. -sea */ -int _pico_nofname( const char *path, char *dest, int destSize ) -{ - int left = destSize; +int _pico_nofname( const char *path, char *dest, int destSize ){ + int left = destSize; char *temp = dest; - while ((*dest = *path) != '\0') + while ( ( *dest = *path ) != '\0' ) { - if (*dest == '/' || *dest == '\\') - { - temp = (dest + 1); + if ( *dest == '/' || *dest == '\\' ) { + temp = ( dest + 1 ); *dest = '/'; } dest++; path++; - if (--left < 1) - { + if ( --left < 1 ) { *temp = '\0'; return 0; } @@ -617,19 +605,22 @@ int _pico_nofname( const char *path, char *dest, int destSize ) * returns ptr to filename portion in given path or an empty * string otherwise. given 'path' is not altered. -sea */ -const char *_pico_nopath( const char *path ) -{ +const char *_pico_nopath( const char *path ){ const char *src; - src = path + (strlen(path) - 1); + src = path + ( strlen( path ) - 1 ); - if (path == NULL) return ""; - if (!strchr(path,'/') && !strchr(path,'\\')) - return (path); + if ( path == NULL ) { + return ""; + } + if ( !strchr( path,'/' ) && !strchr( path,'\\' ) ) { + return ( path ); + } - while ((src--) != path) + while ( ( src-- ) != path ) { - if (*src == '/' || *src == '\\') - return (++src); + if ( *src == '/' || *src == '\\' ) { + return ( ++src ); + } } return ""; } @@ -639,35 +630,38 @@ const char *_pico_nopath( const char *path ) * or filepath's filename portion. the given 'path' *is* * altered. leave 'ext' empty to remove extension. -sea */ -char *_pico_setfext( char *path, const char *ext ) -{ +char *_pico_setfext( char *path, const char *ext ){ char *src; - int remfext = 0; + int remfext = 0; - src = path + (strlen(path) - 1); + src = path + ( strlen( path ) - 1 ); - if (ext == NULL) ext = ""; - if (strlen(ext ) < 1) remfext = 1; - if (strlen(path) < 1) + if ( ext == NULL ) { + ext = ""; + } + if ( strlen( ext ) < 1 ) { + remfext = 1; + } + if ( strlen( path ) < 1 ) { return path; + } - while ((src--) != path) + while ( ( src-- ) != path ) { - if (*src == '/' || *src == '\\') + if ( *src == '/' || *src == '\\' ) { return path; + } - if (*src == '.') - { - if (remfext) - { + if ( *src == '.' ) { + if ( remfext ) { *src = '\0'; return path; } - *(++src) = '\0'; + *( ++src ) = '\0'; break; } } - strcat(path,ext); + strcat( path,ext ); return path; } @@ -677,22 +671,26 @@ char *_pico_setfext( char *path, const char *ext ) * removed string trimming here. this can be done manually by the * calling func. */ -int _pico_getline( char *buf, int bufsize, char *dest, int destsize ) -{ +int _pico_getline( char *buf, int bufsize, char *dest, int destsize ){ int pos; /* check output */ - if (dest == NULL || destsize < 1) return -1; + if ( dest == NULL || destsize < 1 ) { + return -1; + } memset( dest,0,destsize ); /* check input */ - if (buf == NULL || bufsize < 1) + if ( buf == NULL || bufsize < 1 ) { return -1; + } /* get next line */ - for (pos=0; poscursor == NULL) + if ( p == NULL || p->cursor == NULL ) { return; + } /* skin white spaces */ - while( 1 ) + while ( 1 ) { /* sanity checks */ - if (p->cursor < p->buffer || - p->cursor >= p->max) - { + if ( p->cursor < p->buffer || + p->cursor >= p->max ) { return; } /* break for chars other than white spaces */ - if (*p->cursor > 0x20) break; - if (*p->cursor == 0x00) return; + if ( *p->cursor > 0x20 ) { + break; + } + if ( *p->cursor == 0x00 ) { + return; + } /* a bit of linefeed handling */ - if (*p->cursor == '\n') - { + if ( *p->cursor == '\n' ) { *hasLFs = 1; p->curLine++; } @@ -738,33 +738,34 @@ void _pico_parse_skip_white( picoParser_t *p, int *hasLFs ) /* _pico_new_parser: * allocates a new ascii parser object. */ -picoParser_t *_pico_new_parser( const picoByte_t *buffer, int bufSize ) -{ +picoParser_t *_pico_new_parser( const picoByte_t *buffer, int bufSize ){ picoParser_t *p; - + /* sanity check */ - if( buffer == NULL || bufSize <= 0 ) + if ( buffer == NULL || bufSize <= 0 ) { return NULL; - + } + /* allocate reader */ - p = _pico_alloc( sizeof(picoParser_t) ); - if (p == NULL) return NULL; - memset( p,0,sizeof(picoParser_t) ); + p = _pico_alloc( sizeof( picoParser_t ) ); + if ( p == NULL ) { + return NULL; + } + memset( p,0,sizeof( picoParser_t ) ); /* allocate token space */ p->tokenSize = 0; p->tokenMax = 1024; p->token = _pico_alloc( p->tokenMax ); - if( p->token == NULL ) - { + if ( p->token == NULL ) { _pico_free( p ); return NULL; } /* setup */ - p->buffer = (const char *) buffer; - p->cursor = (const char *) buffer; - p->bufSize = bufSize; - p->max = p->buffer + bufSize; + p->buffer = (const char *) buffer; + p->cursor = (const char *) buffer; + p->bufSize = bufSize; + p->max = p->buffer + bufSize; p->curLine = 1; /* sea: new */ /* return ptr to parser */ @@ -774,14 +775,14 @@ picoParser_t *_pico_new_parser( const picoByte_t *buffer, int bufSize ) /* _pico_free_parser: * frees an existing pico parser object. */ -void _pico_free_parser( picoParser_t *p ) -{ +void _pico_free_parser( picoParser_t *p ){ /* sanity check */ - if (p == NULL) return; + if ( p == NULL ) { + return; + } /* free the parser */ - if (p->token != NULL) - { + if ( p->token != NULL ) { _pico_free( p->token ); } _pico_free( p ); @@ -795,16 +796,14 @@ void _pico_free_parser( picoParser_t *p ) * will handle "quoted" strings and return the data between the * quotes as token. returns 0 on end/error or 1 on success. -sea */ -int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ) -{ +int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ){ int hasLFs = 0; const char *old; /* sanity checks */ - if( p == NULL || p->buffer == NULL || - p->cursor < p->buffer || - p->cursor >= p->max ) - { + if ( p == NULL || p->buffer == NULL || + p->cursor < p->buffer || + p->cursor >= p->max ) { return 0; } /* clear parser token */ @@ -813,43 +812,36 @@ int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ) old = p->cursor; /* skip whitespaces */ - while( p->cursor < p->max && *p->cursor <= 32 ) + while ( p->cursor < p->max && *p->cursor <= 32 ) { - if (*p->cursor == '\n') - { + if ( *p->cursor == '\n' ) { p->curLine++; hasLFs++; } p->cursor++; } /* return if we're not allowed to go beyond lfs */ - if ((hasLFs > 0) && !allowLFs) - { + if ( ( hasLFs > 0 ) && !allowLFs ) { p->cursor = old; return 0; } /* get next quoted string */ - if (*p->cursor == '\"' && handleQuoted) - { + if ( *p->cursor == '\"' && handleQuoted ) { p->cursor++; - while (p->cursor < p->max && *p->cursor) + while ( p->cursor < p->max && *p->cursor ) { - if (*p->cursor == '\\') - { - if (*(p->cursor+1) == '"') - { + if ( *p->cursor == '\\' ) { + if ( *( p->cursor + 1 ) == '"' ) { p->cursor++; } p->token[ p->tokenSize++ ] = *p->cursor++; continue; } - else if (*p->cursor == '\"') - { + else if ( *p->cursor == '\"' ) { p->cursor++; break; } - else if (*p->cursor == '\n') - { + else if ( *p->cursor == '\n' ) { p->curLine++; } p->token[ p->tokenSize++ ] = *p->cursor++; @@ -859,10 +851,9 @@ int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ) return 1; } /* otherwise get next word */ - while( p->cursor < p->max && *p->cursor > 32 ) + while ( p->cursor < p->max && *p->cursor > 32 ) { - if (*p->cursor == '\n') - { + if ( *p->cursor == '\n' ) { p->curLine++; } p->token[ p->tokenSize++ ] = *p->cursor++; @@ -876,14 +867,16 @@ int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ) * reads the first token from the next line and returns * a pointer to it. returns NULL on EOL or EOF. -sea */ -char *_pico_parse_first( picoParser_t *p ) -{ +char *_pico_parse_first( picoParser_t *p ){ /* sanity check */ - if (p == NULL) return NULL; + if ( p == NULL ) { + return NULL; + } /* try to read next token (with lfs & quots) */ - if (!_pico_parse_ex( p,1,1 )) + if ( !_pico_parse_ex( p,1,1 ) ) { return NULL; + } /* return ptr to the token string */ return p->token; @@ -894,14 +887,16 @@ char *_pico_parse_first( picoParser_t *p ) * to it. quoted strings are handled as usual. returns NULL * on EOL or EOF. -sea */ -char *_pico_parse( picoParser_t *p, int allowLFs ) -{ +char *_pico_parse( picoParser_t *p, int allowLFs ){ /* sanity check */ - if (p == NULL) return NULL; + if ( p == NULL ) { + return NULL; + } /* try to read next token (with quots) */ - if (!_pico_parse_ex( p,allowLFs,1 )) + if ( !_pico_parse_ex( p,allowLFs,1 ) ) { return NULL; + } /* return ptr to the token string */ return p->token; @@ -910,9 +905,8 @@ char *_pico_parse( picoParser_t *p, int allowLFs ) /* _pico_parse_skip_rest: * skips the rest of the current line in parser. */ -void _pico_parse_skip_rest( picoParser_t *p ) -{ - while( _pico_parse_ex( p,0,0 ) ) ; +void _pico_parse_skip_rest( picoParser_t *p ){ + while ( _pico_parse_ex( p,0,0 ) ) ; } /* _pico_parse_skip_braced: @@ -921,29 +915,28 @@ void _pico_parse_skip_rest( picoParser_t *p ) * end of buffer was reached or when the opening bracket was * missing). */ -int _pico_parse_skip_braced( picoParser_t *p ) -{ +int _pico_parse_skip_braced( picoParser_t *p ){ int firstToken = 1; int level; /* sanity check */ - if (p == NULL) return 0; + if ( p == NULL ) { + return 0; + } /* set the initial level for parsing */ level = 0; /* skip braced section */ - while( 1 ) + while ( 1 ) { /* read next token (lfs allowed) */ - if (!_pico_parse_ex( p,1,1 )) - { + if ( !_pico_parse_ex( p,1,1 ) ) { /* end of parser buffer reached */ return 0; } /* first token must be an opening bracket */ - if (firstToken && p->token[0] != '{') - { + if ( firstToken && p->token[0] != '{' ) { /* opening bracket missing */ return 0; } @@ -951,126 +944,140 @@ int _pico_parse_skip_braced( picoParser_t *p ) firstToken = 0; /* update level */ - if (p->token[1] == '\0') - { - if (p->token[0] == '{') level++; - if (p->token[0] == '}') level--; + if ( p->token[1] == '\0' ) { + if ( p->token[0] == '{' ) { + level++; + } + if ( p->token[0] == '}' ) { + level--; + } } /* break if we're back at our starting level */ - if (level == 0) break; + if ( level == 0 ) { + break; + } } /* successfully skipped braced section */ return 1; } -int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ) -{ - if (!_pico_parse_ex( p,allowLFs,1 )) +int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ){ + if ( !_pico_parse_ex( p,allowLFs,1 ) ) { return 0; - if (!strcmp(p->token,str)) + } + if ( !strcmp( p->token,str ) ) { return 1; - return 0; + } + return 0; } -int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ) -{ - if (!_pico_parse_ex( p,allowLFs,1 )) +int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ){ + if ( !_pico_parse_ex( p,allowLFs,1 ) ) { return 0; - if (!_pico_stricmp(p->token,str)) + } + if ( !_pico_stricmp( p->token,str ) ) { return 1; - return 0; + } + return 0; } -int _pico_parse_int( picoParser_t *p, int *out ) -{ +int _pico_parse_int( picoParser_t *p, int *out ){ char *token; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* get token and turn it into an integer */ *out = 0; token = _pico_parse( p,0 ); - if (token == NULL) return 0; + if ( token == NULL ) { + return 0; + } *out = atoi( token ); /* success */ return 1; } -int _pico_parse_int_def( picoParser_t *p, int *out, int def ) -{ +int _pico_parse_int_def( picoParser_t *p, int *out, int def ){ char *token; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* get token and turn it into an integer */ *out = def; token = _pico_parse( p,0 ); - if (token == NULL) return 0; + if ( token == NULL ) { + return 0; + } *out = atoi( token ); /* success */ return 1; } -int _pico_parse_float( picoParser_t *p, float *out ) -{ +int _pico_parse_float( picoParser_t *p, float *out ){ char *token; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* get token and turn it into a float */ *out = 0.0f; token = _pico_parse( p,0 ); - if (token == NULL) return 0; + if ( token == NULL ) { + return 0; + } *out = (float) atof( token ); /* success */ return 1; } -int _pico_parse_float_def( picoParser_t *p, float *out, float def ) -{ +int _pico_parse_float_def( picoParser_t *p, float *out, float def ){ char *token; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* get token and turn it into a float */ *out = def; token = _pico_parse( p,0 ); - if (token == NULL) return 0; + if ( token == NULL ) { + return 0; + } *out = (float) atof( token ); /* success */ return 1; } -int _pico_parse_vec( picoParser_t *p, picoVec3_t out ) -{ +int _pico_parse_vec( picoParser_t *p, picoVec3_t out ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* zero out outination vector */ _pico_zero_vec( out ); /* parse three vector components */ - for (i=0; i<3; i++) + for ( i = 0; i < 3; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_zero_vec( out ); return 0; } @@ -1080,24 +1087,23 @@ int _pico_parse_vec( picoParser_t *p, picoVec3_t out ) return 1; } -int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ) -{ +int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* assign default vector value */ _pico_copy_vec( def,out ); /* parse three vector components */ - for (i=0; i<3; i++) + for ( i = 0; i < 3; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_copy_vec( def,out ); return 0; } @@ -1107,24 +1113,23 @@ int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ) return 1; } -int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ) -{ +int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* zero out outination vector */ _pico_zero_vec2( out ); /* parse two vector components */ - for (i=0; i<2; i++) + for ( i = 0; i < 2; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_zero_vec2( out ); return 0; } @@ -1134,24 +1139,23 @@ int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ) return 1; } -int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ) -{ +int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* assign default vector value */ _pico_copy_vec2( def,out ); /* parse two vector components */ - for (i=0; i<2; i++) + for ( i = 0; i < 2; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_copy_vec2( def,out ); return 0; } @@ -1161,24 +1165,23 @@ int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ) return 1; } -int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ) -{ +int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* zero out outination vector */ _pico_zero_vec4( out ); /* parse four vector components */ - for (i=0; i<4; i++) + for ( i = 0; i < 4; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_zero_vec4( out ); return 0; } @@ -1188,24 +1191,23 @@ int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ) return 1; } -int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ) -{ +int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ){ char *token; - int i; + int i; /* sanity checks */ - if (p == NULL || out == NULL) + if ( p == NULL || out == NULL ) { return 0; + } /* assign default vector value */ _pico_copy_vec4( def,out ); /* parse four vector components */ - for (i=0; i<4; i++) + for ( i = 0; i < 4; i++ ) { token = _pico_parse( p,0 ); - if (token == NULL) - { + if ( token == NULL ) { _pico_copy_vec4( def,out ); return 0; } @@ -1218,24 +1220,26 @@ int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ) /* _pico_new_memstream: * allocates a new memorystream object. */ -picoMemStream_t *_pico_new_memstream( const picoByte_t *buffer, int bufSize ) -{ +picoMemStream_t *_pico_new_memstream( const picoByte_t *buffer, int bufSize ){ picoMemStream_t *s; - + /* sanity check */ - if( buffer == NULL || bufSize <= 0 ) + if ( buffer == NULL || bufSize <= 0 ) { return NULL; - + } + /* allocate stream */ - s = _pico_alloc( sizeof(picoMemStream_t) ); - if (s == NULL) return NULL; - memset( s,0,sizeof(picoMemStream_t) ); + s = _pico_alloc( sizeof( picoMemStream_t ) ); + if ( s == NULL ) { + return NULL; + } + memset( s,0,sizeof( picoMemStream_t ) ); /* setup */ - s->buffer = buffer; - s->curPos = buffer; - s->bufSize = bufSize; - s->flag = 0; + s->buffer = buffer; + s->curPos = buffer; + s->bufSize = bufSize; + s->flag = 0; /* return ptr to stream */ return s; @@ -1244,10 +1248,11 @@ picoMemStream_t *_pico_new_memstream( const picoByte_t *buffer, int bufSize ) /* _pico_free_memstream: * frees an existing pico memorystream object. */ -void _pico_free_memstream( picoMemStream_t *s ) -{ +void _pico_free_memstream( picoMemStream_t *s ){ /* sanity check */ - if (s == NULL) return; + if ( s == NULL ) { + return; + } /* free the stream */ _pico_free( s ); @@ -1256,16 +1261,15 @@ void _pico_free_memstream( picoMemStream_t *s ) /* _pico_memstream_read: * reads data from a pico memorystream into a buffer. */ -int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ) -{ +int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ){ int ret = 1; /* sanity checks */ - if (s == NULL || buffer == NULL) + if ( s == NULL || buffer == NULL ) { return 0; + } - if (s->curPos + len > s->buffer + s->bufSize) - { + if ( s->curPos + len > s->buffer + s->bufSize ) { s->flag |= PICO_IOEOF; len = s->buffer + s->bufSize - s->curPos; ret = 0; @@ -1280,17 +1284,18 @@ int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ) /* _pico_memstream_read: * reads a character from a pico memorystream */ -int _pico_memstream_getc( picoMemStream_t *s ) -{ +int _pico_memstream_getc( picoMemStream_t *s ){ int c = 0; /* sanity check */ - if (s == NULL) + if ( s == NULL ) { return -1; + } /* read the character */ - if (_pico_memstream_read( s, &c, 1) == 0) + if ( _pico_memstream_read( s, &c, 1 ) == 0 ) { return -1; + } return c; } @@ -1298,42 +1303,36 @@ int _pico_memstream_getc( picoMemStream_t *s ) /* _pico_memstream_seek: * sets the current read position to a different location */ -int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ) -{ +int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ){ int overflow; /* sanity check */ - if (s == NULL) + if ( s == NULL ) { return -1; + } - if (origin == PICO_SEEK_SET) - { + if ( origin == PICO_SEEK_SET ) { s->curPos = s->buffer + offset; overflow = s->curPos - ( s->buffer + s->bufSize ); - if (overflow > 0) - { + if ( overflow > 0 ) { s->curPos = s->buffer + s->bufSize; return offset - overflow; } return 0; } - else if (origin == PICO_SEEK_CUR) - { + else if ( origin == PICO_SEEK_CUR ) { s->curPos += offset; overflow = s->curPos - ( s->buffer + s->bufSize ); - if (overflow > 0) - { + if ( overflow > 0 ) { s->curPos = s->buffer + s->bufSize; return offset - overflow; } return 0; } - else if (origin == PICO_SEEK_END) - { + else if ( origin == PICO_SEEK_END ) { s->curPos = ( s->buffer + s->bufSize ) - offset; overflow = s->buffer - s->curPos; - if (overflow > 0) - { + if ( overflow > 0 ) { s->curPos = s->buffer; return offset - overflow; } @@ -1346,11 +1345,11 @@ int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ) /* _pico_memstream_tell: * returns the current read position in the pico memorystream */ -long _pico_memstream_tell( picoMemStream_t *s ) -{ +long _pico_memstream_tell( picoMemStream_t *s ){ /* sanity check */ - if (s == NULL) + if ( s == NULL ) { return -1; + } return s->curPos - s->buffer; } diff --git a/libs/picomodel/picointernal.h b/libs/picomodel/picointernal.h index 10769e33..07c24cb5 100644 --- a/libs/picomodel/picointernal.h +++ b/libs/picomodel/picointernal.h @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -66,137 +66,137 @@ extern "C" /* constants */ -#define PICO_PI 3.14159265358979323846 +#define PICO_PI 3.14159265358979323846 #define PICO_SEEK_SET 0 #define PICO_SEEK_CUR 1 #define PICO_SEEK_END 2 -#define PICO_IOEOF 1 -#define PICO_IOERR 2 +#define PICO_IOEOF 1 +#define PICO_IOERR 2 /* types */ typedef struct picoParser_s { - const char *buffer; - int bufSize; - char *token; - int tokenSize; - int tokenMax; - const char *cursor; - const char *max; - int curLine; + const char *buffer; + int bufSize; + char *token; + int tokenSize; + int tokenMax; + const char *cursor; + const char *max; + int curLine; } picoParser_t; typedef struct picoMemStream_s { - const picoByte_t *buffer; - int bufSize; - const picoByte_t *curPos; - int flag; + const picoByte_t *buffer; + int bufSize; + const picoByte_t *curPos; + int flag; } picoMemStream_t; /* variables */ -extern const picoModule_t *picoModules[]; +extern const picoModule_t *picoModules[]; -extern void *(*_pico_ptr_malloc)( size_t ); -extern void (*_pico_ptr_free)( void* ); -extern void (*_pico_ptr_load_file)( const char*, unsigned char**, int* ); -extern void (*_pico_ptr_free_file)( void* ); -extern void (*_pico_ptr_print)( int, const char* ); +extern void *( *_pico_ptr_malloc )( size_t ); +extern void ( *_pico_ptr_free )( void* ); +extern void ( *_pico_ptr_load_file )( const char*, unsigned char**, int* ); +extern void ( *_pico_ptr_free_file )( void* ); +extern void ( *_pico_ptr_print )( int, const char* ); /* prototypes */ /* memory */ -void *_pico_alloc( size_t size ); -void *_pico_calloc( size_t num, size_t size ); -void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ); -char *_pico_clone_alloc( const char *str ); -void _pico_free( void *ptr ); +void *_pico_alloc( size_t size ); +void *_pico_calloc( size_t num, size_t size ); +void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ); +char *_pico_clone_alloc( const char *str ); +void _pico_free( void *ptr ); /* files */ -void _pico_load_file( const char *name, unsigned char **buffer, int *bufSize ); -void _pico_free_file( void *buffer ); +void _pico_load_file( const char *name, unsigned char **buffer, int *bufSize ); +void _pico_free_file( void *buffer ); /* strings */ -void _pico_first_token( char *str ); -char *_pico_strltrim( char *str ); -char *_pico_strrtrim( char *str ); -int _pico_strchcount( char *str, int ch ); -void _pico_printf( int level, const char *format, ... ); -const char *_pico_stristr( const char *str, const char *substr ); -void _pico_unixify( char *path ); -int _pico_nofname( const char *path, char *dest, int destSize ); +void _pico_first_token( char *str ); +char *_pico_strltrim( char *str ); +char *_pico_strrtrim( char *str ); +int _pico_strchcount( char *str, int ch ); +void _pico_printf( int level, const char *format, ... ); +const char *_pico_stristr( const char *str, const char *substr ); +void _pico_unixify( char *path ); +int _pico_nofname( const char *path, char *dest, int destSize ); const char *_pico_nopath( const char *path ); -char *_pico_setfext( char *path, const char *ext ); -int _pico_getline( char *buf, int bufsize, char *dest, int destsize ); -char *_pico_strlwr( char *str ); +char *_pico_setfext( char *path, const char *ext ); +int _pico_getline( char *buf, int bufsize, char *dest, int destsize ); +char *_pico_strlwr( char *str ); /* vectors */ -void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ); -void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ); -void _pico_zero_vec( picoVec3_t vec ); -void _pico_zero_vec2( picoVec2_t vec ); -void _pico_zero_vec4( picoVec4_t vec ); -void _pico_set_vec( picoVec3_t v, float a, float b, float c ); -void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ); -void _pico_set_color( picoColor_t c, int r, int g, int b, int a ); -void _pico_copy_color( picoColor_t src, picoColor_t dest ); -void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ); -void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ); -picoVec_t _pico_normalize_vec( picoVec3_t vec ); -void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ); -void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ); -void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ); -void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ); +void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ); +void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ); +void _pico_zero_vec( picoVec3_t vec ); +void _pico_zero_vec2( picoVec2_t vec ); +void _pico_zero_vec4( picoVec4_t vec ); +void _pico_set_vec( picoVec3_t v, float a, float b, float c ); +void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ); +void _pico_set_color( picoColor_t c, int r, int g, int b, int a ); +void _pico_copy_color( picoColor_t src, picoColor_t dest ); +void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ); +void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ); +picoVec_t _pico_normalize_vec( picoVec3_t vec ); +void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); +void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); +picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ); +void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); +picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ); +void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ); +void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ); /* endian */ -int _pico_big_long( int src ); -short _pico_big_short( short src ); -float _pico_big_float( float src ); +int _pico_big_long( int src ); +short _pico_big_short( short src ); +float _pico_big_float( float src ); -int _pico_little_long( int src ); -short _pico_little_short( short src ); -float _pico_little_float( float src ); +int _pico_little_long( int src ); +short _pico_little_short( short src ); +float _pico_little_float( float src ); /* pico ascii parser */ -picoParser_t *_pico_new_parser( const picoByte_t *buffer, int bufSize ); -void _pico_free_parser( picoParser_t *p ); -int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ); -char *_pico_parse_first( picoParser_t *p ); -char *_pico_parse( picoParser_t *p, int allowLFs ); -void _pico_parse_skip_rest( picoParser_t *p ); -int _pico_parse_skip_braced( picoParser_t *p ); -int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ); -int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ); -int _pico_parse_int( picoParser_t *p, int *out ); -int _pico_parse_int_def( picoParser_t *p, int *out, int def ); -int _pico_parse_float( picoParser_t *p, float *out ); -int _pico_parse_float_def( picoParser_t *p, float *out, float def ); -int _pico_parse_vec( picoParser_t *p, picoVec3_t out); -int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def); -int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ); -int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ); -int _pico_parse_vec4( picoParser_t *p, picoVec4_t out); -int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def); +picoParser_t *_pico_new_parser( const picoByte_t *buffer, int bufSize ); +void _pico_free_parser( picoParser_t *p ); +int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ); +char *_pico_parse_first( picoParser_t *p ); +char *_pico_parse( picoParser_t *p, int allowLFs ); +void _pico_parse_skip_rest( picoParser_t *p ); +int _pico_parse_skip_braced( picoParser_t *p ); +int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ); +int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ); +int _pico_parse_int( picoParser_t *p, int *out ); +int _pico_parse_int_def( picoParser_t *p, int *out, int def ); +int _pico_parse_float( picoParser_t *p, float *out ); +int _pico_parse_float_def( picoParser_t *p, float *out, float def ); +int _pico_parse_vec( picoParser_t *p, picoVec3_t out ); +int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ); +int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ); +int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ); +int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ); +int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ); /* pico memory stream */ -picoMemStream_t *_pico_new_memstream( const picoByte_t *buffer, int bufSize ); -void _pico_free_memstream( picoMemStream_t *s ); -int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ); -int _pico_memstream_getc( picoMemStream_t *s ); -int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ); -long _pico_memstream_tell( picoMemStream_t *s ); -#define _pico_memstream_eof( _pico_memstream ) ((_pico_memstream)->flag & PICO_IOEOF) -#define _pico_memstream_error( _pico_memstream ) ((_pico_memstream)->flag & PICO_IOERR) +picoMemStream_t *_pico_new_memstream( const picoByte_t *buffer, int bufSize ); +void _pico_free_memstream( picoMemStream_t *s ); +int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ); +int _pico_memstream_getc( picoMemStream_t *s ); +int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ); +long _pico_memstream_tell( picoMemStream_t *s ); +#define _pico_memstream_eof( _pico_memstream ) ( ( _pico_memstream )->flag & PICO_IOEOF ) +#define _pico_memstream_error( _pico_memstream ) ( ( _pico_memstream )->flag & PICO_IOERR ) /* end marker */ #ifdef __cplusplus diff --git a/libs/picomodel/picomodel.c b/libs/picomodel/picomodel.c index 86ec08bd..4526745c 100644 --- a/libs/picomodel/picomodel.c +++ b/libs/picomodel/picomodel.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -45,12 +45,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* -PicoInit() -initializes the picomodel library -*/ + PicoInit() + initializes the picomodel library + */ -int PicoInit( void ) -{ +int PicoInit( void ){ /* successfully initialized -sea */ return 1; } @@ -58,12 +57,11 @@ int PicoInit( void ) /* -PicoShutdown() -shuts the pico model library down -*/ + PicoShutdown() + shuts the pico model library down + */ -void PicoShutdown( void ) -{ +void PicoShutdown( void ){ /* do something interesting here in the future */ return; } @@ -71,12 +69,11 @@ void PicoShutdown( void ) /* -PicoError() -returns last picomodel error code (see PME_* defines) -*/ + PicoError() + returns last picomodel error code (see PME_* defines) + */ -int PicoError( void ) -{ +int PicoError( void ){ /* todo: do something here */ return 0; } @@ -84,98 +81,93 @@ int PicoError( void ) /* -PicoSetMallocFunc() -sets the ptr to the malloc function -*/ + PicoSetMallocFunc() + sets the ptr to the malloc function + */ -void PicoSetMallocFunc( void *(*func)( size_t ) ) -{ - if( func != NULL ) +void PicoSetMallocFunc( void *( *func )( size_t ) ){ + if ( func != NULL ) { _pico_ptr_malloc = func; + } } /* -PicoSetFreeFunc() -sets the ptr to the free function -*/ + PicoSetFreeFunc() + sets the ptr to the free function + */ -void PicoSetFreeFunc( void (*func)( void* ) ) -{ - if( func != NULL ) +void PicoSetFreeFunc( void ( *func )( void* ) ){ + if ( func != NULL ) { _pico_ptr_free = func; + } } /* -PicoSetLoadFileFunc() -sets the ptr to the file load function -*/ + PicoSetLoadFileFunc() + sets the ptr to the file load function + */ -void PicoSetLoadFileFunc( void (*func)( const char*, unsigned char**, int* ) ) -{ - if( func != NULL ) +void PicoSetLoadFileFunc( void ( *func )( const char*, unsigned char**, int* ) ){ + if ( func != NULL ) { _pico_ptr_load_file = func; + } } /* -PicoSetFreeFileFunc() -sets the ptr to the free function -*/ + PicoSetFreeFileFunc() + sets the ptr to the free function + */ -void PicoSetFreeFileFunc( void (*func)( void* ) ) -{ - if( func != NULL ) +void PicoSetFreeFileFunc( void ( *func )( void* ) ){ + if ( func != NULL ) { _pico_ptr_free_file = func; + } } /* -PicoSetPrintFunc() -sets the ptr to the print function -*/ + PicoSetPrintFunc() + sets the ptr to the print function + */ -void PicoSetPrintFunc( void (*func)( int, const char* ) ) -{ - if( func != NULL ) +void PicoSetPrintFunc( void ( *func )( int, const char* ) ){ + if ( func != NULL ) { _pico_ptr_print = func; + } } -picoModel_t *PicoModuleLoadModel( const picoModule_t* pm, const char* fileName, picoByte_t* buffer, int bufSize, int frameNum ) -{ - char *modelFileName, *remapFileName; +picoModel_t *PicoModuleLoadModel( const picoModule_t* pm, const char* fileName, picoByte_t* buffer, int bufSize, int frameNum ){ + char *modelFileName, *remapFileName; /* see whether this module can load the model file or not */ - if( pm->canload( fileName, buffer, bufSize ) == PICO_PMV_OK ) - { + if ( pm->canload( fileName, buffer, bufSize ) == PICO_PMV_OK ) { /* use loader provided by module to read the model data */ picoModel_t* model = pm->load( fileName, frameNum, buffer, bufSize ); - if( model == NULL ) - { + if ( model == NULL ) { _pico_free_file( buffer ); return NULL; } - + /* assign pointer to file format module */ model->module = pm; - + /* get model file name */ modelFileName = PicoGetModelFileName( model ); - + /* apply model remappings from .remap */ - if( strlen( modelFileName ) ) - { + if ( strlen( modelFileName ) ) { /* alloc copy of model file name */ remapFileName = _pico_alloc( strlen( modelFileName ) + 20 ); - if( remapFileName != NULL ) - { + if ( remapFileName != NULL ) { /* copy model file name and change extension */ strcpy( remapFileName, modelFileName ); _pico_setfext( remapFileName, "remap" ); @@ -195,103 +187,98 @@ picoModel_t *PicoModuleLoadModel( const picoModule_t* pm, const char* fileName, } /* -PicoLoadModel() -the meat and potatoes function -*/ + PicoLoadModel() + the meat and potatoes function + */ + +picoModel_t *PicoLoadModel( const char *fileName, int frameNum ){ + const picoModule_t **modules, *pm; + picoModel_t *model; + picoByte_t *buffer; + int bufSize; -picoModel_t *PicoLoadModel( const char *fileName, int frameNum ) -{ - const picoModule_t **modules, *pm; - picoModel_t *model; - picoByte_t *buffer; - int bufSize; - /* init */ model = NULL; - + /* make sure we've got a file name */ - if( fileName == NULL ) - { + if ( fileName == NULL ) { _pico_printf( PICO_ERROR, "PicoLoadModel: No filename given (fileName == NULL)" ); return NULL; } - + /* load file data (buffer is allocated by host app) */ _pico_load_file( fileName, &buffer, &bufSize ); - if( bufSize < 0 ) - { + if ( bufSize < 0 ) { _pico_printf( PICO_ERROR, "PicoLoadModel: Failed loading model %s", fileName ); return NULL; } /* get ptr to list of supported modules */ modules = PicoModuleList( NULL ); - + /* run it through the various loader functions and try */ /* to find a loader that fits the given file data */ - for( ; *modules != NULL; modules++ ) + for ( ; *modules != NULL; modules++ ) { /* get module */ pm = *modules; - + /* sanity check */ - if( pm == NULL) + if ( pm == NULL ) { break; + } /* module must be able to load */ - if( pm->canload == NULL || pm->load == NULL ) + if ( pm->canload == NULL || pm->load == NULL ) { continue; - - model = PicoModuleLoadModel(pm, fileName, buffer, bufSize, frameNum); - if(model != NULL) - { + } + + model = PicoModuleLoadModel( pm, fileName, buffer, bufSize, frameNum ); + if ( model != NULL ) { /* model was loaded, so break out of loop */ break; } } - + /* free memory used by file buffer */ - if( buffer) + if ( buffer ) { _pico_free_file( buffer ); + } /* return */ return model; } -picoModel_t *PicoModuleLoadModelStream( const picoModule_t* module, void* inputStream, PicoInputStreamReadFunc inputStreamRead, size_t streamLength, int frameNum, const char *fileName ) -{ - picoModel_t *model; - picoByte_t *buffer; - int bufSize; +picoModel_t *PicoModuleLoadModelStream( const picoModule_t* module, void* inputStream, PicoInputStreamReadFunc inputStreamRead, size_t streamLength, int frameNum, const char *fileName ){ + picoModel_t *model; + picoByte_t *buffer; + int bufSize; + - /* init */ model = NULL; - - if( inputStream == NULL ) - { + + if ( inputStream == NULL ) { _pico_printf( PICO_ERROR, "PicoLoadModel: invalid input stream (inputStream == NULL)" ); return NULL; } - - if( inputStreamRead == NULL ) - { + + if ( inputStreamRead == NULL ) { _pico_printf( PICO_ERROR, "PicoLoadModel: invalid input stream (inputStreamRead == NULL)" ); return NULL; } - - buffer = _pico_alloc(streamLength + 1); - bufSize = (int)inputStreamRead(inputStream, buffer, streamLength); + buffer = _pico_alloc( streamLength + 1 ); + + bufSize = (int)inputStreamRead( inputStream, buffer, streamLength ); buffer[bufSize] = '\0'; - model = PicoModuleLoadModel(module, fileName, buffer, bufSize, frameNum); - - if(model != 0) - { - _pico_free(buffer); - } + model = PicoModuleLoadModel( module, fileName, buffer, bufSize, frameNum ); + + if ( model != 0 ) { + _pico_free( buffer ); + } /* return */ return model; @@ -299,26 +286,26 @@ picoModel_t *PicoModuleLoadModelStream( const picoModule_t* module, void* inputS /* ---------------------------------------------------------------------------- -models ----------------------------------------------------------------------------- */ + models + ---------------------------------------------------------------------------- */ /* -PicoNewModel() -creates a new pico model -*/ + PicoNewModel() + creates a new pico model + */ + +picoModel_t *PicoNewModel( void ){ + picoModel_t *model; -picoModel_t *PicoNewModel( void ) -{ - picoModel_t *model; - /* allocate */ - model = _pico_alloc( sizeof(picoModel_t) ); - if( model == NULL ) + model = _pico_alloc( sizeof( picoModel_t ) ); + if ( model == NULL ) { return NULL; + } /* clear */ - memset( model,0,sizeof(picoModel_t) ); - + memset( model,0,sizeof( picoModel_t ) ); + /* model set up */ _pico_zero_bounds( model->mins,model->maxs ); @@ -332,36 +319,38 @@ picoModel_t *PicoNewModel( void ) /* -PicoFreeModel() -frees a model and all associated data -*/ + PicoFreeModel() + frees a model and all associated data + */ + +void PicoFreeModel( picoModel_t *model ){ + int i; -void PicoFreeModel( picoModel_t *model ) -{ - int i; - /* sanity check */ - if( model == NULL ) + if ( model == NULL ) { return; - + } + /* free bits */ - if( model->name ) + if ( model->name ) { _pico_free( model->name ); - - if( model->fileName ) + } + + if ( model->fileName ) { _pico_free( model->fileName ); - + } + /* free shaders */ - for( i = 0; i < model->numShaders; i++ ) + for ( i = 0; i < model->numShaders; i++ ) PicoFreeShader( model->shader[ i ] ); free( model->shader ); - + /* free surfaces */ - for( i = 0; i < model->numSurfaces; i++ ) + for ( i = 0; i < model->numSurfaces; i++ ) PicoFreeSurface( model->surface[ i ] ); free( model->surface ); - + /* free the model */ _pico_free( model ); } @@ -369,48 +358,54 @@ void PicoFreeModel( picoModel_t *model ) /* -PicoAdjustModel() -adjusts a models's memory allocations to handle the requested sizes. -will always grow, never shrink -*/ + PicoAdjustModel() + adjusts a models's memory allocations to handle the requested sizes. + will always grow, never shrink + */ -int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ) -{ +int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ){ /* dummy check */ - if( model == NULL ) + if ( model == NULL ) { return 0; - + } + /* bare minimums */ /* sea: null surface/shader fix (1s=>0s) */ - if( numShaders < 0 ) + if ( numShaders < 0 ) { numShaders = 0; - if( numSurfaces < 0 ) + } + if ( numSurfaces < 0 ) { numSurfaces = 0; + } /* additional shaders? */ - while( numShaders > model->maxShaders ) + while ( numShaders > model->maxShaders ) { model->maxShaders += PICO_GROW_SHADERS; - if( !_pico_realloc( (void *) &model->shader, model->numShaders * sizeof( *model->shader ), model->maxShaders * sizeof( *model->shader ) ) ) + if ( !_pico_realloc( (void *) &model->shader, model->numShaders * sizeof( *model->shader ), model->maxShaders * sizeof( *model->shader ) ) ) { return 0; + } } - + /* set shader count to higher */ - if( numShaders > model->numShaders ) + if ( numShaders > model->numShaders ) { model->numShaders = numShaders; - + } + /* additional surfaces? */ - while( numSurfaces > model->maxSurfaces ) + while ( numSurfaces > model->maxSurfaces ) { model->maxSurfaces += PICO_GROW_SURFACES; - if( !_pico_realloc( (void *) &model->surface, model->numSurfaces * sizeof( *model->surface ), model->maxSurfaces * sizeof( *model->surface ) ) ) + if ( !_pico_realloc( (void *) &model->surface, model->numSurfaces * sizeof( *model->surface ), model->maxSurfaces * sizeof( *model->surface ) ) ) { return 0; + } } - + /* set shader count to higher */ - if( numSurfaces > model->numSurfaces ) + if ( numSurfaces > model->numSurfaces ) { model->numSurfaces = numSurfaces; - + } + /* return ok */ return 1; } @@ -418,49 +413,47 @@ int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ) /* ---------------------------------------------------------------------------- -shaders ----------------------------------------------------------------------------- */ + shaders + ---------------------------------------------------------------------------- */ /* -PicoNewShader() -creates a new pico shader and returns its index. -sea -*/ + PicoNewShader() + creates a new pico shader and returns its index. -sea + */ + +picoShader_t *PicoNewShader( picoModel_t *model ){ + picoShader_t *shader; + -picoShader_t *PicoNewShader( picoModel_t *model ) -{ - picoShader_t *shader; - - /* allocate and clear */ - shader = _pico_alloc( sizeof(picoShader_t) ); - if( shader == NULL ) + shader = _pico_alloc( sizeof( picoShader_t ) ); + if ( shader == NULL ) { return NULL; - memset( shader, 0, sizeof(picoShader_t) ); - + } + memset( shader, 0, sizeof( picoShader_t ) ); + /* attach it to the model */ - if( model != NULL ) - { + if ( model != NULL ) { /* adjust model */ - if( !PicoAdjustModel( model, model->numShaders + 1, 0 ) ) - { + if ( !PicoAdjustModel( model, model->numShaders + 1, 0 ) ) { _pico_free( shader ); return NULL; } - + /* attach */ model->shader[ model->numShaders - 1 ] = shader; shader->model = model; } - + /* setup default shader colors */ _pico_set_color( shader->ambientColor,0,0,0,0 ); _pico_set_color( shader->diffuseColor,255,255,255,1 ); _pico_set_color( shader->specularColor,0,0,0,0 ); - + /* no need to do this, but i do it anyway */ shader->transparency = 0; shader->shininess = 0; - + /* return the newly created shader */ return shader; } @@ -468,22 +461,24 @@ picoShader_t *PicoNewShader( picoModel_t *model ) /* -PicoFreeShader() -frees a shader and all associated data -sea -*/ + PicoFreeShader() + frees a shader and all associated data -sea + */ -void PicoFreeShader( picoShader_t *shader ) -{ +void PicoFreeShader( picoShader_t *shader ){ /* dummy check */ - if( shader == NULL ) + if ( shader == NULL ) { return; - + } + /* free bits */ - if( shader->name ) + if ( shader->name ) { _pico_free( shader->name ); - if( shader->mapName ) + } + if ( shader->mapName ) { _pico_free( shader->mapName ); - + } + /* free the shader */ _pico_free( shader ); } @@ -491,37 +486,39 @@ void PicoFreeShader( picoShader_t *shader ) /* -PicoFindShader() -finds a named shader in a model -*/ + PicoFindShader() + finds a named shader in a model + */ + +picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ){ + int i; + -picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ) -{ - int i; - - /* sanity checks */ - if( model == NULL || name == NULL ) /* sea: null name fix */ + if ( model == NULL || name == NULL ) { /* sea: null name fix */ return NULL; - + } + /* walk list */ - for( i = 0; i < model->numShaders; i++ ) + for ( i = 0; i < model->numShaders; i++ ) { /* skip null shaders or shaders with null names */ - if( model->shader[ i ] == NULL || - model->shader[ i ]->name == NULL ) + if ( model->shader[ i ] == NULL || + model->shader[ i ]->name == NULL ) { continue; + } /* compare the shader name with name we're looking for */ - if( caseSensitive ) - { - if( !strcmp( name, model->shader[ i ]->name ) ) + if ( caseSensitive ) { + if ( !strcmp( name, model->shader[ i ]->name ) ) { return model->shader[ i ]; + } + } + else if ( !_pico_stricmp( name, model->shader[ i ]->name ) ) { + return model->shader[ i ]; } - else if( !_pico_stricmp( name, model->shader[ i ]->name ) ) - return model->shader[ i ]; } - + /* named shader not found */ return NULL; } @@ -529,44 +526,42 @@ picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive /* ---------------------------------------------------------------------------- -surfaces ----------------------------------------------------------------------------- */ + surfaces + ---------------------------------------------------------------------------- */ /* -PicoNewSurface() -creates a new pico surface -*/ + PicoNewSurface() + creates a new pico surface + */ -picoSurface_t *PicoNewSurface( picoModel_t *model ) -{ - picoSurface_t *surface; +picoSurface_t *PicoNewSurface( picoModel_t *model ){ + picoSurface_t *surface; char surfaceName[64]; - + /* allocate and clear */ surface = _pico_alloc( sizeof( *surface ) ); - if( surface == NULL ) + if ( surface == NULL ) { return NULL; + } memset( surface, 0, sizeof( *surface ) ); - + /* attach it to the model */ - if( model != NULL ) - { + if ( model != NULL ) { /* adjust model */ - if( !PicoAdjustModel( model, 0, model->numSurfaces + 1 ) ) - { + if ( !PicoAdjustModel( model, 0, model->numSurfaces + 1 ) ) { _pico_free( surface ); return NULL; } - + /* attach */ model->surface[ model->numSurfaces - 1 ] = surface; surface->model = model; - + /* set default name */ sprintf( surfaceName, "Unnamed_%d", model->numSurfaces ); PicoSetSurfaceName( surface, surfaceName ); } - + /* return */ return surface; } @@ -574,18 +569,18 @@ picoSurface_t *PicoNewSurface( picoModel_t *model ) /* -PicoFreeSurface() -frees a surface and all associated data -*/ -void PicoFreeSurface( picoSurface_t *surface ) -{ - int i; - - + PicoFreeSurface() + frees a surface and all associated data + */ +void PicoFreeSurface( picoSurface_t *surface ){ + int i; + + /* dummy check */ - if( surface == NULL ) + if ( surface == NULL ) { return; - + } + /* free bits */ _pico_free( surface->xyz ); _pico_free( surface->normal ); @@ -593,17 +588,18 @@ void PicoFreeSurface( picoSurface_t *surface ) _pico_free( surface->index ); _pico_free( surface->faceNormal ); - if( surface->name ) - _pico_free( surface->name ); - + if ( surface->name ) { + _pico_free( surface->name ); + } + /* free arrays */ - for( i = 0; i < surface->numSTArrays; i++ ) + for ( i = 0; i < surface->numSTArrays; i++ ) _pico_free( surface->st[ i ] ); free( surface->st ); - for( i = 0; i < surface->numColorArrays; i++ ) + for ( i = 0; i < surface->numColorArrays; i++ ) _pico_free( surface->color[ i ] ); free( surface->color ); - + /* free the surface */ _pico_free( surface ); } @@ -611,103 +607,119 @@ void PicoFreeSurface( picoSurface_t *surface ) /* -PicoAdjustSurface() -adjusts a surface's memory allocations to handle the requested sizes. -will always grow, never shrink -*/ + PicoAdjustSurface() + adjusts a surface's memory allocations to handle the requested sizes. + will always grow, never shrink + */ + +int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ){ + int i; + -int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ) -{ - int i; - - /* dummy check */ - if( surface == NULL ) + if ( surface == NULL ) { return 0; - + } + /* bare minimums */ - if( numVertexes < 1 ) + if ( numVertexes < 1 ) { numVertexes = 1; - if( numSTArrays < 1 ) + } + if ( numSTArrays < 1 ) { numSTArrays = 1; - if( numColorArrays < 1 ) + } + if ( numColorArrays < 1 ) { numColorArrays = 1; - if( numIndexes < 1 ) + } + if ( numIndexes < 1 ) { numIndexes = 1; - + } + /* additional vertexes? */ - while( numVertexes > surface->maxVertexes ) /* fix */ + while ( numVertexes > surface->maxVertexes ) /* fix */ { surface->maxVertexes += PICO_GROW_VERTEXES; - if( !_pico_realloc( (void *) &surface->xyz, surface->numVertexes * sizeof( *surface->xyz ), surface->maxVertexes * sizeof( *surface->xyz ) ) ) - return 0; - if( !_pico_realloc( (void *) &surface->normal, surface->numVertexes * sizeof( *surface->normal ), surface->maxVertexes * sizeof( *surface->normal ) ) ) + if ( !_pico_realloc( (void *) &surface->xyz, surface->numVertexes * sizeof( *surface->xyz ), surface->maxVertexes * sizeof( *surface->xyz ) ) ) { return 0; - if( !_pico_realloc( (void *) &surface->smoothingGroup, surface->numVertexes * sizeof( *surface->smoothingGroup ), surface->maxVertexes * sizeof( *surface->smoothingGroup ) ) ) - return 0; - for( i = 0; i < surface->numSTArrays; i++ ) - if( !_pico_realloc( (void*) &surface->st[ i ], surface->numVertexes * sizeof( *surface->st[ i ] ), surface->maxVertexes * sizeof( *surface->st[ i ] ) ) ) + } + if ( !_pico_realloc( (void *) &surface->normal, surface->numVertexes * sizeof( *surface->normal ), surface->maxVertexes * sizeof( *surface->normal ) ) ) { return 0; - for( i = 0; i < surface->numColorArrays; i++ ) - if( !_pico_realloc( (void*) &surface->color[ i ], surface->numVertexes * sizeof( *surface->color[ i ] ), surface->maxVertexes * sizeof( *surface->color[ i ] ) ) ) + } + if ( !_pico_realloc( (void *) &surface->smoothingGroup, surface->numVertexes * sizeof( *surface->smoothingGroup ), surface->maxVertexes * sizeof( *surface->smoothingGroup ) ) ) { return 0; + } + for ( i = 0; i < surface->numSTArrays; i++ ) + if ( !_pico_realloc( (void*) &surface->st[ i ], surface->numVertexes * sizeof( *surface->st[ i ] ), surface->maxVertexes * sizeof( *surface->st[ i ] ) ) ) { + return 0; + } + for ( i = 0; i < surface->numColorArrays; i++ ) + if ( !_pico_realloc( (void*) &surface->color[ i ], surface->numVertexes * sizeof( *surface->color[ i ] ), surface->maxVertexes * sizeof( *surface->color[ i ] ) ) ) { + return 0; + } } - + /* set vertex count to higher */ - if( numVertexes > surface->numVertexes ) + if ( numVertexes > surface->numVertexes ) { surface->numVertexes = numVertexes; - + } + /* additional st arrays? */ - while( numSTArrays > surface->maxSTArrays ) /* fix */ + while ( numSTArrays > surface->maxSTArrays ) /* fix */ { surface->maxSTArrays += PICO_GROW_ARRAYS; - if( !_pico_realloc( (void*) &surface->st, surface->numSTArrays * sizeof( *surface->st ), surface->maxSTArrays * sizeof( *surface->st ) ) ) + if ( !_pico_realloc( (void*) &surface->st, surface->numSTArrays * sizeof( *surface->st ), surface->maxSTArrays * sizeof( *surface->st ) ) ) { return 0; - while( surface->numSTArrays < numSTArrays ) + } + while ( surface->numSTArrays < numSTArrays ) { surface->st[ surface->numSTArrays ] = _pico_alloc( surface->maxVertexes * sizeof( *surface->st[ 0 ] ) ); memset( surface->st[ surface->numSTArrays ], 0, surface->maxVertexes * sizeof( *surface->st[ 0 ] ) ); surface->numSTArrays++; } } - + /* additional color arrays? */ - while( numColorArrays > surface->maxColorArrays ) /* fix */ + while ( numColorArrays > surface->maxColorArrays ) /* fix */ { surface->maxColorArrays += PICO_GROW_ARRAYS; - if( !_pico_realloc( (void*) &surface->color, surface->numColorArrays * sizeof( *surface->color ), surface->maxColorArrays * sizeof( *surface->color ) ) ) + if ( !_pico_realloc( (void*) &surface->color, surface->numColorArrays * sizeof( *surface->color ), surface->maxColorArrays * sizeof( *surface->color ) ) ) { return 0; - while( surface->numColorArrays < numColorArrays ) + } + while ( surface->numColorArrays < numColorArrays ) { surface->color[ surface->numColorArrays ] = _pico_alloc( surface->maxVertexes * sizeof( *surface->color[ 0 ] ) ); memset( surface->color[ surface->numColorArrays ], 0, surface->maxVertexes * sizeof( *surface->color[ 0 ] ) ); surface->numColorArrays++; } } - + /* additional indexes? */ - while( numIndexes > surface->maxIndexes ) /* fix */ + while ( numIndexes > surface->maxIndexes ) /* fix */ { surface->maxIndexes += PICO_GROW_INDEXES; - if( !_pico_realloc( (void*) &surface->index, surface->numIndexes * sizeof( *surface->index ), surface->maxIndexes * sizeof( *surface->index ) ) ) + if ( !_pico_realloc( (void*) &surface->index, surface->numIndexes * sizeof( *surface->index ), surface->maxIndexes * sizeof( *surface->index ) ) ) { return 0; + } } - + /* set index count to higher */ - if( numIndexes > surface->numIndexes ) + if ( numIndexes > surface->numIndexes ) { surface->numIndexes = numIndexes; + } /* additional face normals? */ - while( numFaceNormals > surface->maxFaceNormals ) /* fix */ + while ( numFaceNormals > surface->maxFaceNormals ) /* fix */ { surface->maxFaceNormals += PICO_GROW_FACES; - if( !_pico_realloc( (void *) &surface->faceNormal, surface->numFaceNormals * sizeof( *surface->faceNormal ), surface->maxFaceNormals * sizeof( *surface->faceNormal ) ) ) + if ( !_pico_realloc( (void *) &surface->faceNormal, surface->numFaceNormals * sizeof( *surface->faceNormal ), surface->maxFaceNormals * sizeof( *surface->faceNormal ) ) ) { return 0; + } } /* set face normal count to higher */ - if( numFaceNormals > surface->numFaceNormals ) + if ( numFaceNormals > surface->numFaceNormals ) { surface->numFaceNormals = numFaceNormals; + } /* return ok */ return 1; @@ -718,29 +730,33 @@ int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, * Finds first matching named surface in a model. */ picoSurface_t *PicoFindSurface( - picoModel_t *model, char *name, int caseSensitive ) -{ - int i; + picoModel_t *model, char *name, int caseSensitive ){ + int i; /* sanity check */ - if( model == NULL || name == NULL ) + if ( model == NULL || name == NULL ) { return NULL; - + } + /* walk list */ - for( i = 0; i < model->numSurfaces; i++ ) + for ( i = 0; i < model->numSurfaces; i++ ) { /* skip null surfaces or surfaces with null names */ - if( model->surface[ i ] == NULL || - model->surface[ i ]->name == NULL ) + if ( model->surface[ i ] == NULL || + model->surface[ i ]->name == NULL ) { continue; + } /* compare the surface name with name we're looking for */ - if (caseSensitive) { - if( !strcmp(name,model->surface[ i ]->name) ) + if ( caseSensitive ) { + if ( !strcmp( name,model->surface[ i ]->name ) ) { return model->surface[ i ]; - } else { - if( !_pico_stricmp(name,model->surface[ i ]->name) ) + } + } + else { + if ( !_pico_stricmp( name,model->surface[ i ]->name ) ) { return model->surface[ i ]; + } } } /* named surface not found */ @@ -750,88 +766,92 @@ picoSurface_t *PicoFindSurface( /*---------------------------------------------------------------------------- - PicoSet*() Setter Functions -----------------------------------------------------------------------------*/ + PicoSet*() Setter Functions + ----------------------------------------------------------------------------*/ -void PicoSetModelName( picoModel_t *model, const char *name ) -{ - if( model == NULL || name == NULL ) +void PicoSetModelName( picoModel_t *model, const char *name ){ + if ( model == NULL || name == NULL ) { return; - if( model->name != NULL ) + } + if ( model->name != NULL ) { _pico_free( model->name ); + } model->name = _pico_clone_alloc( name ); } -void PicoSetModelFileName( picoModel_t *model, const char *fileName ) -{ - if( model == NULL || fileName == NULL ) +void PicoSetModelFileName( picoModel_t *model, const char *fileName ){ + if ( model == NULL || fileName == NULL ) { return; - if( model->fileName != NULL ) + } + if ( model->fileName != NULL ) { _pico_free( model->fileName ); + } model->fileName = _pico_clone_alloc( fileName ); } -void PicoSetModelFrameNum( picoModel_t *model, int frameNum ) -{ - if( model == NULL ) +void PicoSetModelFrameNum( picoModel_t *model, int frameNum ){ + if ( model == NULL ) { return; + } model->frameNum = frameNum; } -void PicoSetModelNumFrames( picoModel_t *model, int numFrames ) -{ - if( model == NULL ) +void PicoSetModelNumFrames( picoModel_t *model, int numFrames ){ + if ( model == NULL ) { return; + } model->numFrames = numFrames; } -void PicoSetModelData( picoModel_t *model, void *data ) -{ - if( model == NULL ) +void PicoSetModelData( picoModel_t *model, void *data ){ + if ( model == NULL ) { return; + } model->data = data; } -void PicoSetShaderName( picoShader_t *shader, char *name ) -{ - if( shader == NULL || name == NULL ) +void PicoSetShaderName( picoShader_t *shader, char *name ){ + if ( shader == NULL || name == NULL ) { return; - if( shader->name != NULL ) + } + if ( shader->name != NULL ) { _pico_free( shader->name ); + } shader->name = _pico_clone_alloc( name ); } -void PicoSetShaderMapName( picoShader_t *shader, char *mapName ) -{ - if( shader == NULL || mapName == NULL ) +void PicoSetShaderMapName( picoShader_t *shader, char *mapName ){ + if ( shader == NULL || mapName == NULL ) { return; - if( shader->mapName != NULL ) + } + if ( shader->mapName != NULL ) { _pico_free( shader->mapName ); + } shader->mapName = _pico_clone_alloc( mapName ); } -void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ) -{ - if( shader == NULL || color == NULL ) +void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ){ + if ( shader == NULL || color == NULL ) { return; + } shader->ambientColor[ 0 ] = color[ 0 ]; shader->ambientColor[ 1 ] = color[ 1 ]; shader->ambientColor[ 2 ] = color[ 2 ]; @@ -840,10 +860,10 @@ void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ) -void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ) -{ - if( shader == NULL || color == NULL ) +void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ){ + if ( shader == NULL || color == NULL ) { return; + } shader->diffuseColor[ 0 ] = color[ 0 ]; shader->diffuseColor[ 1 ] = color[ 1 ]; shader->diffuseColor[ 2 ] = color[ 2 ]; @@ -852,10 +872,10 @@ void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ) -void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ) -{ - if( shader == NULL || color == NULL ) +void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ){ + if ( shader == NULL || color == NULL ) { return; + } shader->specularColor[ 0 ] = color[ 0 ]; shader->specularColor[ 1 ] = color[ 1 ]; shader->specularColor[ 2 ] = color[ 2 ]; @@ -864,117 +884,127 @@ void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ) -void PicoSetShaderTransparency( picoShader_t *shader, float value ) -{ - if( shader == NULL ) +void PicoSetShaderTransparency( picoShader_t *shader, float value ){ + if ( shader == NULL ) { return; + } shader->transparency = value; /* cap to 0..1 range */ - if (shader->transparency < 0.0) + if ( shader->transparency < 0.0 ) { shader->transparency = 0.0; - if (shader->transparency > 1.0) + } + if ( shader->transparency > 1.0 ) { shader->transparency = 1.0; + } } -void PicoSetShaderShininess( picoShader_t *shader, float value ) -{ - if( shader == NULL ) +void PicoSetShaderShininess( picoShader_t *shader, float value ){ + if ( shader == NULL ) { return; + } shader->shininess = value; /* cap to 0..127 range */ - if (shader->shininess < 0.0) + if ( shader->shininess < 0.0 ) { shader->shininess = 0.0; - if (shader->shininess > 127.0) + } + if ( shader->shininess > 127.0 ) { shader->shininess = 127.0; + } } -void PicoSetSurfaceData( picoSurface_t *surface, void *data ) -{ - if( surface == NULL ) +void PicoSetSurfaceData( picoSurface_t *surface, void *data ){ + if ( surface == NULL ) { return; + } surface->data = data; } -void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ) -{ - if( surface == NULL ) +void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ){ + if ( surface == NULL ) { return; + } surface->type = type; } -void PicoSetSurfaceName( picoSurface_t *surface, const char *name ) -{ - if( surface == NULL || name == NULL ) +void PicoSetSurfaceName( picoSurface_t *surface, const char *name ){ + if ( surface == NULL || name == NULL ) { return; - if( surface->name != NULL ) + } + if ( surface->name != NULL ) { _pico_free( surface->name ); + } surface->name = _pico_clone_alloc( name ); } -void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ) -{ - if( surface == NULL ) +void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ){ + if ( surface == NULL ) { return; + } surface->shader = shader; } -void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ) -{ - if( surface == NULL || num < 0 || xyz == NULL ) +void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ){ + if ( surface == NULL || num < 0 || xyz == NULL ) { return; - if( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) + } + if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { return; + } _pico_copy_vec( xyz, surface->xyz[ num ] ); - if( surface->model != NULL ) + if ( surface->model != NULL ) { _pico_expand_bounds( xyz, surface->model->mins, surface->model->maxs ); + } } -void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ) -{ - if( surface == NULL || num < 0 || normal == NULL ) +void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ){ + if ( surface == NULL || num < 0 || normal == NULL ) { return; - if( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) + } + if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { return; + } _pico_copy_vec( normal, surface->normal[ num ] ); } -void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ) -{ - if( surface == NULL || num < 0 || st == NULL ) +void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ){ + if ( surface == NULL || num < 0 || st == NULL ) { return; - if( !PicoAdjustSurface( surface, num + 1, array + 1, 0, 0, 0 ) ) + } + if ( !PicoAdjustSurface( surface, num + 1, array + 1, 0, 0, 0 ) ) { return; + } surface->st[ array ][ num ][ 0 ] = st[ 0 ]; surface->st[ array ][ num ][ 1 ] = st[ 1 ]; } -void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ) -{ - if( surface == NULL || num < 0 || color == NULL ) +void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ){ + if ( surface == NULL || num < 0 || color == NULL ) { return; - if( !PicoAdjustSurface( surface, num + 1, 0, array + 1, 0, 0 ) ) + } + if ( !PicoAdjustSurface( surface, num + 1, 0, array + 1, 0, 0 ) ) { return; + } surface->color[ array ][ num ][ 0 ] = color[ 0 ]; surface->color[ array ][ num ][ 1 ] = color[ 1 ]; surface->color[ array ][ num ][ 2 ] = color[ 2 ]; @@ -983,482 +1013,492 @@ void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_ -void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ) -{ - if( surface == NULL || num < 0 ) +void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ){ + if ( surface == NULL || num < 0 ) { return; - if( !PicoAdjustSurface( surface, 0, 0, 0, num + 1, 0 ) ) + } + if ( !PicoAdjustSurface( surface, 0, 0, 0, num + 1, 0 ) ) { return; + } surface->index[ num ] = index; } -void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ) -{ - if( num < 0 || index == NULL || count < 1 ) +void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ){ + if ( num < 0 || index == NULL || count < 1 ) { return; - if( !PicoAdjustSurface( surface, 0, 0, 0, num + count, 0 ) ) + } + if ( !PicoAdjustSurface( surface, 0, 0, 0, num + count, 0 ) ) { return; + } memcpy( &surface->index[ num ], index, count * sizeof( surface->index[ num ] ) ); } -void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ) -{ - if( surface == NULL || num < 0 || normal == NULL ) +void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ){ + if ( surface == NULL || num < 0 || normal == NULL ) { return; - if( !PicoAdjustSurface( surface, 0, 0, 0, 0, num + 1 ) ) + } + if ( !PicoAdjustSurface( surface, 0, 0, 0, 0, num + 1 ) ) { return; + } _pico_copy_vec( normal, surface->faceNormal[ num ] ); } -void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ) -{ - if( num < 0 ) +void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ){ + if ( num < 0 ) { return; - if( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) + } + if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { return; + } surface->smoothingGroup[ num ] = smoothingGroup; } -void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ) -{ - if( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) +void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ){ + if ( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) { return; + } surface->special[ num ] = special; } /*---------------------------------------------------------------------------- - PicoGet*() Getter Functions -----------------------------------------------------------------------------*/ + PicoGet*() Getter Functions + ----------------------------------------------------------------------------*/ -char *PicoGetModelName( picoModel_t *model ) -{ - if( model == NULL ) +char *PicoGetModelName( picoModel_t *model ){ + if ( model == NULL ) { return NULL; - if( model->name == NULL) + } + if ( model->name == NULL ) { return (char*) ""; + } return model->name; } -char *PicoGetModelFileName( picoModel_t *model ) -{ - if( model == NULL ) +char *PicoGetModelFileName( picoModel_t *model ){ + if ( model == NULL ) { return NULL; - if( model->fileName == NULL) + } + if ( model->fileName == NULL ) { return (char*) ""; + } return model->fileName; } -int PicoGetModelFrameNum( picoModel_t *model ) -{ - if( model == NULL ) +int PicoGetModelFrameNum( picoModel_t *model ){ + if ( model == NULL ) { return 0; + } return model->frameNum; } -int PicoGetModelNumFrames( picoModel_t *model ) -{ - if( model == NULL ) +int PicoGetModelNumFrames( picoModel_t *model ){ + if ( model == NULL ) { return 0; + } return model->numFrames; } -void *PicoGetModelData( picoModel_t *model ) -{ - if( model == NULL ) +void *PicoGetModelData( picoModel_t *model ){ + if ( model == NULL ) { return NULL; + } return model->data; } -int PicoGetModelNumShaders( picoModel_t *model ) -{ - if( model == NULL ) +int PicoGetModelNumShaders( picoModel_t *model ){ + if ( model == NULL ) { return 0; + } return model->numShaders; } -picoShader_t *PicoGetModelShader( picoModel_t *model, int num ) -{ +picoShader_t *PicoGetModelShader( picoModel_t *model, int num ){ /* a few sanity checks */ - if( model == NULL ) + if ( model == NULL ) { return NULL; - if( model->shader == NULL) + } + if ( model->shader == NULL ) { return NULL; - if( num < 0 || num >= model->numShaders ) + } + if ( num < 0 || num >= model->numShaders ) { return NULL; - + } + /* return the shader */ return model->shader[ num ]; } -int PicoGetModelNumSurfaces( picoModel_t *model ) -{ - if( model == NULL ) +int PicoGetModelNumSurfaces( picoModel_t *model ){ + if ( model == NULL ) { return 0; + } return model->numSurfaces; } -picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ) -{ +picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ){ /* a few sanity checks */ - if( model == NULL ) + if ( model == NULL ) { return NULL; - if( model->surface == NULL) + } + if ( model->surface == NULL ) { return NULL; - if( num < 0 || num >= model->numSurfaces ) + } + if ( num < 0 || num >= model->numSurfaces ) { return NULL; - + } + /* return the surface */ return model->surface[ num ]; } -int PicoGetModelTotalVertexes( picoModel_t *model ) -{ - int i, count; - - - if( model == NULL ) +int PicoGetModelTotalVertexes( picoModel_t *model ){ + int i, count; + + + if ( model == NULL ) { return 0; - if( model->surface == NULL ) + } + if ( model->surface == NULL ) { return 0; - + } + count = 0; - for( i = 0; i < model->numSurfaces; i++ ) - count += PicoGetSurfaceNumVertexes( model->surface[ i ] ); - + for ( i = 0; i < model->numSurfaces; i++ ) + count += PicoGetSurfaceNumVertexes( model->surface[ i ] ); + return count; } -int PicoGetModelTotalIndexes( picoModel_t *model ) -{ - int i, count; - - - if( model == NULL ) +int PicoGetModelTotalIndexes( picoModel_t *model ){ + int i, count; + + + if ( model == NULL ) { return 0; - if( model->surface == NULL ) + } + if ( model->surface == NULL ) { return 0; - + } + count = 0; - for( i = 0; i < model->numSurfaces; i++ ) - count += PicoGetSurfaceNumIndexes( model->surface[ i ] ); - + for ( i = 0; i < model->numSurfaces; i++ ) + count += PicoGetSurfaceNumIndexes( model->surface[ i ] ); + return count; } -char *PicoGetShaderName( picoShader_t *shader ) -{ - if( shader == NULL ) +char *PicoGetShaderName( picoShader_t *shader ){ + if ( shader == NULL ) { return NULL; - if( shader->name == NULL) + } + if ( shader->name == NULL ) { return (char*) ""; + } return shader->name; } -char *PicoGetShaderMapName( picoShader_t *shader ) -{ - if( shader == NULL ) +char *PicoGetShaderMapName( picoShader_t *shader ){ + if ( shader == NULL ) { return NULL; - if( shader->mapName == NULL) + } + if ( shader->mapName == NULL ) { return (char*) ""; + } return shader->mapName; } -picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ) -{ - if( shader == NULL ) +picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ){ + if ( shader == NULL ) { return NULL; + } return shader->ambientColor; } -picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ) -{ - if( shader == NULL ) +picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ){ + if ( shader == NULL ) { return NULL; + } return shader->diffuseColor; } -picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ) -{ - if( shader == NULL ) +picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ){ + if ( shader == NULL ) { return NULL; + } return shader->specularColor; } -float PicoGetShaderTransparency( picoShader_t *shader ) -{ - if( shader == NULL ) +float PicoGetShaderTransparency( picoShader_t *shader ){ + if ( shader == NULL ) { return 0.0f; + } return shader->transparency; } -float PicoGetShaderShininess( picoShader_t *shader ) -{ - if( shader == NULL ) +float PicoGetShaderShininess( picoShader_t *shader ){ + if ( shader == NULL ) { return 0.0f; + } return shader->shininess; } -void *PicoGetSurfaceData( picoSurface_t *surface ) -{ - if( surface == NULL ) +void *PicoGetSurfaceData( picoSurface_t *surface ){ + if ( surface == NULL ) { return NULL; + } return surface->data; } -picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ) -{ - if( surface == NULL ) +picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ){ + if ( surface == NULL ) { return PICO_BAD; + } return surface->type; } -char *PicoGetSurfaceName( picoSurface_t *surface ) -{ - if( surface == NULL ) +char *PicoGetSurfaceName( picoSurface_t *surface ){ + if ( surface == NULL ) { return NULL; - if( surface->name == NULL ) + } + if ( surface->name == NULL ) { return (char*) ""; + } return surface->name; } -picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ) -{ - if( surface == NULL ) +picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ){ + if ( surface == NULL ) { return NULL; + } return surface->shader; } -int PicoGetSurfaceNumVertexes( picoSurface_t *surface ) -{ - if( surface == NULL ) +int PicoGetSurfaceNumVertexes( picoSurface_t *surface ){ + if ( surface == NULL ) { return 0; + } return surface->numVertexes; } -picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numVertexes ) +picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numVertexes ) { return NULL; + } return surface->xyz[ num ]; } -picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numVertexes ) +picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numVertexes ) { return NULL; + } return surface->normal[ num ]; } -picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ) -{ - if( surface == NULL || array < 0 || array > surface->numSTArrays || num < 0 || num > surface->numVertexes ) +picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ){ + if ( surface == NULL || array < 0 || array > surface->numSTArrays || num < 0 || num > surface->numVertexes ) { return NULL; + } return surface->st[ array ][ num ]; } -picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ) -{ - if( surface == NULL || array < 0 || array > surface->numColorArrays || num < 0 || num > surface->numVertexes ) +picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ){ + if ( surface == NULL || array < 0 || array > surface->numColorArrays || num < 0 || num > surface->numVertexes ) { return NULL; + } return surface->color[ array ][ num ]; } -int PicoGetSurfaceNumIndexes( picoSurface_t *surface ) -{ - if( surface == NULL ) +int PicoGetSurfaceNumIndexes( picoSurface_t *surface ){ + if ( surface == NULL ) { return 0; + } return surface->numIndexes; } -picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numIndexes ) +picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numIndexes ) { return 0; + } return surface->index[ num ]; } -picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numIndexes ) +picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numIndexes ) { return NULL; + } return &surface->index[ num ]; } -picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numFaceNormals ) +picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numFaceNormals ) { return NULL; + } return surface->faceNormal[ num ]; } -picoIndex_t PicoGetSurfaceSmoothingGroup( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num > surface->numVertexes ) +picoIndex_t PicoGetSurfaceSmoothingGroup( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num > surface->numVertexes ) { return -1; + } return surface->smoothingGroup[ num ]; } -int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ) -{ - if( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) +int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ){ + if ( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) { return 0; + } return surface->special[ num ]; } /* ---------------------------------------------------------------------------- -hashtable related functions ----------------------------------------------------------------------------- */ + hashtable related functions + ---------------------------------------------------------------------------- */ /* hashtable code for faster vertex lookups */ //#define HASHTABLE_SIZE 32768 // 2048 /* power of 2, use & */ -#define HASHTABLE_SIZE 7919 // 32749 // 2039 /* prime, use % */ +#define HASHTABLE_SIZE 7919 // 32749 // 2039 /* prime, use % */ -int PicoGetHashTableSize( void ) -{ +int PicoGetHashTableSize( void ){ return HASHTABLE_SIZE; } #define HASH_USE_EPSILON #ifdef HASH_USE_EPSILON -#define HASH_XYZ_EPSILON 0.01f -#define HASH_XYZ_EPSILONSPACE_MULTIPLIER 1.f / HASH_XYZ_EPSILON -#define HASH_ST_EPSILON 0.0001f -#define HASH_NORMAL_EPSILON 0.02f +#define HASH_XYZ_EPSILON 0.01f +#define HASH_XYZ_EPSILONSPACE_MULTIPLIER 1.f / HASH_XYZ_EPSILON +#define HASH_ST_EPSILON 0.0001f +#define HASH_NORMAL_EPSILON 0.02f #endif -unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ) -{ +unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ){ unsigned int hash = 0; #ifndef HASH_USE_EPSILON - hash += ~(*((unsigned int*) &xyz[ 0 ]) << 15); - hash ^= (*((unsigned int*) &xyz[ 0 ]) >> 10); - hash += (*((unsigned int*) &xyz[ 1 ]) << 3); - hash ^= (*((unsigned int*) &xyz[ 1 ]) >> 6); - hash += ~(*((unsigned int*) &xyz[ 2 ]) << 11); - hash ^= (*((unsigned int*) &xyz[ 2 ]) >> 16); + hash += ~( *( (unsigned int*) &xyz[ 0 ] ) << 15 ); + hash ^= ( *( (unsigned int*) &xyz[ 0 ] ) >> 10 ); + hash += ( *( (unsigned int*) &xyz[ 1 ] ) << 3 ); + hash ^= ( *( (unsigned int*) &xyz[ 1 ] ) >> 6 ); + hash += ~( *( (unsigned int*) &xyz[ 2 ] ) << 11 ); + hash ^= ( *( (unsigned int*) &xyz[ 2 ] ) >> 16 ); #else picoVec3_t xyz_epsilonspace; _pico_scale_vec( xyz, HASH_XYZ_EPSILONSPACE_MULTIPLIER, xyz_epsilonspace ); - xyz_epsilonspace[ 0 ] = (float)floor(xyz_epsilonspace[ 0 ]); - xyz_epsilonspace[ 1 ] = (float)floor(xyz_epsilonspace[ 1 ]); - xyz_epsilonspace[ 2 ] = (float)floor(xyz_epsilonspace[ 2 ]); - - hash += ~(*((unsigned int*) &xyz_epsilonspace[ 0 ]) << 15); - hash ^= (*((unsigned int*) &xyz_epsilonspace[ 0 ]) >> 10); - hash += (*((unsigned int*) &xyz_epsilonspace[ 1 ]) << 3); - hash ^= (*((unsigned int*) &xyz_epsilonspace[ 1 ]) >> 6); - hash += ~(*((unsigned int*) &xyz_epsilonspace[ 2 ]) << 11); - hash ^= (*((unsigned int*) &xyz_epsilonspace[ 2 ]) >> 16); + xyz_epsilonspace[ 0 ] = (float)floor( xyz_epsilonspace[ 0 ] ); + xyz_epsilonspace[ 1 ] = (float)floor( xyz_epsilonspace[ 1 ] ); + xyz_epsilonspace[ 2 ] = (float)floor( xyz_epsilonspace[ 2 ] ); + + hash += ~( *( (unsigned int*) &xyz_epsilonspace[ 0 ] ) << 15 ); + hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 0 ] ) >> 10 ); + hash += ( *( (unsigned int*) &xyz_epsilonspace[ 1 ] ) << 3 ); + hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 1 ] ) >> 6 ); + hash += ~( *( (unsigned int*) &xyz_epsilonspace[ 2 ] ) << 11 ); + hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 2 ] ) >> 16 ); #endif //hash = hash & (HASHTABLE_SIZE-1); - hash = hash % (HASHTABLE_SIZE); + hash = hash % ( HASHTABLE_SIZE ); return hash; } -picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ) -{ - picoVertexCombinationHash_t **hashTable = _pico_alloc( HASHTABLE_SIZE * sizeof(picoVertexCombinationHash_t*) ); +picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ){ + picoVertexCombinationHash_t **hashTable = _pico_alloc( HASHTABLE_SIZE * sizeof( picoVertexCombinationHash_t* ) ); - memset( hashTable, 0, HASHTABLE_SIZE * sizeof(picoVertexCombinationHash_t*) ); + memset( hashTable, 0, HASHTABLE_SIZE * sizeof( picoVertexCombinationHash_t* ) ); return hashTable; } -void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ) -{ - int i; - picoVertexCombinationHash_t *vertexCombinationHash; +void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ){ + int i; + picoVertexCombinationHash_t *vertexCombinationHash; picoVertexCombinationHash_t *nextVertexCombinationHash; /* dummy check */ - if (hashTable == NULL) + if ( hashTable == NULL ) { return; + } - for( i = 0; i < HASHTABLE_SIZE; i++ ) + for ( i = 0; i < HASHTABLE_SIZE; i++ ) { - if (hashTable[ i ]) - { + if ( hashTable[ i ] ) { nextVertexCombinationHash = NULL; - for( vertexCombinationHash = hashTable[ i ]; vertexCombinationHash; vertexCombinationHash = nextVertexCombinationHash ) + for ( vertexCombinationHash = hashTable[ i ]; vertexCombinationHash; vertexCombinationHash = nextVertexCombinationHash ) { nextVertexCombinationHash = vertexCombinationHash->next; - if (vertexCombinationHash->data != NULL) - { + if ( vertexCombinationHash->data != NULL ) { _pico_free( vertexCombinationHash->data ); } _pico_free( vertexCombinationHash ); @@ -1469,53 +1509,60 @@ void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable _pico_free( hashTable ); } -picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ) -{ - unsigned int hash; - picoVertexCombinationHash_t *vertexCombinationHash; +picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ){ + unsigned int hash; + picoVertexCombinationHash_t *vertexCombinationHash; /* dumy check */ - if (hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) + if ( hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) { return NULL; + } hash = PicoVertexCoordGenerateHash( xyz ); - for( vertexCombinationHash = hashTable[ hash ]; vertexCombinationHash; vertexCombinationHash = vertexCombinationHash->next ) + for ( vertexCombinationHash = hashTable[ hash ]; vertexCombinationHash; vertexCombinationHash = vertexCombinationHash->next ) { #ifndef HASH_USE_EPSILON /* check xyz */ - if( (vertexCombinationHash->vcd.xyz[ 0 ] != xyz[ 0 ] || vertexCombinationHash->vcd.xyz[ 1 ] != xyz[ 1 ] || vertexCombinationHash->vcd.xyz[ 2 ] != xyz[ 2 ]) ) + if ( ( vertexCombinationHash->vcd.xyz[ 0 ] != xyz[ 0 ] || vertexCombinationHash->vcd.xyz[ 1 ] != xyz[ 1 ] || vertexCombinationHash->vcd.xyz[ 2 ] != xyz[ 2 ] ) ) { continue; + } /* check normal */ - if( (vertexCombinationHash->vcd.normal[ 0 ] != normal[ 0 ] || vertexCombinationHash->vcd.normal[ 1 ] != normal[ 1 ] || vertexCombinationHash->vcd.normal[ 2 ] != normal[ 2 ]) ) + if ( ( vertexCombinationHash->vcd.normal[ 0 ] != normal[ 0 ] || vertexCombinationHash->vcd.normal[ 1 ] != normal[ 1 ] || vertexCombinationHash->vcd.normal[ 2 ] != normal[ 2 ] ) ) { continue; - + } + /* check st */ - if( vertexCombinationHash->vcd.st[ 0 ] != st[ 0 ] || vertexCombinationHash->vcd.st[ 1 ] != st[ 1 ] ) + if ( vertexCombinationHash->vcd.st[ 0 ] != st[ 0 ] || vertexCombinationHash->vcd.st[ 1 ] != st[ 1 ] ) { continue; + } #else /* check xyz */ - if( ( fabs(xyz[ 0 ] - vertexCombinationHash->vcd.xyz[ 0 ]) ) > HASH_XYZ_EPSILON || - ( fabs(xyz[ 1 ] - vertexCombinationHash->vcd.xyz[ 1 ]) ) > HASH_XYZ_EPSILON || - ( fabs(xyz[ 2 ] - vertexCombinationHash->vcd.xyz[ 2 ]) ) > HASH_XYZ_EPSILON ) + if ( ( fabs( xyz[ 0 ] - vertexCombinationHash->vcd.xyz[ 0 ] ) ) > HASH_XYZ_EPSILON || + ( fabs( xyz[ 1 ] - vertexCombinationHash->vcd.xyz[ 1 ] ) ) > HASH_XYZ_EPSILON || + ( fabs( xyz[ 2 ] - vertexCombinationHash->vcd.xyz[ 2 ] ) ) > HASH_XYZ_EPSILON ) { continue; + } /* check normal */ - if( ( fabs(normal[ 0 ] - vertexCombinationHash->vcd.normal[ 0 ]) ) > HASH_NORMAL_EPSILON || - ( fabs(normal[ 1 ] - vertexCombinationHash->vcd.normal[ 1 ]) ) > HASH_NORMAL_EPSILON || - ( fabs(normal[ 2 ] - vertexCombinationHash->vcd.normal[ 2 ]) ) > HASH_NORMAL_EPSILON ) + if ( ( fabs( normal[ 0 ] - vertexCombinationHash->vcd.normal[ 0 ] ) ) > HASH_NORMAL_EPSILON || + ( fabs( normal[ 1 ] - vertexCombinationHash->vcd.normal[ 1 ] ) ) > HASH_NORMAL_EPSILON || + ( fabs( normal[ 2 ] - vertexCombinationHash->vcd.normal[ 2 ] ) ) > HASH_NORMAL_EPSILON ) { continue; - + } + /* check st */ - if( ( fabs(st[ 0 ] - vertexCombinationHash->vcd.st[ 0 ]) ) > HASH_ST_EPSILON || - ( fabs(st[ 1 ] - vertexCombinationHash->vcd.st[ 1 ]) ) > HASH_ST_EPSILON ) + if ( ( fabs( st[ 0 ] - vertexCombinationHash->vcd.st[ 0 ] ) ) > HASH_ST_EPSILON || + ( fabs( st[ 1 ] - vertexCombinationHash->vcd.st[ 1 ] ) ) > HASH_ST_EPSILON ) { continue; + } #endif /* check color */ - if( *((int*) vertexCombinationHash->vcd.color) != *((int*) color) ) + if ( *( (int*) vertexCombinationHash->vcd.color ) != *( (int*) color ) ) { continue; + } /* gotcha */ return vertexCombinationHash; @@ -1524,19 +1571,20 @@ picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCom return NULL; } -picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color, picoIndex_t index ) -{ - unsigned int hash; - picoVertexCombinationHash_t *vertexCombinationHash; +picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color, picoIndex_t index ){ + unsigned int hash; + picoVertexCombinationHash_t *vertexCombinationHash; /* dumy check */ - if (hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) + if ( hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) { return NULL; + } - vertexCombinationHash = _pico_alloc( sizeof(picoVertexCombinationHash_t) ); + vertexCombinationHash = _pico_alloc( sizeof( picoVertexCombinationHash_t ) ); - if (!vertexCombinationHash) + if ( !vertexCombinationHash ) { return NULL; + } hash = PicoVertexCoordGenerateHash( xyz ); @@ -1553,67 +1601,72 @@ picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexComb } /* ---------------------------------------------------------------------------- -specialized routines ----------------------------------------------------------------------------- */ + specialized routines + ---------------------------------------------------------------------------- */ /* -PicoFindSurfaceVertex() -finds a vertex matching the set parameters -fixme: needs non-naive algorithm -*/ + PicoFindSurfaceVertex() + finds a vertex matching the set parameters + fixme: needs non-naive algorithm + */ + +int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup ){ + int i, j; + -int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup) -{ - int i, j; - - /* dummy check */ - if( surface == NULL || surface->numVertexes <= 0 ) + if ( surface == NULL || surface->numVertexes <= 0 ) { return -1; - + } + /* walk vertex list */ - for( i = 0; i < surface->numVertexes; i++ ) + for ( i = 0; i < surface->numVertexes; i++ ) { /* check xyz */ - if( xyz != NULL && (surface->xyz[ i ][ 0 ] != xyz[ 0 ] || surface->xyz[ i ][ 1 ] != xyz[ 1 ] || surface->xyz[ i ][ 2 ] != xyz[ 2 ]) ) + if ( xyz != NULL && ( surface->xyz[ i ][ 0 ] != xyz[ 0 ] || surface->xyz[ i ][ 1 ] != xyz[ 1 ] || surface->xyz[ i ][ 2 ] != xyz[ 2 ] ) ) { continue; - + } + /* check normal */ - if( normal != NULL && (surface->normal[ i ][ 0 ] != normal[ 0 ] || surface->normal[ i ][ 1 ] != normal[ 1 ] || surface->normal[ i ][ 2 ] != normal[ 2 ]) ) + if ( normal != NULL && ( surface->normal[ i ][ 0 ] != normal[ 0 ] || surface->normal[ i ][ 1 ] != normal[ 1 ] || surface->normal[ i ][ 2 ] != normal[ 2 ] ) ) { continue; - + } + /* check normal */ - if( surface->smoothingGroup[ i ] != smoothingGroup ) + if ( surface->smoothingGroup[ i ] != smoothingGroup ) { continue; + } - /* check st */ - if( numSTs > 0 && st != NULL ) - { - for( j = 0; j < numSTs; j++ ) + /* check st */ + if ( numSTs > 0 && st != NULL ) { + for ( j = 0; j < numSTs; j++ ) { - if( surface->st[ j ][ i ][ 0 ] != st[ j ][ 0 ] || surface->st[ j ][ i ][ 1 ] != st[ j ][ 1 ] ) + if ( surface->st[ j ][ i ][ 0 ] != st[ j ][ 0 ] || surface->st[ j ][ i ][ 1 ] != st[ j ][ 1 ] ) { break; + } } - if( j != numSTs ) + if ( j != numSTs ) { continue; + } } - + /* check color */ - if( numColors > 0 && color != NULL ) - { - for( j = 0; j < numSTs; j++ ) + if ( numColors > 0 && color != NULL ) { + for ( j = 0; j < numSTs; j++ ) { - if( *((int*) surface->color[ j ]) != *((int*) color[ j ]) ) + if ( *( (int*) surface->color[ j ] ) != *( (int*) color[ j ] ) ) { break; + } } - if( j != numColors ) + if ( j != numColors ) { continue; + } } - + /* vertex matches */ return i; } - + /* nada */ return -1; } @@ -1628,24 +1681,20 @@ struct _IndexArray picoIndex_t* last; }; -void indexarray_push_back(IndexArray* self, picoIndex_t value) -{ +void indexarray_push_back( IndexArray* self, picoIndex_t value ){ *self->last++ = value; } -size_t indexarray_size(IndexArray* self) -{ +size_t indexarray_size( IndexArray* self ){ return self->last - self->data; } -void indexarray_reserve(IndexArray* self, size_t size) -{ - self->data = self->last = _pico_calloc(size, sizeof(picoIndex_t)); +void indexarray_reserve( IndexArray* self, size_t size ){ + self->data = self->last = _pico_calloc( size, sizeof( picoIndex_t ) ); } -void indexarray_clear(IndexArray* self) -{ - _pico_free(self->data); +void indexarray_clear( IndexArray* self ){ + _pico_free( self->data ); } typedef struct _BinaryTreeNode BinaryTreeNode; @@ -1662,29 +1711,25 @@ struct _BinaryTree BinaryTreeNode* last; }; -void binarytree_extend(BinaryTree* self) -{ +void binarytree_extend( BinaryTree* self ){ self->last->left = 0; self->last->right = 0; ++self->last; } -size_t binarytree_size(BinaryTree* self) -{ +size_t binarytree_size( BinaryTree* self ){ return self->last - self->data; } -void binarytree_reserve(BinaryTree* self, size_t size) -{ - self->data = self->last = _pico_calloc(size, sizeof(BinaryTreeNode)); +void binarytree_reserve( BinaryTree* self, size_t size ){ + self->data = self->last = _pico_calloc( size, sizeof( BinaryTreeNode ) ); } -void binarytree_clear(BinaryTree* self) -{ - _pico_free(self->data); +void binarytree_clear( BinaryTree* self ){ + _pico_free( self->data ); } -typedef int (*LessFunc)(void*, picoIndex_t, picoIndex_t); +typedef int ( *LessFunc )( void*, picoIndex_t, picoIndex_t ); typedef struct _UniqueIndices UniqueIndices; struct _UniqueIndices @@ -1695,65 +1740,56 @@ struct _UniqueIndices void* lessData; }; -size_t UniqueIndices_size(UniqueIndices* self) -{ - return binarytree_size(&self->tree); +size_t UniqueIndices_size( UniqueIndices* self ){ + return binarytree_size( &self->tree ); } -void UniqueIndices_reserve(UniqueIndices* self, size_t size) -{ - binarytree_reserve(&self->tree, size); - indexarray_reserve(&self->indices, size); +void UniqueIndices_reserve( UniqueIndices* self, size_t size ){ + binarytree_reserve( &self->tree, size ); + indexarray_reserve( &self->indices, size ); } -void UniqueIndices_init(UniqueIndices* self, LessFunc lessFunc, void* lessData) -{ +void UniqueIndices_init( UniqueIndices* self, LessFunc lessFunc, void* lessData ){ self->lessFunc = lessFunc; self->lessData = lessData; } -void UniqueIndices_destroy(UniqueIndices* self) -{ - binarytree_clear(&self->tree); - indexarray_clear(&self->indices); +void UniqueIndices_destroy( UniqueIndices* self ){ + binarytree_clear( &self->tree ); + indexarray_clear( &self->indices ); } -picoIndex_t UniqueIndices_find_or_insert(UniqueIndices* self, picoIndex_t value) -{ +picoIndex_t UniqueIndices_find_or_insert( UniqueIndices* self, picoIndex_t value ){ picoIndex_t index = 0; - for(;;) + for (;; ) { - if(self->lessFunc(self->lessData, value, self->indices.data[index])) - { + if ( self->lessFunc( self->lessData, value, self->indices.data[index] ) ) { BinaryTreeNode* node = self->tree.data + index; - if(node->left != 0) - { + if ( node->left != 0 ) { index = node->left; continue; } else { - node->left = (picoIndex_t)binarytree_size(&self->tree); - binarytree_extend(&self->tree); - indexarray_push_back(&self->indices, value); + node->left = (picoIndex_t)binarytree_size( &self->tree ); + binarytree_extend( &self->tree ); + indexarray_push_back( &self->indices, value ); return node->left; } } - if(self->lessFunc(self->lessData, self->indices.data[index], value)) - { + if ( self->lessFunc( self->lessData, self->indices.data[index], value ) ) { BinaryTreeNode* node = self->tree.data + index; - if(node->right != 0) - { + if ( node->right != 0 ) { index = node->right; continue; } else { - node->right = (picoIndex_t)binarytree_size(&self->tree); - binarytree_extend(&self->tree); - indexarray_push_back(&self->indices, value); + node->right = (picoIndex_t)binarytree_size( &self->tree ); + binarytree_extend( &self->tree ); + indexarray_push_back( &self->indices, value ); return node->right; } } @@ -1762,17 +1798,15 @@ picoIndex_t UniqueIndices_find_or_insert(UniqueIndices* self, picoIndex_t value) } } -picoIndex_t UniqueIndices_insert(UniqueIndices* self, picoIndex_t value) -{ - if(self->tree.data == self->tree.last) - { - binarytree_extend(&self->tree); - indexarray_push_back(&self->indices, value); +picoIndex_t UniqueIndices_insert( UniqueIndices* self, picoIndex_t value ){ + if ( self->tree.data == self->tree.last ) { + binarytree_extend( &self->tree ); + indexarray_push_back( &self->indices, value ); return 0; - } + } else { - return UniqueIndices_find_or_insert(self, value); + return UniqueIndices_find_or_insert( self, value ); } } @@ -1783,62 +1817,54 @@ struct picoSmoothVertices_s picoIndex_t* smoothingGroups; }; -int lessSmoothVertex(void* data, picoIndex_t first, picoIndex_t second) -{ +int lessSmoothVertex( void* data, picoIndex_t first, picoIndex_t second ){ picoSmoothVertices_t* smoothVertices = data; - - if(smoothVertices->xyz[first][0] != smoothVertices->xyz[second][0]) - { + + if ( smoothVertices->xyz[first][0] != smoothVertices->xyz[second][0] ) { return smoothVertices->xyz[first][0] < smoothVertices->xyz[second][0]; } - if(smoothVertices->xyz[first][1] != smoothVertices->xyz[second][1]) - { + if ( smoothVertices->xyz[first][1] != smoothVertices->xyz[second][1] ) { return smoothVertices->xyz[first][1] < smoothVertices->xyz[second][1]; } - if(smoothVertices->xyz[first][2] != smoothVertices->xyz[second][2]) - { + if ( smoothVertices->xyz[first][2] != smoothVertices->xyz[second][2] ) { return smoothVertices->xyz[first][2] < smoothVertices->xyz[second][2]; } - if(smoothVertices->smoothingGroups[first] != smoothVertices->smoothingGroups[second]) - { + if ( smoothVertices->smoothingGroups[first] != smoothVertices->smoothingGroups[second] ) { return smoothVertices->smoothingGroups[first] < smoothVertices->smoothingGroups[second]; } return 0; } -void _pico_vertices_combine_shared_normals(picoVec3_t* xyz, picoIndex_t* smoothingGroups, picoVec3_t* normals, picoIndex_t numVertices) -{ +void _pico_vertices_combine_shared_normals( picoVec3_t* xyz, picoIndex_t* smoothingGroups, picoVec3_t* normals, picoIndex_t numVertices ){ UniqueIndices vertices; IndexArray indices; picoSmoothVertices_t smoothVertices = { xyz, smoothingGroups }; - UniqueIndices_init(&vertices, lessSmoothVertex, &smoothVertices); - UniqueIndices_reserve(&vertices, numVertices); - indexarray_reserve(&indices, numVertices); + UniqueIndices_init( &vertices, lessSmoothVertex, &smoothVertices ); + UniqueIndices_reserve( &vertices, numVertices ); + indexarray_reserve( &indices, numVertices ); { picoIndex_t i = 0; - for(; i < numVertices; ++i) + for (; i < numVertices; ++i ) { - size_t size = UniqueIndices_size(&vertices); - picoIndex_t index = UniqueIndices_insert(&vertices, i); - if((size_t)index != size) - { + size_t size = UniqueIndices_size( &vertices ); + picoIndex_t index = UniqueIndices_insert( &vertices, i ); + if ( (size_t)index != size ) { float* normal = normals[vertices.indices.data[index]]; - _pico_add_vec(normal, normals[i], normal); + _pico_add_vec( normal, normals[i], normal ); } - indexarray_push_back(&indices, index); + indexarray_push_back( &indices, index ); } } { picoIndex_t maxIndex = 0; picoIndex_t* i = indices.data; - for(; i != indices.last; ++i) + for (; i != indices.last; ++i ) { - if(*i <= maxIndex) - { - _pico_copy_vec(normals[vertices.indices.data[*i]], normals[i - indices.data]); + if ( *i <= maxIndex ) { + _pico_copy_vec( normals[vertices.indices.data[*i]], normals[i - indices.data] ); } else { @@ -1847,8 +1873,8 @@ void _pico_vertices_combine_shared_normals(picoVec3_t* xyz, picoIndex_t* smoothi } } - UniqueIndices_destroy(&vertices); - indexarray_clear(&indices); + UniqueIndices_destroy( &vertices ); + indexarray_clear( &indices ); } typedef picoVec3_t* picoNormalIter_t; @@ -1856,16 +1882,15 @@ typedef picoIndex_t* picoIndexIter_t; #define THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL 1 -void _pico_triangles_generate_weighted_normals(picoIndexIter_t first, picoIndexIter_t end, picoVec3_t* xyz, picoVec3_t* normals) -{ - for(; first != end; first += 3) +void _pico_triangles_generate_weighted_normals( picoIndexIter_t first, picoIndexIter_t end, picoVec3_t* xyz, picoVec3_t* normals ){ + for (; first != end; first += 3 ) { -#if (THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) +#if ( THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL ) picoVec3_t weightedNormal; { - float* a = xyz[*(first + 0)]; - float* b = xyz[*(first + 1)]; - float* c = xyz[*(first + 2)]; + float* a = xyz[*( first + 0 )]; + float* b = xyz[*( first + 1 )]; + float* c = xyz[*( first + 2 )]; picoVec3_t ba, ca; _pico_subtract_vec( b, a, ba ); _pico_subtract_vec( c, a, ca ); @@ -1874,189 +1899,190 @@ void _pico_triangles_generate_weighted_normals(picoIndexIter_t first, picoIndexI #endif { int j = 0; - for(; j < 3; ++j) + for (; j < 3; ++j ) { - float* normal = normals[*(first + j)]; -#if (!THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) + float* normal = normals[*( first + j )]; +#if ( !THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL ) picoVec3_t weightedNormal; { - float* a = xyz[*(first + ((j + 0) % 3))]; - float* b = xyz[*(first + ((j + 1) % 3))]; - float* c = xyz[*(first + ((j + 2) % 3))]; + float* a = xyz[*( first + ( ( j + 0 ) % 3 ) )]; + float* b = xyz[*( first + ( ( j + 1 ) % 3 ) )]; + float* c = xyz[*( first + ( ( j + 2 ) % 3 ) )]; picoVec3_t ba, ca; _pico_subtract_vec( b, a, ba ); _pico_subtract_vec( c, a, ca ); _pico_cross_vec( ca, ba, weightedNormal ); } #endif - _pico_add_vec(weightedNormal, normal, normal); + _pico_add_vec( weightedNormal, normal, normal ); } } } } -void _pico_normals_zero(picoNormalIter_t first, picoNormalIter_t last) -{ - for(; first != last; ++first) +void _pico_normals_zero( picoNormalIter_t first, picoNormalIter_t last ){ + for (; first != last; ++first ) { - _pico_zero_vec(*first); + _pico_zero_vec( *first ); } } -void _pico_normals_normalize(picoNormalIter_t first, picoNormalIter_t last) -{ - for(; first != last; ++first) +void _pico_normals_normalize( picoNormalIter_t first, picoNormalIter_t last ){ + for (; first != last; ++first ) { - _pico_normalize_vec(*first); + _pico_normalize_vec( *first ); } } -double _pico_length_vec( picoVec3_t vec ) -{ +double _pico_length_vec( picoVec3_t vec ){ return sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] + vec[ 2 ] * vec[ 2 ] ); } #define NORMAL_UNIT_LENGTH_EPSILON 0.01 -#define FLOAT_EQUAL_EPSILON(f, other, epsilon) (fabs(f - other) < epsilon) +#define FLOAT_EQUAL_EPSILON( f, other, epsilon ) ( fabs( f - other ) < epsilon ) -int _pico_normal_is_unit_length(picoVec3_t normal) -{ - return FLOAT_EQUAL_EPSILON(_pico_length_vec(normal), 1.0, NORMAL_UNIT_LENGTH_EPSILON); +int _pico_normal_is_unit_length( picoVec3_t normal ){ + return FLOAT_EQUAL_EPSILON( _pico_length_vec( normal ), 1.0, NORMAL_UNIT_LENGTH_EPSILON ); } -int _pico_normal_within_tolerance(picoVec3_t normal, picoVec3_t other) -{ - return _pico_dot_vec(normal, other) > 0.0f; +int _pico_normal_within_tolerance( picoVec3_t normal, picoVec3_t other ){ + return _pico_dot_vec( normal, other ) > 0.0f; } -void _pico_normals_assign_generated_normals(picoNormalIter_t first, picoNormalIter_t last, picoNormalIter_t generated) -{ - for(; first != last; ++first, ++generated) +void _pico_normals_assign_generated_normals( picoNormalIter_t first, picoNormalIter_t last, picoNormalIter_t generated ){ + for (; first != last; ++first, ++generated ) { - if(!_pico_normal_is_unit_length(*first) || !_pico_normal_within_tolerance(*first, *generated)) - { - _pico_copy_vec(*generated, *first); + if ( !_pico_normal_is_unit_length( *first ) || !_pico_normal_within_tolerance( *first, *generated ) ) { + _pico_copy_vec( *generated, *first ); } } } -void PicoFixSurfaceNormals(picoSurface_t* surface) -{ - picoVec3_t* normals = (picoVec3_t*)_pico_calloc(surface->numVertexes, sizeof(picoVec3_t)); +void PicoFixSurfaceNormals( picoSurface_t* surface ){ + picoVec3_t* normals = (picoVec3_t*)_pico_calloc( surface->numVertexes, sizeof( picoVec3_t ) ); - _pico_normals_zero(normals, normals + surface->numVertexes); + _pico_normals_zero( normals, normals + surface->numVertexes ); - _pico_triangles_generate_weighted_normals(surface->index, surface->index + surface->numIndexes, surface->xyz, normals); - _pico_vertices_combine_shared_normals(surface->xyz, surface->smoothingGroup, normals, surface->numVertexes); + _pico_triangles_generate_weighted_normals( surface->index, surface->index + surface->numIndexes, surface->xyz, normals ); + _pico_vertices_combine_shared_normals( surface->xyz, surface->smoothingGroup, normals, surface->numVertexes ); - _pico_normals_normalize(normals, normals + surface->numVertexes); + _pico_normals_normalize( normals, normals + surface->numVertexes ); - _pico_normals_assign_generated_normals(surface->normal, surface->normal + surface->numVertexes, normals); + _pico_normals_assign_generated_normals( surface->normal, surface->normal + surface->numVertexes, normals ); - _pico_free(normals); + _pico_free( normals ); } /* -PicoRemapModel() - sea -remaps model material/etc. information using the remappings -contained in the given 'remapFile' (full path to the ascii file to open) -returns 1 on success or 0 on error -*/ + PicoRemapModel() - sea + remaps model material/etc. information using the remappings + contained in the given 'remapFile' (full path to the ascii file to open) + returns 1 on success or 0 on error + */ #define _prm_error_return \ -{ \ - _pico_free_parser( p ); \ - _pico_free_file( remapBuffer ); \ - return 0; \ -} + { \ + _pico_free_parser( p ); \ + _pico_free_file( remapBuffer ); \ + return 0; \ + } + +int PicoRemapModel( picoModel_t *model, char *remapFile ){ + picoParser_t *p; + picoByte_t *remapBuffer; + int remapBufSize; + -int PicoRemapModel( picoModel_t *model, char *remapFile ) -{ - picoParser_t *p; - picoByte_t *remapBuffer; - int remapBufSize; - - /* sanity checks */ - if( model == NULL || remapFile == NULL ) + if ( model == NULL || remapFile == NULL ) { return 0; - + } + /* load remap file contents */ _pico_load_file( remapFile,&remapBuffer,&remapBufSize ); - + /* check result */ - if( remapBufSize == 0 ) - return 1; /* file is empty: no error */ - if( remapBufSize < 0 ) - return 0; /* load failed: error */ - + if ( remapBufSize == 0 ) { + return 1; /* file is empty: no error */ + } + if ( remapBufSize < 0 ) { + return 0; /* load failed: error */ + + } /* create a new pico parser */ p = _pico_new_parser( remapBuffer, remapBufSize ); - if (p == NULL) - { + if ( p == NULL ) { /* ram is really cheap nowadays... */ _prm_error_return; } - + /* doo teh parse */ - while( 1 ) + while ( 1 ) { /* get next token in remap file */ - if (!_pico_parse( p,1 )) + if ( !_pico_parse( p,1 ) ) { break; + } /* skip over c++ style comment lines */ - if (!_pico_stricmp(p->token,"//")) - { + if ( !_pico_stricmp( p->token,"//" ) ) { _pico_parse_skip_rest( p ); continue; } - + /* block for quick material shader name remapping */ /* materials { "m" (=>|->|=) "s" } */ - if( !_pico_stricmp(p->token, "materials" ) ) - { + if ( !_pico_stricmp( p->token, "materials" ) ) { int level = 1; /* check bracket */ - if (!_pico_parse_check( p,1,"{" )) + if ( !_pico_parse_check( p,1,"{" ) ) { _prm_error_return; + } /* process assignments */ - while( 1 ) + while ( 1 ) { - picoShader_t *shader; - char *materialName; - - + picoShader_t *shader; + char *materialName; + + /* get material name */ - if (_pico_parse( p,1 ) == NULL) break; - if (!strlen(p->token)) continue; + if ( _pico_parse( p,1 ) == NULL ) { + break; + } + if ( !strlen( p->token ) ) { + continue; + } materialName = _pico_clone_alloc( p->token ); - if (materialName == NULL) + if ( materialName == NULL ) { _prm_error_return; + } /* handle levels */ - if (p->token[0] == '{') level++; - if (p->token[0] == '}') level--; - if (!level) break; + if ( p->token[0] == '{' ) { + level++; + } + if ( p->token[0] == '}' ) { + level--; + } + if ( !level ) { + break; + } /* get next token (assignment token or shader name) */ - if (!_pico_parse( p,0 )) - { + if ( !_pico_parse( p,0 ) ) { _pico_free( materialName ); _prm_error_return; } /* skip assignment token (if present) */ - if (!strcmp(p->token,"=>") || - !strcmp(p->token,"->") || - !strcmp(p->token,"=")) - { + if ( !strcmp( p->token,"=>" ) || + !strcmp( p->token,"->" ) || + !strcmp( p->token,"=" ) ) { /* simply grab the next token */ - if (!_pico_parse( p,0 )) - { + if ( !_pico_parse( p,0 ) ) { _pico_free( materialName ); _prm_error_return; } @@ -2065,8 +2091,7 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) shader = PicoFindShader( model,materialName,0 ); /* we've found a material matching the name */ - if (shader != NULL) - { + if ( shader != NULL ) { PicoSetShaderName( shader,p->token ); } /* free memory used by material name */ @@ -2078,24 +2103,26 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) } /* block for detailed single material remappings */ /* materials[ "m" ] { key data... } */ - else if (!_pico_stricmp(p->token,"materials[")) - { + else if ( !_pico_stricmp( p->token,"materials[" ) ) { picoShader_t *shader; char *tempMaterialName; int level = 1; /* get material name */ - if (!_pico_parse( p,0 )) + if ( !_pico_parse( p,0 ) ) { _prm_error_return; + } /* temporary copy of material name */ tempMaterialName = _pico_clone_alloc( p->token ); - if (tempMaterialName == NULL) + if ( tempMaterialName == NULL ) { _prm_error_return; + } /* check square closing bracket */ - if (!_pico_parse_check( p,0,"]" )) - _prm_error_return; + if ( !_pico_parse_check( p,0,"]" ) ) { + _prm_error_return; + } /* try to find material by name */ shader = PicoFindShader( model,tempMaterialName,0 ); @@ -2106,47 +2133,60 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) /* we haven't found a material matching the name */ /* so we simply skip the braced section now and */ /* continue parsing with the next main token */ - if (shader == NULL) - { + if ( shader == NULL ) { _pico_parse_skip_braced( p ); continue; } /* check opening bracket */ - if (!_pico_parse_check( p,1,"{" )) + if ( !_pico_parse_check( p,1,"{" ) ) { _prm_error_return; + } /* process material info keys */ - while( 1 ) + while ( 1 ) { /* get key name */ - if (_pico_parse( p,1 ) == NULL) break; - if (!strlen(p->token)) continue; + if ( _pico_parse( p,1 ) == NULL ) { + break; + } + if ( !strlen( p->token ) ) { + continue; + } /* handle levels */ - if (p->token[0] == '{') level++; - if (p->token[0] == '}') level--; - if (!level) break; + if ( p->token[0] == '{' ) { + level++; + } + if ( p->token[0] == '}' ) { + level--; + } + if ( !level ) { + break; + } /* remap shader name */ - if (!_pico_stricmp(p->token,"shader")) - { - if (!_pico_parse( p,0 )) _prm_error_return; + if ( !_pico_stricmp( p->token,"shader" ) ) { + if ( !_pico_parse( p,0 ) ) { + _prm_error_return; + } PicoSetShaderName( shader,p->token ); } /* remap shader map name */ - else if (!_pico_stricmp(p->token,"mapname")) - { - if (!_pico_parse( p,0 )) _prm_error_return; + else if ( !_pico_stricmp( p->token,"mapname" ) ) { + if ( !_pico_parse( p,0 ) ) { + _prm_error_return; + } PicoSetShaderMapName( shader,p->token ); } /* remap shader's ambient color */ - else if (!_pico_stricmp(p->token,"ambient")) - { + else if ( !_pico_stricmp( p->token,"ambient" ) ) { picoColor_t color; - picoVec3_t v; + picoVec3_t v; /* get vector from parser */ - if (!_pico_parse_vec( p,v )) _prm_error_return; + if ( !_pico_parse_vec( p,v ) ) { + _prm_error_return; + } /* store as color */ color[ 0 ] = (picoByte_t)v[ 0 ]; @@ -2157,13 +2197,14 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) PicoSetShaderAmbientColor( shader,color ); } /* remap shader's diffuse color */ - else if (!_pico_stricmp(p->token,"diffuse")) - { + else if ( !_pico_stricmp( p->token,"diffuse" ) ) { picoColor_t color; - picoVec3_t v; + picoVec3_t v; /* get vector from parser */ - if (!_pico_parse_vec( p,v )) _prm_error_return; + if ( !_pico_parse_vec( p,v ) ) { + _prm_error_return; + } /* store as color */ color[ 0 ] = (picoByte_t)v[ 0 ]; @@ -2174,13 +2215,14 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) PicoSetShaderDiffuseColor( shader,color ); } /* remap shader's specular color */ - else if (!_pico_stricmp(p->token,"specular")) - { + else if ( !_pico_stricmp( p->token,"specular" ) ) { picoColor_t color; - picoVec3_t v; + picoVec3_t v; /* get vector from parser */ - if (!_pico_parse_vec( p,v )) _prm_error_return; + if ( !_pico_parse_vec( p,v ) ) { + _prm_error_return; + } /* store as color */ color[ 0 ] = (picoByte_t)v[ 0 ]; @@ -2196,7 +2238,7 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) } /* end 'materials[' */ } - + /* free both parser and file buffer */ _pico_free_parser( p ); _pico_free_file( remapBuffer ); @@ -2207,15 +2249,14 @@ int PicoRemapModel( picoModel_t *model, char *remapFile ) /* -PicoAddTriangleToModel() - jhefty -A nice way to add individual triangles to the model. -Chooses an appropriate surface based on the shader, or adds a new surface if necessary -*/ - -void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, - int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, - picoShader_t* shader, const char *name, picoIndex_t* smoothingGroup ) -{ + PicoAddTriangleToModel() - jhefty + A nice way to add individual triangles to the model. + Chooses an appropriate surface based on the shader, or adds a new surface if necessary + */ + +void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, + int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, + picoShader_t* shader, const char *name, picoIndex_t* smoothingGroup ){ int i,j; int vertDataIndex; picoSurface_t* workSurface = NULL; @@ -2224,21 +2265,19 @@ void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** for ( i = 0 ; i < model->numSurfaces ; i++ ) { workSurface = model->surface[i]; - if ( !name || !strcmp(workSurface->name, name) ) - if ( workSurface->shader == shader ) - { - break; + if ( !name || !strcmp( workSurface->name, name ) ) { + if ( workSurface->shader == shader ) { + break; + } } } /* no surface uses this shader yet, so create a new surface */ - if ( !workSurface || i >=model->numSurfaces ) - { + if ( !workSurface || i >= model->numSurfaces ) { /* create a new surface in the model for the unique shader */ - workSurface = PicoNewSurface(model); - if ( !workSurface ) - { - _pico_printf ( PICO_ERROR , "Could not allocate a new surface!\n" ); + workSurface = PicoNewSurface( model ); + if ( !workSurface ) { + _pico_printf( PICO_ERROR, "Could not allocate a new surface!\n" ); return; } @@ -2249,38 +2288,37 @@ void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** } /* add the triangle data to the surface */ - for ( i = 0 ; i < 3 ; i++ ) + for ( i = 0 ; i < 3 ; i++ ) { /* get the next free spot in the index array */ - int newVertIndex = PicoGetSurfaceNumIndexes ( workSurface ); + int newVertIndex = PicoGetSurfaceNumIndexes( workSurface ); /* get the index of the vertex that we're going to store at newVertIndex */ - vertDataIndex = PicoFindSurfaceVertexNum ( workSurface , *xyz[i] , *normals[i] , numSTs , st[i] , numColors , colors[i], smoothingGroup[i]); + vertDataIndex = PicoFindSurfaceVertexNum( workSurface, *xyz[i], *normals[i], numSTs, st[i], numColors, colors[i], smoothingGroup[i] ); /* the vertex wasn't found, so create a new vertex in the pool from the data we have */ - if ( vertDataIndex == -1 ) - { + if ( vertDataIndex == -1 ) { /* find the next spot for a new vertex */ - vertDataIndex = PicoGetSurfaceNumVertexes ( workSurface ); + vertDataIndex = PicoGetSurfaceNumVertexes( workSurface ); /* assign the data to it */ - PicoSetSurfaceXYZ ( workSurface ,vertDataIndex , *xyz[i] ); - PicoSetSurfaceNormal ( workSurface , vertDataIndex , *normals[i] ); + PicoSetSurfaceXYZ( workSurface,vertDataIndex, *xyz[i] ); + PicoSetSurfaceNormal( workSurface, vertDataIndex, *normals[i] ); /* make sure to copy over all available ST's and colors for the vertex */ for ( j = 0 ; j < numColors ; j++ ) { - PicoSetSurfaceColor( workSurface , j , vertDataIndex , colors[i][j] ); + PicoSetSurfaceColor( workSurface, j, vertDataIndex, colors[i][j] ); } for ( j = 0 ; j < numSTs ; j++ ) { - PicoSetSurfaceST ( workSurface , j , vertDataIndex , st[i][j] ); + PicoSetSurfaceST( workSurface, j, vertDataIndex, st[i][j] ); } - PicoSetSurfaceSmoothingGroup ( workSurface , vertDataIndex , smoothingGroup[i] ); + PicoSetSurfaceSmoothingGroup( workSurface, vertDataIndex, smoothingGroup[i] ); } - /* add this vertex to the triangle */ - PicoSetSurfaceIndex ( workSurface , newVertIndex , vertDataIndex ); + /* add this vertex to the triangle */ + PicoSetSurfaceIndex( workSurface, newVertIndex, vertDataIndex ); } } diff --git a/libs/picomodel/picomodules.c b/libs/picomodel/picomodules.c index 59a6a9ee..9a973724 100644 --- a/libs/picomodel/picomodules.c +++ b/libs/picomodel/picomodules.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -61,34 +61,34 @@ extern const picoModule_t picoModuleTerrain; /* list of all supported file format modules */ const picoModule_t *picoModules[] = { - &picoModuleMD3, /* quake3 arena md3 */ - &picoModule3DS, /* autodesk 3ds */ - &picoModuleASE, /* autodesk ase */ - &picoModuleMS3D, /* milkshape3d */ - &picoModuleMDC, /* return to castle wolfenstein mdc */ - &picoModuleMD2, /* quake2 md2 */ - &picoModuleFM, /* heretic2 fm */ - &picoModuleLWO, /* lightwave object */ - &picoModuleTerrain, /* picoterrain object */ - &picoModuleOBJ, /* wavefront object */ - NULL /* arnold */ + &picoModuleMD3, /* quake3 arena md3 */ + &picoModule3DS, /* autodesk 3ds */ + &picoModuleASE, /* autodesk ase */ + &picoModuleMS3D, /* milkshape3d */ + &picoModuleMDC, /* return to castle wolfenstein mdc */ + &picoModuleMD2, /* quake2 md2 */ + &picoModuleFM, /* heretic2 fm */ + &picoModuleLWO, /* lightwave object */ + &picoModuleTerrain, /* picoterrain object */ + &picoModuleOBJ, /* wavefront object */ + NULL /* arnold */ }; /* -PicoModuleList() -returns a pointer to the module list and optionally stores -the number of supported modules in 'numModules'. Note that -this param can be NULL when the count is not needed. -*/ + PicoModuleList() + returns a pointer to the module list and optionally stores + the number of supported modules in 'numModules'. Note that + this param can be NULL when the count is not needed. + */ -const picoModule_t **PicoModuleList( int *numModules ) -{ +const picoModule_t **PicoModuleList( int *numModules ){ /* get module count */ - if( numModules != NULL ) - for( (*numModules) = 0; picoModules[ *numModules ] != NULL; (*numModules)++ ); - + if ( numModules != NULL ) { + for ( ( *numModules ) = 0; picoModules[ *numModules ] != NULL; ( *numModules )++ ) ; + } + /* return list of modules */ return (const picoModule_t**) picoModules; } diff --git a/libs/picomodel/pm_3ds.c b/libs/picomodel/pm_3ds.c index 5ec21bf6..83a1446e 100644 --- a/libs/picomodel/pm_3ds.c +++ b/libs/picomodel/pm_3ds.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -51,88 +51,86 @@ static picoColor_t white = { 255,255,255,255 }; */ /* uncomment when debugging this module */ /* #define DEBUG_PM_3DS -#define DEBUG_PM_3DS_EX */ + #define DEBUG_PM_3DS_EX */ /* structure holding persistent 3ds loader specific data used */ /* to store formerly static vars to keep the module reentrant */ /* safe. put everything that needs to be static in here. */ typedef struct S3dsLoaderPers { - picoModel_t *model; /* ptr to output model */ - picoSurface_t *surface; /* ptr to current surface */ - picoShader_t *shader; /* ptr to current shader */ - picoByte_t *bufptr; /* ptr to raw data */ - char *basename; /* ptr to model base name (eg. jeep) */ - int cofs; - int maxofs; + picoModel_t *model; /* ptr to output model */ + picoSurface_t *surface; /* ptr to current surface */ + picoShader_t *shader; /* ptr to current shader */ + picoByte_t *bufptr; /* ptr to raw data */ + char *basename; /* ptr to model base name (eg. jeep) */ + int cofs; + int maxofs; } T3dsLoaderPers; /* 3ds chunk types that we use */ enum { - /* primary chunk */ - CHUNK_MAIN = 0x4D4D, + /* primary chunk */ + CHUNK_MAIN = 0x4D4D, /* main chunks */ - CHUNK_VERSION = 0x0002, - CHUNK_EDITOR_CONFIG = 0x3D3E, - CHUNK_EDITOR_DATA = 0x3D3D, - CHUNK_KEYFRAME_DATA = 0xB000, + CHUNK_VERSION = 0x0002, + CHUNK_EDITOR_CONFIG = 0x3D3E, + CHUNK_EDITOR_DATA = 0x3D3D, + CHUNK_KEYFRAME_DATA = 0xB000, /* editor data sub chunks */ - CHUNK_MATERIAL = 0xAFFF, - CHUNK_OBJECT = 0x4000, + CHUNK_MATERIAL = 0xAFFF, + CHUNK_OBJECT = 0x4000, /* material sub chunks */ - CHUNK_MATNAME = 0xA000, - CHUNK_MATDIFFUSE = 0xA020, - CHUNK_MATMAP = 0xA200, - CHUNK_MATMAPFILE = 0xA300, + CHUNK_MATNAME = 0xA000, + CHUNK_MATDIFFUSE = 0xA020, + CHUNK_MATMAP = 0xA200, + CHUNK_MATMAPFILE = 0xA300, /* lets us know we're reading a new object */ - CHUNK_OBJECT_MESH = 0x4100, + CHUNK_OBJECT_MESH = 0x4100, /* object mesh sub chunks */ - CHUNK_OBJECT_VERTICES = 0x4110, - CHUNK_OBJECT_FACES = 0x4120, - CHUNK_OBJECT_MATERIAL = 0x4130, - CHUNK_OBJECT_UV = 0x4140, + CHUNK_OBJECT_VERTICES = 0x4110, + CHUNK_OBJECT_FACES = 0x4120, + CHUNK_OBJECT_MATERIAL = 0x4130, + CHUNK_OBJECT_UV = 0x4140, }; #ifdef DEBUG_PM_3DS static struct { - int id; + int id; char *name; } debugChunkNames[] = { - { CHUNK_MAIN , "CHUNK_MAIN" }, - { CHUNK_VERSION , "CHUNK_VERSION" }, - { CHUNK_EDITOR_CONFIG , "CHUNK_EDITOR_CONFIG" }, - { CHUNK_EDITOR_DATA , "CHUNK_EDITOR_DATA" }, - { CHUNK_KEYFRAME_DATA , "CHUNK_KEYFRAME_DATA" }, - { CHUNK_MATERIAL , "CHUNK_MATERIAL" }, - { CHUNK_OBJECT , "CHUNK_OBJECT" }, - { CHUNK_MATNAME , "CHUNK_MATNAME" }, - { CHUNK_MATDIFFUSE , "CHUNK_MATDIFFUSE" }, - { CHUNK_MATMAP , "CHUNK_MATMAP" }, - { CHUNK_MATMAPFILE , "CHUNK_MATMAPFILE" }, - { CHUNK_OBJECT_MESH , "CHUNK_OBJECT_MESH" }, - { CHUNK_OBJECT_VERTICES , "CHUNK_OBJECT_VERTICES" }, - { CHUNK_OBJECT_FACES , "CHUNK_OBJECT_FACES" }, - { CHUNK_OBJECT_MATERIAL , "CHUNK_OBJECT_MATERIAL" }, - { CHUNK_OBJECT_UV , "CHUNK_OBJECT_UV" }, - { 0 , NULL } + { CHUNK_MAIN, "CHUNK_MAIN" }, + { CHUNK_VERSION, "CHUNK_VERSION" }, + { CHUNK_EDITOR_CONFIG, "CHUNK_EDITOR_CONFIG" }, + { CHUNK_EDITOR_DATA, "CHUNK_EDITOR_DATA" }, + { CHUNK_KEYFRAME_DATA, "CHUNK_KEYFRAME_DATA" }, + { CHUNK_MATERIAL, "CHUNK_MATERIAL" }, + { CHUNK_OBJECT, "CHUNK_OBJECT" }, + { CHUNK_MATNAME, "CHUNK_MATNAME" }, + { CHUNK_MATDIFFUSE, "CHUNK_MATDIFFUSE" }, + { CHUNK_MATMAP, "CHUNK_MATMAP" }, + { CHUNK_MATMAPFILE, "CHUNK_MATMAPFILE" }, + { CHUNK_OBJECT_MESH, "CHUNK_OBJECT_MESH" }, + { CHUNK_OBJECT_VERTICES, "CHUNK_OBJECT_VERTICES" }, + { CHUNK_OBJECT_FACES, "CHUNK_OBJECT_FACES" }, + { CHUNK_OBJECT_MATERIAL, "CHUNK_OBJECT_MATERIAL" }, + { CHUNK_OBJECT_UV, "CHUNK_OBJECT_UV" }, + { 0, NULL } }; -static char *DebugGetChunkName (int id) -{ - int i,max; /* imax? ;) */ - max = sizeof(debugChunkNames) / sizeof(debugChunkNames[0]); +static char *DebugGetChunkName( int id ){ + int i,max; /* imax? ;) */ + max = sizeof( debugChunkNames ) / sizeof( debugChunkNames[0] ); - for (i=0; ilen)) + if ( bufSize < (int) _pico_little_long( chunk->len ) ) { return PICO_PMV_ERROR_SIZE; + } /* check 3ds magic */ - if (_pico_little_short(chunk->id) != CHUNK_MAIN) + if ( _pico_little_short( chunk->id ) != CHUNK_MAIN ) { return PICO_PMV_ERROR_IDENT; + } /* file seems to be a valid 3ds */ return PICO_PMV_OK; } -static T3dsChunk *GetChunk (T3dsLoaderPers *pers) -{ +static T3dsChunk *GetChunk( T3dsLoaderPers *pers ){ T3dsChunk *chunk; /* sanity check */ - if (pers->cofs > pers->maxofs) return 0; + if ( pers->cofs > pers->maxofs ) { + return 0; + } #ifdef DEBUG_PM_3DS /* printf("GetChunk: pers->cofs %x\n",pers->cofs); */ #endif /* fill in pointer to chunk */ chunk = (T3dsChunk *)&pers->bufptr[ pers->cofs ]; - if (!chunk) return NULL; + if ( !chunk ) { + return NULL; + } - chunk->id = _pico_little_short(chunk->id ); - chunk->len = _pico_little_long (chunk->len); + chunk->id = _pico_little_short( chunk->id ); + chunk->len = _pico_little_long( chunk->len ); /* advance in buffer */ - pers->cofs += sizeof(T3dsChunk); + pers->cofs += sizeof( T3dsChunk ); /* this means yay */ return chunk; } -static int GetASCIIZ (T3dsLoaderPers *pers, char *dest, int max) -{ +static int GetASCIIZ( T3dsLoaderPers *pers, char *dest, int max ){ int pos = 0; int ch; - for (;;) + for (;; ) { ch = pers->bufptr[ pers->cofs++ ]; - if (ch == '\0') break; - if (pers->cofs >= pers->maxofs) - { + if ( ch == '\0' ) { + break; + } + if ( pers->cofs >= pers->maxofs ) { dest[ pos ] = '\0'; return 0; } dest[ pos++ ] = ch; - if (pos >= max) break; + if ( pos >= max ) { + break; + } } dest[ pos ] = '\0'; return 1; } -static picoByte_t GetByte (T3dsLoaderPers *pers) -{ +static picoByte_t GetByte( T3dsLoaderPers *pers ){ picoByte_t *value; /* sanity check */ - if (pers->cofs > pers->maxofs) return 0; + if ( pers->cofs > pers->maxofs ) { + return 0; + } /* get and return value */ - value = (picoByte_t *)(pers->bufptr + pers->cofs); + value = (picoByte_t *)( pers->bufptr + pers->cofs ); pers->cofs += 1; return *value; } -static int GetWord (T3dsLoaderPers *pers) -{ +static int GetWord( T3dsLoaderPers *pers ){ unsigned short *value; /* sanity check */ - if (pers->cofs > pers->maxofs) return 0; + if ( pers->cofs > pers->maxofs ) { + return 0; + } /* get and return value */ - value = (unsigned short *)(pers->bufptr + pers->cofs); + value = (unsigned short *)( pers->bufptr + pers->cofs ); pers->cofs += 2; - return _pico_little_short(*value); + return _pico_little_short( *value ); } -static float GetFloat (T3dsLoaderPers *pers) -{ +static float GetFloat( T3dsLoaderPers *pers ){ float *value; /* sanity check */ - if (pers->cofs > pers->maxofs) return 0; + if ( pers->cofs > pers->maxofs ) { + return 0; + } /* get and return value */ - value = (float *)(pers->bufptr + pers->cofs); + value = (float *)( pers->bufptr + pers->cofs ); pers->cofs += 4; - return _pico_little_float(*value); + return _pico_little_float( *value ); } -static int GetMeshVertices (T3dsLoaderPers *pers) -{ +static int GetMeshVertices( T3dsLoaderPers *pers ){ int numVerts; int i; /* get number of verts for this surface */ - numVerts = GetWord(pers); + numVerts = GetWord( pers ); #ifdef DEBUG_PM_3DS - printf("GetMeshVertices: numverts %d\n",numVerts); + printf( "GetMeshVertices: numverts %d\n",numVerts ); #endif /* read in vertices for current surface */ - for (i=0; isurface,i,v ); - PicoSetSurfaceColor( pers->surface,0,i,white ); /* ydnar */ + PicoSetSurfaceColor( pers->surface,0,i,white ); /* ydnar */ #ifdef DEBUG_PM_3DS_EX - printf("Vertex: x: %f y: %f z: %f\n",v[0],v[1],v[2]); + printf( "Vertex: x: %f y: %f z: %f\n",v[0],v[1],v[2] ); #endif } /* success (no errors occured) */ return 1; } -static int GetMeshFaces (T3dsLoaderPers *pers) -{ +static int GetMeshFaces( T3dsLoaderPers *pers ){ int numFaces; int i; /* get number of faces for this surface */ - numFaces = GetWord(pers); + numFaces = GetWord( pers ); #ifdef DEBUG_PM_3DS - printf("GetMeshFaces: numfaces %d\n",numFaces); + printf( "GetMeshFaces: numfaces %d\n",numFaces ); #endif /* read in vertex indices for current surface */ - for (i=0; isurface, (i * 3 + 0), (picoIndex_t)face.a ); - PicoSetSurfaceIndex( pers->surface, (i * 3 + 1), (picoIndex_t)face.b ); - PicoSetSurfaceIndex( pers->surface, (i * 3 + 2), (picoIndex_t)face.c ); + PicoSetSurfaceIndex( pers->surface, ( i * 3 + 0 ), (picoIndex_t)face.a ); + PicoSetSurfaceIndex( pers->surface, ( i * 3 + 1 ), (picoIndex_t)face.b ); + PicoSetSurfaceIndex( pers->surface, ( i * 3 + 2 ), (picoIndex_t)face.c ); #ifdef DEBUG_PM_3DS_EX - printf("Face: a: %d b: %d c: %d (%d)\n",face.a,face.b,face.c,face.visible); + printf( "Face: a: %d b: %d c: %d (%d)\n",face.a,face.b,face.c,face.visible ); #endif } /* success (no errors occured) */ return 1; } -static int GetMeshTexCoords (T3dsLoaderPers *pers) -{ +static int GetMeshTexCoords( T3dsLoaderPers *pers ){ int numTexCoords; int i; /* get number of uv coords for this surface */ - numTexCoords = GetWord(pers); + numTexCoords = GetWord( pers ); #ifdef DEBUG_PM_3DS - printf("GetMeshTexCoords: numcoords %d\n",numTexCoords); + printf( "GetMeshTexCoords: numcoords %d\n",numTexCoords ); #endif /* read in uv coords for current surface */ - for (i=0; isurface == NULL) + if ( pers->surface == NULL ) { continue; - + } + /* add current uv */ PicoSetSurfaceST( pers->surface,0,i,uv ); #ifdef DEBUG_PM_3DS_EX - printf("u: %f v: %f\n",uv[0],uv[1]); + printf( "u: %f v: %f\n",uv[0],uv[1] ); #endif } /* success (no errors occured) */ return 1; } -static int GetMeshShader (T3dsLoaderPers *pers) -{ +static int GetMeshShader( T3dsLoaderPers *pers ){ char shaderName[255] = { 0 }; picoShader_t *shader; - int numSharedVerts; - int setShaderName = 0; - int i; - + int numSharedVerts; + int setShaderName = 0; + int i; + /* the shader is either the color or the texture map of the */ /* object. it can also hold other information like the brightness, */ /* shine, etc. stuff we don't really care about. we just want the */ /* color, or the texture map file name really */ /* get in the shader name */ - if (!GetASCIIZ(pers,shaderName,sizeof(shaderName))) + if ( !GetASCIIZ( pers,shaderName,sizeof( shaderName ) ) ) { return 0; - + } + /* ydnar: trim to first whitespace */ _pico_first_token( shaderName ); - + /* now that we have the shader name we need to go through all of */ /* the shaders and check the name against each shader. when we */ /* find a shader in our shader list that matches this name we */ @@ -401,19 +407,17 @@ static int GetMeshShader (T3dsLoaderPers *pers) shader = PicoFindShader( pers->model, shaderName, 1 ); /* we've found a matching shader */ - if ((shader != NULL) && pers->surface) - { - char mapName[1024+1]; + if ( ( shader != NULL ) && pers->surface ) { + char mapName[1024 + 1]; char *mapNamePtr; - memset( mapName,0,sizeof(mapName) ); + memset( mapName,0,sizeof( mapName ) ); /* get ptr to shader's map name */ mapNamePtr = PicoGetShaderMapName( shader ); /* we have a valid map name ptr */ - if (mapNamePtr != NULL) - { - char temp[128]; + if ( mapNamePtr != NULL ) { + char temp[128]; const char *name; /* copy map name to local buffer */ @@ -421,14 +425,15 @@ static int GetMeshShader (T3dsLoaderPers *pers) /* extract file name */ name = _pico_nopath( mapName ); - strncpy( temp, name, sizeof(temp) ); + strncpy( temp, name, sizeof( temp ) ); /* remove file extension */ /* name = _pico_setfext( name,"" ); */ /* assign default name if no name available */ - if (strlen(temp) < 1) - strcpy(temp,pers->basename); + if ( strlen( temp ) < 1 ) { + strcpy( temp,pers->basename ); + } /* build shader name */ _pico_strlwr( temp ); /* gaynux update -sea */ @@ -444,9 +449,8 @@ static int GetMeshShader (T3dsLoaderPers *pers) } } /* we didn't set a shader name; throw out warning */ - if (!setShaderName) - { - _pico_printf( PICO_WARNING,"3DS mesh is missing shader name"); + if ( !setShaderName ) { + _pico_printf( PICO_WARNING,"3DS mesh is missing shader name" ); } /* we don't process the list of shared vertices here; there is a */ /* short int that gives the number of faces of the mesh concerned */ @@ -454,80 +458,80 @@ static int GetMeshShader (T3dsLoaderPers *pers) /* 0000 means the first face of the (4120) face list */ /* get number of shared verts */ - numSharedVerts = GetWord(pers); + numSharedVerts = GetWord( pers ); #ifdef DEBUG_PM_3DS - printf("GetMeshShader: uses shader '%s' (nsv %d)\n",shaderName,numSharedVerts); + printf( "GetMeshShader: uses shader '%s' (nsv %d)\n",shaderName,numSharedVerts ); #endif /* skip list of shared verts */ - for (i=0; ishader ) - { + if ( pers->shader ) { PicoSetShaderDiffuseColor( pers->shader,color ); } #ifdef DEBUG_PM_3DS - printf("GetDiffuseColor: %d %d %d\n",color[0],color[1],color[2]); + printf( "GetDiffuseColor: %d %d %d\n",color[0],color[1],color[2] ); #endif /* success (no errors occured) */ return 1; } -static int DoNextEditorDataChunk (T3dsLoaderPers *pers, long endofs) -{ +static int DoNextEditorDataChunk( T3dsLoaderPers *pers, long endofs ){ T3dsChunk *chunk; #ifdef DEBUG_PM_3DS_EX - printf("DoNextEditorDataChunk: endofs %d\n",endofs); + printf( "DoNextEditorDataChunk: endofs %d\n",endofs ); #endif - while (pers->cofs < endofs) + while ( pers->cofs < endofs ) { long nextofs = pers->cofs; - if ((chunk = GetChunk(pers)) == NULL) return 0; - if (!chunk->len) return 0; + if ( ( chunk = GetChunk( pers ) ) == NULL ) { + return 0; + } + if ( !chunk->len ) { + return 0; + } nextofs += chunk->len; #ifdef DEBUG_PM_3DS_EX - printf("Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName(chunk->id),chunk->len,pers->cofs); + printf( "Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName( chunk->id ),chunk->len,pers->cofs ); #endif /*** meshes ***/ - if (chunk->id == CHUNK_OBJECT) - { + if ( chunk->id == CHUNK_OBJECT ) { picoSurface_t *surface; char surfaceName[ 0xff ] = { 0 }; /* read in surface name */ - if( !GetASCIIZ(pers,surfaceName,sizeof(surfaceName)) ) + if ( !GetASCIIZ( pers,surfaceName,sizeof( surfaceName ) ) ) { return 0; /* this is bad */ + } //PicoGetSurfaceName /* ignore NULL name surfaces */ // if( surfaceName /* allocate a pico surface */ surface = PicoNewSurface( pers->model ); - if( surface == NULL ) - { + if ( surface == NULL ) { pers->surface = NULL; return 0; /* this is bad too */ } @@ -541,66 +545,67 @@ static int DoNextEditorDataChunk (T3dsLoaderPers *pers, long endofs) PicoSetSurfaceName( pers->surface,surfaceName ); /* continue mess with object's sub chunks */ - DoNextEditorDataChunk(pers,nextofs); + DoNextEditorDataChunk( pers,nextofs ); continue; } - if (chunk->id == CHUNK_OBJECT_MESH) - { + if ( chunk->id == CHUNK_OBJECT_MESH ) { /* continue mess with mesh's sub chunks */ - if (!DoNextEditorDataChunk(pers,nextofs)) return 0; + if ( !DoNextEditorDataChunk( pers,nextofs ) ) { + return 0; + } continue; } - if (chunk->id == CHUNK_OBJECT_VERTICES) - { - if (!GetMeshVertices(pers)) return 0; + if ( chunk->id == CHUNK_OBJECT_VERTICES ) { + if ( !GetMeshVertices( pers ) ) { + return 0; + } continue; } - if (chunk->id == CHUNK_OBJECT_FACES) - { - if (!GetMeshFaces(pers)) return 0; + if ( chunk->id == CHUNK_OBJECT_FACES ) { + if ( !GetMeshFaces( pers ) ) { + return 0; + } continue; } - if (chunk->id == CHUNK_OBJECT_UV) - { - if (!GetMeshTexCoords(pers)) return 0; + if ( chunk->id == CHUNK_OBJECT_UV ) { + if ( !GetMeshTexCoords( pers ) ) { + return 0; + } continue; } - if (chunk->id == CHUNK_OBJECT_MATERIAL) - { - if (!GetMeshShader(pers)) return 0; + if ( chunk->id == CHUNK_OBJECT_MATERIAL ) { + if ( !GetMeshShader( pers ) ) { + return 0; + } continue; } /*** materials ***/ - if (chunk->id == CHUNK_MATERIAL) - { + if ( chunk->id == CHUNK_MATERIAL ) { /* new shader specific things should be */ /* initialized right here */ picoShader_t *shader; /* allocate a pico shader */ - shader = PicoNewShader( pers->model ); /* ydnar */ - if( shader == NULL ) - { + shader = PicoNewShader( pers->model ); /* ydnar */ + if ( shader == NULL ) { pers->shader = NULL; return 0; /* this is bad too */ } - + /* assign ptr to current shader */ pers->shader = shader; /* continue and process the material's sub chunks */ - DoNextEditorDataChunk(pers,nextofs); + DoNextEditorDataChunk( pers,nextofs ); continue; } - if (chunk->id == CHUNK_MATNAME) - { + if ( chunk->id == CHUNK_MATNAME ) { /* new material's names should be stored here. note that */ /* GetMeshMaterial returns the name of the material that */ /* is used by the mesh. new material names are set HERE. */ /* but for now we skip the new material's name ... */ - if (pers->shader) - { - char *name = (char*) (pers->bufptr + pers->cofs); + if ( pers->shader ) { + char *name = (char*) ( pers->bufptr + pers->cofs ); char *cleanedName = _pico_clone_alloc( name ); _pico_first_token( cleanedName ); PicoSetShaderName( pers->shader, cleanedName ); @@ -610,69 +615,70 @@ static int DoNextEditorDataChunk (T3dsLoaderPers *pers, long endofs) _pico_free( cleanedName ); } } - if (chunk->id == CHUNK_MATDIFFUSE) - { + if ( chunk->id == CHUNK_MATDIFFUSE ) { /* todo: color for last inserted new material should be */ /* stored somewhere by GetDiffuseColor */ - if (!GetDiffuseColor(pers)) return 0; + if ( !GetDiffuseColor( pers ) ) { + return 0; + } /* rest of chunk is skipped here */ } - if (chunk->id == CHUNK_MATMAP) - { + if ( chunk->id == CHUNK_MATMAP ) { /* continue and process the material map sub chunks */ - DoNextEditorDataChunk(pers,nextofs); + DoNextEditorDataChunk( pers,nextofs ); continue; } - if (chunk->id == CHUNK_MATMAPFILE) - { + if ( chunk->id == CHUNK_MATMAPFILE ) { /* map file name for last inserted new material should */ /* be stored here. but for now we skip this too ... */ - if( pers->shader ) - { - char *name = (char *)(pers->bufptr + pers->cofs); + if ( pers->shader ) { + char *name = (char *)( pers->bufptr + pers->cofs ); PicoSetShaderMapName( pers->shader,name ); #ifdef DEBUG_PM_3DS - printf("NewShaderMapfile: '%s'\n",name); + printf( "NewShaderMapfile: '%s'\n",name ); #endif } } /*** keyframes ***/ - if (chunk->id == CHUNK_KEYFRAME_DATA) - { + if ( chunk->id == CHUNK_KEYFRAME_DATA ) { /* well umm, this is a bit too much since we don't really */ /* need model animation sequences right now. we skip this */ #ifdef DEBUG_PM_3DS - printf("KeyframeData: len %d\n",chunk->len); + printf( "KeyframeData: len %d\n",chunk->len ); #endif } /* skip unknown chunk */ pers->cofs = nextofs; - if (pers->cofs >= pers->maxofs) break; + if ( pers->cofs >= pers->maxofs ) { + break; + } } return 1; } -static int DoNextChunk (T3dsLoaderPers *pers, int endofs) -{ +static int DoNextChunk( T3dsLoaderPers *pers, int endofs ){ T3dsChunk *chunk; #ifdef DEBUG_PM_3DS - printf("DoNextChunk: endofs %d\n",endofs); + printf( "DoNextChunk: endofs %d\n",endofs ); #endif - while (pers->cofs < endofs) + while ( pers->cofs < endofs ) { long nextofs = pers->cofs; - if ((chunk = GetChunk(pers)) == NULL) return 0; - if (!chunk->len) return 0; + if ( ( chunk = GetChunk( pers ) ) == NULL ) { + return 0; + } + if ( !chunk->len ) { + return 0; + } nextofs += chunk->len; #ifdef DEBUG_PM_3DS_EX - printf("Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName(chunk->id),chunk->len,pers->cofs); + printf( "Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName( chunk->id ),chunk->len,pers->cofs ); #endif /*** version ***/ - if (chunk->id == CHUNK_VERSION) - { + if ( chunk->id == CHUNK_VERSION ) { /* at this point i get the 3ds file version. since there */ /* might be new additions to the 3ds file format in 4.0 */ /* it might be a good idea to store the version somewhere */ @@ -680,61 +686,61 @@ static int DoNextChunk (T3dsLoaderPers *pers, int endofs) /* get the version */ int version; - version = GetWord(pers); - GetWord(pers); + version = GetWord( pers ); + GetWord( pers ); #ifdef DEBUG_PM_3DS - printf("FileVersion: %d\n",version); + printf( "FileVersion: %d\n",version ); #endif /* throw out a warning for version 4 models */ - if (version == 4) - { + if ( version == 4 ) { _pico_printf( PICO_WARNING, - "3DS version is 4. Model might load incorrectly."); + "3DS version is 4. Model might load incorrectly." ); } /* store the 3ds file version in pico special field 0 */ /* PicoSetSurfaceSpecial(pers->surface,0,version); */ /* ydnar: this was causing a crash accessing uninitialized surface */ - + /* rest of chunk is skipped here */ } /*** editor data ***/ - if (chunk->id == CHUNK_EDITOR_DATA) - { - if (!DoNextEditorDataChunk(pers,nextofs)) return 0; + if ( chunk->id == CHUNK_EDITOR_DATA ) { + if ( !DoNextEditorDataChunk( pers,nextofs ) ) { + return 0; + } continue; } /* skip unknown chunk */ pers->cofs = nextofs; - if (pers->cofs >= pers->maxofs) break; + if ( pers->cofs >= pers->maxofs ) { + break; + } } return 1; } /* _3ds_load: * loads an autodesk 3ds model file. -*/ -static picoModel_t *_3ds_load( PM_PARAMS_LOAD ) -{ - T3dsLoaderPers pers; - picoModel_t *model; - char basename[128]; + */ +static picoModel_t *_3ds_load( PM_PARAMS_LOAD ){ + T3dsLoaderPers pers; + picoModel_t *model; + char basename[128]; /* create a new pico model */ model = PicoNewModel(); - if (model == NULL) - { + if ( model == NULL ) { /* user must have some serious ram problems ;) */ return NULL; } /* get model's base name (eg. jeep from c:\models\jeep.3ds) */ - memset( basename,0,sizeof(basename) ); - strncpy( basename,_pico_nopath(fileName),sizeof(basename) ); + memset( basename,0,sizeof( basename ) ); + strncpy( basename,_pico_nopath( fileName ),sizeof( basename ) ); _pico_setfext( basename,"" ); /* initialize persistant vars (formerly static) */ pers.model = model; - pers.bufptr = (picoByte_t *)_pico_alloc(bufSize); - memcpy(pers.bufptr, buffer, bufSize); + pers.bufptr = (picoByte_t *)_pico_alloc( bufSize ); + memcpy( pers.bufptr, buffer, bufSize ); pers.basename = (char *)basename; pers.maxofs = bufSize; pers.cofs = 0L; @@ -745,13 +751,12 @@ static picoModel_t *_3ds_load( PM_PARAMS_LOAD ) PicoSetModelFileName( model,fileName ); /* skip first chunk in file (magic) */ - GetChunk(&pers); + GetChunk( &pers ); /* process chunks */ - if (!DoNextChunk(&pers,pers.maxofs)) - { + if ( !DoNextChunk( &pers,pers.maxofs ) ) { /* well, bleh i guess */ - PicoFreeModel(model); + PicoFreeModel( model ); return NULL; } /* return allocated pico model */ @@ -761,15 +766,15 @@ static picoModel_t *_3ds_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModule3DS = { - "0.86-b", /* module version string */ - "Autodesk 3Dstudio", /* module display name */ - "seaw0lf", /* author's name */ - "2002 seaw0lf", /* module copyright */ + "0.86-b", /* module version string */ + "Autodesk 3Dstudio", /* module display name */ + "seaw0lf", /* author's name */ + "2002 seaw0lf", /* module copyright */ { - "3ds",NULL,NULL,NULL /* default extensions to use */ + "3ds",NULL,NULL,NULL /* default extensions to use */ }, - _3ds_canload, /* validation routine */ - _3ds_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _3ds_canload, /* validation routine */ + _3ds_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_ase.c b/libs/picomodel/pm_ase.c index 6905431e..001cca4f 100644 --- a/libs/picomodel/pm_ase.c +++ b/libs/picomodel/pm_ase.c @@ -1,43 +1,43 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other aseMaterialList provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other aseMaterialList provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ /* marker */ #define PM_ASE_C /* uncomment when debugging this module */ -//#define DEBUG_PM_ASE +//#define DEBUG_PM_ASE //#define DEBUG_PM_ASE_EX @@ -61,25 +61,23 @@ typedef struct aseSubMaterial_s struct aseSubMaterial_s* next; int subMtlId; picoShader_t* shader; - + } aseSubMaterial_t; typedef struct aseMaterial_s { struct aseMaterial_s* next; struct aseSubMaterial_s* subMtls; - int mtlId; + int mtlId; } aseMaterial_t; /* Material/SubMaterial management functions */ -static aseMaterial_t* _ase_get_material ( aseMaterial_t* list , int mtlIdParent ) -{ +static aseMaterial_t* _ase_get_material( aseMaterial_t* list, int mtlIdParent ){ aseMaterial_t* mtl = list; while ( mtl ) { - if ( mtlIdParent == mtl->mtlId ) - { + if ( mtlIdParent == mtl->mtlId ) { break; } mtl = mtl->next; @@ -87,22 +85,19 @@ static aseMaterial_t* _ase_get_material ( aseMaterial_t* list , int mtlIdParent return mtl; } -static aseSubMaterial_t* _ase_get_submaterial ( aseMaterial_t* list, int mtlIdParent , int subMtlId ) -{ - aseMaterial_t* parent = _ase_get_material ( list , mtlIdParent ); +static aseSubMaterial_t* _ase_get_submaterial( aseMaterial_t* list, int mtlIdParent, int subMtlId ){ + aseMaterial_t* parent = _ase_get_material( list, mtlIdParent ); aseSubMaterial_t* subMtl = NULL; - if ( !parent ) - { - _pico_printf ( PICO_ERROR , "No ASE material exists with id %i\n" , mtlIdParent ); + if ( !parent ) { + _pico_printf( PICO_ERROR, "No ASE material exists with id %i\n", mtlIdParent ); return NULL; } subMtl = parent->subMtls; while ( subMtl ) { - if ( subMtlId == subMtl->subMtlId ) - { + if ( subMtlId == subMtl->subMtlId ) { break; } subMtl = subMtl->next; @@ -110,18 +105,15 @@ static aseSubMaterial_t* _ase_get_submaterial ( aseMaterial_t* list, int mtlIdP return subMtl; } -aseSubMaterial_t* _ase_get_submaterial_or_default ( aseMaterial_t* materials, int mtlIdParent , int subMtlId ) -{ +aseSubMaterial_t* _ase_get_submaterial_or_default( aseMaterial_t* materials, int mtlIdParent, int subMtlId ){ aseSubMaterial_t* subMtl = _ase_get_submaterial( materials, mtlIdParent, subMtlId ); - if(subMtl != NULL) - { + if ( subMtl != NULL ) { return subMtl; } /* ydnar: trying default submaterial */ subMtl = _ase_get_submaterial( materials, mtlIdParent, 0 ); - if( subMtl != NULL ) - { + if ( subMtl != NULL ) { return subMtl; } @@ -132,8 +124,7 @@ aseSubMaterial_t* _ase_get_submaterial_or_default ( aseMaterial_t* materials, in -static aseMaterial_t* _ase_add_material( aseMaterial_t **list, int mtlIdParent ) -{ +static aseMaterial_t* _ase_add_material( aseMaterial_t **list, int mtlIdParent ){ aseMaterial_t *mtl = _pico_calloc( 1, sizeof( aseMaterial_t ) ); mtl->mtlId = mtlIdParent; mtl->subMtls = NULL; @@ -143,14 +134,12 @@ static aseMaterial_t* _ase_add_material( aseMaterial_t **list, int mtlIdParent ) return mtl; } -static aseSubMaterial_t* _ase_add_submaterial( aseMaterial_t **list, int mtlIdParent, int subMtlId, picoShader_t* shader ) -{ +static aseSubMaterial_t* _ase_add_submaterial( aseMaterial_t **list, int mtlIdParent, int subMtlId, picoShader_t* shader ){ aseMaterial_t *parent = _ase_get_material( *list, mtlIdParent ); - aseSubMaterial_t *subMtl = _pico_calloc( 1, sizeof ( aseSubMaterial_t ) ); + aseSubMaterial_t *subMtl = _pico_calloc( 1, sizeof( aseSubMaterial_t ) ); - if ( !parent ) - { - parent = _ase_add_material ( list , mtlIdParent ); + if ( !parent ) { + parent = _ase_add_material( list, mtlIdParent ); } subMtl->shader = shader; @@ -161,8 +150,7 @@ static aseSubMaterial_t* _ase_add_submaterial( aseMaterial_t **list, int mtlIdPa return subMtl; } -static void _ase_free_materials( aseMaterial_t **list ) -{ +static void _ase_free_materials( aseMaterial_t **list ){ aseMaterial_t* mtl = *list; aseSubMaterial_t* subMtl = NULL; @@ -175,29 +163,28 @@ static void _ase_free_materials( aseMaterial_t **list ) while ( subMtl ) { subMtlTemp = subMtl->next; - _pico_free ( subMtl ); + _pico_free( subMtl ); subMtl = subMtlTemp; } mtlTemp = mtl->next; - _pico_free ( mtl ); + _pico_free( mtl ); mtl = mtlTemp; } - (*list) = NULL; + ( *list ) = NULL; } #ifdef DEBUG_PM_ASE -static void _ase_print_materials( aseMaterial_t *list ) -{ +static void _ase_print_materials( aseMaterial_t *list ){ aseMaterial_t* mtl = list; aseSubMaterial_t* subMtl = NULL; while ( mtl ) { - _pico_printf ( PICO_NORMAL , "ASE Material %i" , mtl->mtlId ); + _pico_printf( PICO_NORMAL, "ASE Material %i", mtl->mtlId ); subMtl = mtl->subMtls; while ( subMtl ) { - _pico_printf ( PICO_NORMAL , " -- ASE SubMaterial %i - %s\n" , subMtl->subMtlId , subMtl->shader->name ); + _pico_printf( PICO_NORMAL, " -- ASE SubMaterial %i - %s\n", subMtl->subMtlId, subMtl->shader->name ); subMtl = subMtl->next; } mtl = mtl->next; @@ -212,36 +199,35 @@ static void _ase_print_materials( aseMaterial_t *list ) /* _ase_canload: * validates a 3dsmax ase model file. */ -static int _ase_canload( PM_PARAMS_CANLOAD ) -{ +static int _ase_canload( PM_PARAMS_CANLOAD ){ picoParser_t *p; - - + + /* quick data length validation */ - if( bufSize < 80 ) + if ( bufSize < 80 ) { return PICO_PMV_ERROR_SIZE; - + } + /* create pico parser */ p = _pico_new_parser( (const picoByte_t*) buffer, bufSize ); - if( p == NULL ) + if ( p == NULL ) { return PICO_PMV_ERROR_MEMORY; - + } + /* get first token */ - if( _pico_parse_first( p ) == NULL) - { + if ( _pico_parse_first( p ) == NULL ) { return PICO_PMV_ERROR_IDENT; } - + /* check first token */ - if( _pico_stricmp( p->token, "*3dsmax_asciiexport" ) ) - { + if ( _pico_stricmp( p->token, "*3dsmax_asciiexport" ) ) { _pico_free_parser( p ); return PICO_PMV_ERROR_IDENT; } - + /* free the pico parser object */ _pico_free_parser( p ); - + /* file seems to be a valid ase file */ return PICO_PMV_OK; } @@ -276,15 +262,13 @@ struct aseFace_s }; typedef aseFace_t* aseFacesIter_t; -picoSurface_t* PicoModelFindOrAddSurface( picoModel_t *model, picoShader_t* shader ) -{ +picoSurface_t* PicoModelFindOrAddSurface( picoModel_t *model, picoShader_t* shader ){ /* see if a surface already has the shader */ int i = 0; for ( ; i < model->numSurfaces ; i++ ) { picoSurface_t* workSurface = model->surface[i]; - if ( workSurface->shader == shader ) - { + if ( workSurface->shader == shader ) { return workSurface; } } @@ -293,10 +277,9 @@ picoSurface_t* PicoModelFindOrAddSurface( picoModel_t *model, picoShader_t* shad { /* create a new surface in the model for the unique shader */ - picoSurface_t* workSurface = PicoNewSurface(model); - if ( !workSurface ) - { - _pico_printf ( PICO_ERROR , "Could not allocate a new surface!\n" ); + picoSurface_t* workSurface = PicoNewSurface( model ); + if ( !workSurface ) { + _pico_printf( PICO_ERROR, "Could not allocate a new surface!\n" ); return 0; } @@ -310,14 +293,14 @@ picoSurface_t* PicoModelFindOrAddSurface( picoModel_t *model, picoShader_t* shad } /* _ase_submit_triangles - jhefty - use the surface and the current face list to look up material/submaterial IDs - and submit them to the model for proper processing + use the surface and the current face list to look up material/submaterial IDs + and submit them to the model for proper processing -The following still holds from ydnar's _ase_make_surface: - indexes 0 1 2 = vert indexes - indexes 3 4 5 = st indexes - indexes 6 7 8 = color indexes (new) -*/ + The following still holds from ydnar's _ase_make_surface: + indexes 0 1 2 = vert indexes + indexes 3 4 5 = st indexes + indexes 6 7 8 = color indexes (new) + */ #if 0 typedef picoIndex_t* picoIndexIter_t; @@ -331,136 +314,120 @@ struct aseUniqueIndices_s aseFace_t* faces; }; -size_t aseUniqueIndices_size(aseUniqueIndices_t* self) -{ +size_t aseUniqueIndices_size( aseUniqueIndices_t* self ){ return self->last - self->data; } -void aseUniqueIndices_reserve(aseUniqueIndices_t* self, picoIndex_t size) -{ - self->data = self->last = (picoIndex_t*)_pico_calloc(size, sizeof(picoIndex_t)); +void aseUniqueIndices_reserve( aseUniqueIndices_t* self, picoIndex_t size ){ + self->data = self->last = (picoIndex_t*)_pico_calloc( size, sizeof( picoIndex_t ) ); } -void aseUniqueIndices_clear(aseUniqueIndices_t* self) -{ - _pico_free(self->data); +void aseUniqueIndices_clear( aseUniqueIndices_t* self ){ + _pico_free( self->data ); } -void aseUniqueIndices_pushBack(aseUniqueIndices_t* self, picoIndex_t index) -{ +void aseUniqueIndices_pushBack( aseUniqueIndices_t* self, picoIndex_t index ){ *self->last++ = index; } -picoIndex_t aseFaces_getVertexIndex(aseFace_t* faces, picoIndex_t index) -{ +picoIndex_t aseFaces_getVertexIndex( aseFace_t* faces, picoIndex_t index ){ return faces[index / 3].indices[index % 3]; } -picoIndex_t aseFaces_getTexCoordIndex(aseFace_t* faces, picoIndex_t index) -{ - return faces[index / 3].indices[(index % 3) + 3]; +picoIndex_t aseFaces_getTexCoordIndex( aseFace_t* faces, picoIndex_t index ){ + return faces[index / 3].indices[( index % 3 ) + 3]; } -picoIndex_t aseFaces_getColorIndex(aseFace_t* faces, picoIndex_t index) -{ - return faces[index / 3].indices[(index % 3) + 6]; +picoIndex_t aseFaces_getColorIndex( aseFace_t* faces, picoIndex_t index ){ + return faces[index / 3].indices[( index % 3 ) + 6]; } -int aseUniqueIndex_equal(aseFace_t* faces, picoIndex_t index, picoIndex_t other) -{ - return aseFaces_getVertexIndex(faces, index) == aseFaces_getVertexIndex(faces, other) - && aseFaces_getTexCoordIndex(faces, index) == aseFaces_getTexCoordIndex(faces, other) - && aseFaces_getColorIndex(faces, index) == aseFaces_getColorIndex(faces, other); +int aseUniqueIndex_equal( aseFace_t* faces, picoIndex_t index, picoIndex_t other ){ + return aseFaces_getVertexIndex( faces, index ) == aseFaces_getVertexIndex( faces, other ) + && aseFaces_getTexCoordIndex( faces, index ) == aseFaces_getTexCoordIndex( faces, other ) + && aseFaces_getColorIndex( faces, index ) == aseFaces_getColorIndex( faces, other ); } -picoIndex_t aseUniqueIndices_insertUniqueVertex(aseUniqueIndices_t* self, picoIndex_t index) -{ +picoIndex_t aseUniqueIndices_insertUniqueVertex( aseUniqueIndices_t* self, picoIndex_t index ){ picoIndexIter_t i = self->data; - for(; i != self->last; ++i) + for (; i != self->last; ++i ) { - picoIndex_t other = (picoIndex_t)(i - self->data); - if(aseUniqueIndex_equal(self->faces, index, other)) - { + picoIndex_t other = (picoIndex_t)( i - self->data ); + if ( aseUniqueIndex_equal( self->faces, index, other ) ) { return other; } } - aseUniqueIndices_pushBack(self, index); - return (picoIndex_t)(aseUniqueIndices_size(self) - 1); + aseUniqueIndices_pushBack( self, index ); + return (picoIndex_t)( aseUniqueIndices_size( self ) - 1 ); } -static void _ase_submit_triangles_unshared ( picoModel_t* model , aseMaterial_t* materials , aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces, int meshHasNormals ) -{ +static void _ase_submit_triangles_unshared( picoModel_t* model, aseMaterial_t* materials, aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces, int meshHasNormals ){ aseFacesIter_t i = faces, end = faces + numFaces; aseUniqueIndices_t indices; aseUniqueIndices_t remap; - aseUniqueIndices_reserve(&indices, numFaces * 3); - aseUniqueIndices_reserve(&remap, numFaces * 3); + aseUniqueIndices_reserve( &indices, numFaces * 3 ); + aseUniqueIndices_reserve( &remap, numFaces * 3 ); indices.faces = faces; - for(; i != end; ++i) + for (; i != end; ++i ) { /* look up the shader for the material/submaterial pair */ - aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, (*i).materialId, (*i).subMaterialId ); - if( subMtl == NULL ) - { + aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, ( *i ).materialId, ( *i ).subMaterialId ); + if ( subMtl == NULL ) { return; } { - picoSurface_t* surface = PicoModelFindOrAddSurface(model, subMtl->shader); + picoSurface_t* surface = PicoModelFindOrAddSurface( model, subMtl->shader ); int j; /* we pull the data from the vertex, color and texcoord arrays using the face index data */ - for ( j = 0 ; j < 3 ; j ++ ) + for ( j = 0 ; j < 3 ; j++ ) { - picoIndex_t index = (picoIndex_t)(((i - faces) * 3) + j); - picoIndex_t size = (picoIndex_t)aseUniqueIndices_size(&indices); - picoIndex_t unique = aseUniqueIndices_insertUniqueVertex(&indices, index); + picoIndex_t index = (picoIndex_t)( ( ( i - faces ) * 3 ) + j ); + picoIndex_t size = (picoIndex_t)aseUniqueIndices_size( &indices ); + picoIndex_t unique = aseUniqueIndices_insertUniqueVertex( &indices, index ); - picoIndex_t numVertexes = PicoGetSurfaceNumVertexes(surface); - picoIndex_t numIndexes = PicoGetSurfaceNumIndexes(surface); + picoIndex_t numVertexes = PicoGetSurfaceNumVertexes( surface ); + picoIndex_t numIndexes = PicoGetSurfaceNumIndexes( surface ); - aseUniqueIndices_pushBack(&remap, numIndexes); + aseUniqueIndices_pushBack( &remap, numIndexes ); - PicoSetSurfaceIndex(surface, numIndexes, remap.data[unique]); + PicoSetSurfaceIndex( surface, numIndexes, remap.data[unique] ); - if(unique == size) - { - PicoSetSurfaceXYZ(surface, numVertexes, vertices[(*i).indices[j]].xyz); - PicoSetSurfaceNormal(surface, numVertexes, vertices[(*i).indices[j]].normal); - PicoSetSurfaceST(surface, 0, numVertexes, texcoords[(*i).indices[j + 3]].texcoord); + if ( unique == size ) { + PicoSetSurfaceXYZ( surface, numVertexes, vertices[( *i ).indices[j]].xyz ); + PicoSetSurfaceNormal( surface, numVertexes, vertices[( *i ).indices[j]].normal ); + PicoSetSurfaceST( surface, 0, numVertexes, texcoords[( *i ).indices[j + 3]].texcoord ); - if ( (*i).indices[j + 6] >= 0 ) - { - PicoSetSurfaceColor(surface, 0, numVertexes, colors[(*i).indices[j + 6]].color); + if ( ( *i ).indices[j + 6] >= 0 ) { + PicoSetSurfaceColor( surface, 0, numVertexes, colors[( *i ).indices[j + 6]].color ); } else { - PicoSetSurfaceColor(surface, 0, numVertexes, white); + PicoSetSurfaceColor( surface, 0, numVertexes, white ); } - PicoSetSurfaceSmoothingGroup(surface, numVertexes, (vertices[(*i).indices[j]].id * (1 << 16)) + (*i).smoothingGroup); + PicoSetSurfaceSmoothingGroup( surface, numVertexes, ( vertices[( *i ).indices[j]].id * ( 1 << 16 ) ) + ( *i ).smoothingGroup ); } } } } - aseUniqueIndices_clear(&indices); - aseUniqueIndices_clear(&remap); + aseUniqueIndices_clear( &indices ); + aseUniqueIndices_clear( &remap ); } #endif -static void _ase_submit_triangles( picoModel_t* model , aseMaterial_t* materials , aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces, const char *name ) -{ +static void _ase_submit_triangles( picoModel_t* model, aseMaterial_t* materials, aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces, const char *name ){ aseFacesIter_t i = faces, end = faces + numFaces; - for(; i != end; ++i) + for (; i != end; ++i ) { /* look up the shader for the material/submaterial pair */ - aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, (*i).materialId, (*i).subMaterialId ); - if( subMtl == NULL ) - { + aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, ( *i ).materialId, ( *i ).subMaterialId ); + if ( subMtl == NULL ) { return; } @@ -472,53 +439,49 @@ static void _ase_submit_triangles( picoModel_t* model , aseMaterial_t* materials picoIndex_t smooth[3]; int j; /* we pull the data from the vertex, color and texcoord arrays using the face index data */ - for ( j = 0 ; j < 3 ; j ++ ) + for ( j = 0 ; j < 3 ; j++ ) { - xyz[j] = &vertices[(*i).indices[j]].xyz; - normal[j] = &vertices[(*i).indices[j]].normal; - st[j] = &texcoords[(*i).indices[j + 3]].texcoord; - - if( colors != NULL && (*i).indices[j + 6] >= 0 ) - { - color[j] = &colors[(*i).indices[j + 6]].color; + xyz[j] = &vertices[( *i ).indices[j]].xyz; + normal[j] = &vertices[( *i ).indices[j]].normal; + st[j] = &texcoords[( *i ).indices[j + 3]].texcoord; + + if ( colors != NULL && ( *i ).indices[j + 6] >= 0 ) { + color[j] = &colors[( *i ).indices[j + 6]].color; } else { color[j] = &white; } - smooth[j] = (vertices[(*i).indices[j]].id * (1 << 16)) + (*i).smoothingGroup; /* don't merge vertices */ - + smooth[j] = ( vertices[( *i ).indices[j]].id * ( 1 << 16 ) ) + ( *i ).smoothingGroup; /* don't merge vertices */ + } /* submit the triangle to the model */ - PicoAddTriangleToModel ( model , xyz , normal , 1 , st , 1 , color , subMtl->shader, name, smooth ); + PicoAddTriangleToModel( model, xyz, normal, 1, st, 1, color, subMtl->shader, name, smooth ); } } } -static void shadername_convert(char* shaderName) -{ - /* unix-style path separators */ - char* s = shaderName; - for(; *s != '\0'; ++s) - { - if(*s == '\\') - { - *s = '/'; - } - } +static void shadername_convert( char* shaderName ){ + /* unix-style path separators */ + char* s = shaderName; + for (; *s != '\0'; ++s ) + { + if ( *s == '\\' ) { + *s = '/'; + } + } } /* _ase_load: * loads a 3dsmax ase model file. -*/ -static picoModel_t *_ase_load( PM_PARAMS_LOAD ) -{ + */ +static picoModel_t *_ase_load( PM_PARAMS_LOAD ){ picoModel_t *model; picoParser_t *p; - char lastNodeName[ 1024 ]; + char lastNodeName[ 1024 ]; aseVertex_t* vertices = NULL; aseTexCoord_t* texcoords = NULL; @@ -541,21 +504,22 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) #endif /* helper */ - #define _ase_error_return(m) \ + #define _ase_error_return( m ) \ { \ - _pico_printf( PICO_ERROR,"%s in ASE, line %d.",m,p->curLine); \ - _pico_free_parser( p ); \ - PicoFreeModel( model ); \ + _pico_printf( PICO_ERROR,"%s in ASE, line %d.",m,p->curLine ); \ + _pico_free_parser( p ); \ + PicoFreeModel( model ); \ return NULL; \ } /* create a new pico parser */ p = _pico_new_parser( (const picoByte_t *)buffer,bufSize ); - if (p == NULL) return NULL; + if ( p == NULL ) { + return NULL; + } /* create a new pico model */ model = PicoNewModel(); - if (model == NULL) - { + if ( model == NULL ) { _pico_free_parser( p ); return NULL; } @@ -565,340 +529,369 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) PicoSetModelFileName( model, fileName ); /* initialize some stuff */ - memset( lastNodeName,0,sizeof(lastNodeName) ); + memset( lastNodeName,0,sizeof( lastNodeName ) ); /* parse ase model file */ - while( 1 ) + while ( 1 ) { /* get first token on line */ - if (_pico_parse_first( p ) == NULL) + if ( _pico_parse_first( p ) == NULL ) { break; + } /* we just skip empty lines */ - if (p->token == NULL || !strlen( p->token )) + if ( p->token == NULL || !strlen( p->token ) ) { continue; + } /* we skip invalid ase statements */ - if (p->token[0] != '*' && p->token[0] != '{' && p->token[0] != '}') - { + if ( p->token[0] != '*' && p->token[0] != '{' && p->token[0] != '}' ) { _pico_parse_skip_rest( p ); continue; } /* remember node name */ - if (!_pico_stricmp(p->token,"*node_name")) - { + if ( !_pico_stricmp( p->token,"*node_name" ) ) { /* read node name */ char *ptr = _pico_parse( p,0 ); - if (ptr == NULL) - _ase_error_return("Node name parse error"); + if ( ptr == NULL ) { + _ase_error_return( "Node name parse error" ); + } /* remember node name */ - strncpy( lastNodeName,ptr,sizeof(lastNodeName) ); + strncpy( lastNodeName,ptr,sizeof( lastNodeName ) ); } /* model mesh (originally contained within geomobject) */ - else if (!_pico_stricmp(p->token,"*mesh")) - { + else if ( !_pico_stricmp( p->token,"*mesh" ) ) { /* finish existing surface */ - _ase_submit_triangles(model, materials, vertices, texcoords, colors, faces, numFaces, lastNodeName); - _pico_free(faces); - _pico_free(vertices); - _pico_free(texcoords); - _pico_free(colors); + _ase_submit_triangles( model, materials, vertices, texcoords, colors, faces, numFaces, lastNodeName ); + _pico_free( faces ); + _pico_free( vertices ); + _pico_free( texcoords ); + _pico_free( colors ); } - else if (!_pico_stricmp(p->token,"*mesh_numvertex")) - { - if (!_pico_parse_int( p, &numVertices) ) - _ase_error_return("Missing MESH_NUMVERTEX value"); + else if ( !_pico_stricmp( p->token,"*mesh_numvertex" ) ) { + if ( !_pico_parse_int( p, &numVertices ) ) { + _ase_error_return( "Missing MESH_NUMVERTEX value" ); + } - vertices = _pico_calloc(numVertices, sizeof(aseVertex_t)); + vertices = _pico_calloc( numVertices, sizeof( aseVertex_t ) ); } - else if (!_pico_stricmp(p->token,"*mesh_numfaces")) - { - if (!_pico_parse_int( p, &numFaces) ) - _ase_error_return("Missing MESH_NUMFACES value"); + else if ( !_pico_stricmp( p->token,"*mesh_numfaces" ) ) { + if ( !_pico_parse_int( p, &numFaces ) ) { + _ase_error_return( "Missing MESH_NUMFACES value" ); + } - faces = _pico_calloc(numFaces, sizeof(aseFace_t)); + faces = _pico_calloc( numFaces, sizeof( aseFace_t ) ); } - else if (!_pico_stricmp(p->token,"*mesh_numtvertex")) - { - if (!_pico_parse_int( p, &numTextureVertices) ) - _ase_error_return("Missing MESH_NUMTVERTEX value"); + else if ( !_pico_stricmp( p->token,"*mesh_numtvertex" ) ) { + if ( !_pico_parse_int( p, &numTextureVertices ) ) { + _ase_error_return( "Missing MESH_NUMTVERTEX value" ); + } - texcoords = _pico_calloc(numTextureVertices, sizeof(aseTexCoord_t)); + texcoords = _pico_calloc( numTextureVertices, sizeof( aseTexCoord_t ) ); } - else if (!_pico_stricmp(p->token,"*mesh_numtvfaces")) - { - if (!_pico_parse_int( p, &numTextureVertexFaces) ) - _ase_error_return("Missing MESH_NUMTVFACES value"); + else if ( !_pico_stricmp( p->token,"*mesh_numtvfaces" ) ) { + if ( !_pico_parse_int( p, &numTextureVertexFaces ) ) { + _ase_error_return( "Missing MESH_NUMTVFACES value" ); + } } - else if (!_pico_stricmp(p->token,"*mesh_numcvertex")) - { - if (!_pico_parse_int( p, &numColorVertices) ) - _ase_error_return("Missing MESH_NUMCVERTEX value"); + else if ( !_pico_stricmp( p->token,"*mesh_numcvertex" ) ) { + if ( !_pico_parse_int( p, &numColorVertices ) ) { + _ase_error_return( "Missing MESH_NUMCVERTEX value" ); + } - colors = _pico_calloc(numColorVertices, sizeof(aseColor_t)); - memset( colors, 255, numColorVertices * sizeof( aseColor_t ) ); /* ydnar: force colors to white initially */ + colors = _pico_calloc( numColorVertices, sizeof( aseColor_t ) ); + memset( colors, 255, numColorVertices * sizeof( aseColor_t ) ); /* ydnar: force colors to white initially */ } - else if (!_pico_stricmp(p->token,"*mesh_numcvfaces")) - { - if (!_pico_parse_int( p, &numColorVertexFaces) ) - _ase_error_return("Missing MESH_NUMCVFACES value"); + else if ( !_pico_stricmp( p->token,"*mesh_numcvfaces" ) ) { + if ( !_pico_parse_int( p, &numColorVertexFaces ) ) { + _ase_error_return( "Missing MESH_NUMCVFACES value" ); + } } /* mesh material reference. this usually comes at the end of */ /* geomobjects after the mesh blocks. we must assume that the */ /* new mesh was already created so all we can do here is assign */ /* the material reference id (shader index) now. */ - else if (!_pico_stricmp(p->token,"*material_ref")) - { + else if ( !_pico_stricmp( p->token,"*material_ref" ) ) { int mtlId; /* get the material ref (0..n) */ - if (!_pico_parse_int( p,&mtlId) ) - _ase_error_return("Missing material reference ID"); + if ( !_pico_parse_int( p,&mtlId ) ) { + _ase_error_return( "Missing material reference ID" ); + } { int i = 0; /* fix up all of the aseFaceList in the surface to point to the parent material */ /* we've already saved off their subMtl */ - for(; i < numFaces; ++i) + for (; i < numFaces; ++i ) { faces[i].materialId = mtlId; } } } /* model mesh vertex */ - else if (!_pico_stricmp(p->token,"*mesh_vertex")) - { - int index; + else if ( !_pico_stricmp( p->token,"*mesh_vertex" ) ) { + int index; - if( numVertices == 0 ) - _ase_error_return("Vertex parse error"); + if ( numVertices == 0 ) { + _ase_error_return( "Vertex parse error" ); + } /* get vertex data (orig: index +y -x +z) */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Vertex parse error"); - if (!_pico_parse_vec( p,vertices[index].xyz )) - _ase_error_return("Vertex parse error"); + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Vertex parse error" ); + } + if ( !_pico_parse_vec( p,vertices[index].xyz ) ) { + _ase_error_return( "Vertex parse error" ); + } vertices[index].id = vertexId++; } /* model mesh vertex normal */ - else if (!_pico_stricmp(p->token,"*mesh_vertexnormal")) - { - int index; + else if ( !_pico_stricmp( p->token,"*mesh_vertexnormal" ) ) { + int index; - if( numVertices == 0 ) - _ase_error_return("Vertex parse error"); + if ( numVertices == 0 ) { + _ase_error_return( "Vertex parse error" ); + } /* get vertex data (orig: index +y -x +z) */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Vertex parse error"); - if (!_pico_parse_vec( p,vertices[index].normal )) - _ase_error_return("Vertex parse error"); + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Vertex parse error" ); + } + if ( !_pico_parse_vec( p,vertices[index].normal ) ) { + _ase_error_return( "Vertex parse error" ); + } } /* model mesh face */ - else if (!_pico_stricmp(p->token,"*mesh_face")) - { + else if ( !_pico_stricmp( p->token,"*mesh_face" ) ) { picoIndex_t indexes[3]; int index; - - if( numFaces == 0 ) - _ase_error_return("Face parse error"); + + if ( numFaces == 0 ) { + _ase_error_return( "Face parse error" ); + } /* get face index */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Face parse error" ); + } /* get 1st vertex index */ _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[0] )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&indexes[0] ) ) { + _ase_error_return( "Face parse error" ); + } /* get 2nd vertex index */ _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[1] )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&indexes[1] ) ) { + _ase_error_return( "Face parse error" ); + } /* get 3rd vertex index */ _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[2] )) - _ase_error_return("Face parse error"); - + if ( !_pico_parse_int( p,&indexes[2] ) ) { + _ase_error_return( "Face parse error" ); + } + /* parse to the subMaterial ID */ while ( 1 ) { - if (!_pico_parse (p,0)) /* EOL */ - { + if ( !_pico_parse( p,0 ) ) { /* EOL */ break; } - if (!_pico_stricmp (p->token,"*MESH_SMOOTHING" )) - { - _pico_parse_int ( p , &faces[index].smoothingGroup ); + if ( !_pico_stricmp( p->token,"*MESH_SMOOTHING" ) ) { + _pico_parse_int( p, &faces[index].smoothingGroup ); } - if (!_pico_stricmp (p->token,"*MESH_MTLID" )) - { - _pico_parse_int ( p , &faces[index].subMaterialId ); + if ( !_pico_stricmp( p->token,"*MESH_MTLID" ) ) { + _pico_parse_int( p, &faces[index].subMaterialId ); } } - + faces[index].materialId = 0; faces[index].indices[0] = indexes[2]; faces[index].indices[1] = indexes[1]; faces[index].indices[2] = indexes[0]; } /* model texture vertex */ - else if (!_pico_stricmp(p->token,"*mesh_tvert")) - { - int index; + else if ( !_pico_stricmp( p->token,"*mesh_tvert" ) ) { + int index; - if( numVertices == 0 ) - _ase_error_return("Texture Vertex parse error"); + if ( numVertices == 0 ) { + _ase_error_return( "Texture Vertex parse error" ); + } /* get uv vertex index */ - if (!_pico_parse_int( p,&index ) || index >= numTextureVertices) - _ase_error_return("Texture vertex parse error"); + if ( !_pico_parse_int( p,&index ) || index >= numTextureVertices ) { + _ase_error_return( "Texture vertex parse error" ); + } /* get uv vertex s */ - if (!_pico_parse_float( p,&texcoords[index].texcoord[0] )) - _ase_error_return("Texture vertex parse error"); + if ( !_pico_parse_float( p,&texcoords[index].texcoord[0] ) ) { + _ase_error_return( "Texture vertex parse error" ); + } /* get uv vertex t */ - if (!_pico_parse_float( p,&texcoords[index].texcoord[1] )) - _ase_error_return("Texture vertex parse error"); - + if ( !_pico_parse_float( p,&texcoords[index].texcoord[1] ) ) { + _ase_error_return( "Texture vertex parse error" ); + } + /* ydnar: invert t */ texcoords[index].texcoord[ 1 ] = 1.0f - texcoords[index].texcoord[ 1 ]; } /* ydnar: model mesh texture face */ - else if( !_pico_stricmp( p->token, "*mesh_tface" ) ) - { + else if ( !_pico_stricmp( p->token, "*mesh_tface" ) ) { picoIndex_t indexes[3]; - int index; - - if( numFaces == 0 ) - _ase_error_return("Texture face parse error"); - + int index; + + if ( numFaces == 0 ) { + _ase_error_return( "Texture face parse error" ); + } + /* get face index */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Texture face parse error"); - + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Texture face parse error" ); + } + /* get 1st vertex index */ - if (!_pico_parse_int( p,&indexes[0] )) - _ase_error_return("Texture face parse error"); - + if ( !_pico_parse_int( p,&indexes[0] ) ) { + _ase_error_return( "Texture face parse error" ); + } + /* get 2nd vertex index */ - if (!_pico_parse_int( p,&indexes[1] )) - _ase_error_return("Texture face parse error"); - + if ( !_pico_parse_int( p,&indexes[1] ) ) { + _ase_error_return( "Texture face parse error" ); + } + /* get 3rd vertex index */ - if (!_pico_parse_int( p,&indexes[2] )) - _ase_error_return("Texture face parse error"); + if ( !_pico_parse_int( p,&indexes[2] ) ) { + _ase_error_return( "Texture face parse error" ); + } faces[index].indices[3] = indexes[2]; faces[index].indices[4] = indexes[1]; faces[index].indices[5] = indexes[0]; } /* model color vertex */ - else if (!_pico_stricmp(p->token,"*mesh_vertcol")) - { - int index; - float colorInput; + else if ( !_pico_stricmp( p->token,"*mesh_vertcol" ) ) { + int index; + float colorInput; - if( numVertices == 0 ) - _ase_error_return("Color Vertex parse error"); + if ( numVertices == 0 ) { + _ase_error_return( "Color Vertex parse error" ); + } /* get color vertex index */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Color vertex parse error"); + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Color vertex parse error" ); + } /* get R component */ - if (!_pico_parse_float( p,&colorInput )) - _ase_error_return("Color vertex parse error"); - colors[index].color[0] = (picoByte_t)(colorInput * 255); + if ( !_pico_parse_float( p,&colorInput ) ) { + _ase_error_return( "Color vertex parse error" ); + } + colors[index].color[0] = (picoByte_t)( colorInput * 255 ); /* get G component */ - if (!_pico_parse_float( p,&colorInput )) - _ase_error_return("Color vertex parse error"); - colors[index].color[1] = (picoByte_t)(colorInput * 255); + if ( !_pico_parse_float( p,&colorInput ) ) { + _ase_error_return( "Color vertex parse error" ); + } + colors[index].color[1] = (picoByte_t)( colorInput * 255 ); /* get B component */ - if (!_pico_parse_float( p,&colorInput )) - _ase_error_return("Color vertex parse error"); - colors[index].color[2] = (picoByte_t)(colorInput * 255); - + if ( !_pico_parse_float( p,&colorInput ) ) { + _ase_error_return( "Color vertex parse error" ); + } + colors[index].color[2] = (picoByte_t)( colorInput * 255 ); + /* leave alpha alone since we don't get any data from the ASE format */ colors[index].color[3] = 255; } /* model color face */ - else if (!_pico_stricmp(p->token,"*mesh_cface")) - { + else if ( !_pico_stricmp( p->token,"*mesh_cface" ) ) { picoIndex_t indexes[3]; - int index; + int index; - if( numFaces == 0 ) - _ase_error_return("Face parse error"); + if ( numFaces == 0 ) { + _ase_error_return( "Face parse error" ); + } /* get face index */ - if (!_pico_parse_int( p,&index )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&index ) ) { + _ase_error_return( "Face parse error" ); + } /* get 1st cvertex index */ // _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[0] )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&indexes[0] ) ) { + _ase_error_return( "Face parse error" ); + } /* get 2nd cvertex index */ // _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[1] )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&indexes[1] ) ) { + _ase_error_return( "Face parse error" ); + } /* get 3rd cvertex index */ // _pico_parse( p,0 ); - if (!_pico_parse_int( p,&indexes[2] )) - _ase_error_return("Face parse error"); + if ( !_pico_parse_int( p,&indexes[2] ) ) { + _ase_error_return( "Face parse error" ); + } faces[index].indices[6] = indexes[2]; faces[index].indices[7] = indexes[1]; faces[index].indices[8] = indexes[0]; } /* model material */ - else if( !_pico_stricmp( p->token, "*material" ) ) - { - aseSubMaterial_t* subMaterial = NULL; - picoShader_t *shader = NULL; - int level = 1, index; - char materialName[ 1024 ]; - float transValue = 0.0f, shineValue = 1.0f; - picoColor_t ambientColor, diffuseColor, specularColor; - char *mapname = NULL; - int subMtlId, subMaterialLevel = -1; - - + else if ( !_pico_stricmp( p->token, "*material" ) ) { + aseSubMaterial_t* subMaterial = NULL; + picoShader_t *shader = NULL; + int level = 1, index; + char materialName[ 1024 ]; + float transValue = 0.0f, shineValue = 1.0f; + picoColor_t ambientColor, diffuseColor, specularColor; + char *mapname = NULL; + int subMtlId, subMaterialLevel = -1; + + /* get material index */ _pico_parse_int( p,&index ); - + /* check brace */ - if (!_pico_parse_check(p,1,"{")) - _ase_error_return("Material missing opening brace"); - + if ( !_pico_parse_check( p,1,"{" ) ) { + _ase_error_return( "Material missing opening brace" ); + } + /* parse material block */ - while( 1 ) + while ( 1 ) { /* get next token */ - if (_pico_parse(p,1) == NULL) break; - if (!strlen(p->token)) continue; + if ( _pico_parse( p,1 ) == NULL ) { + break; + } + if ( !strlen( p->token ) ) { + continue; + } /* handle levels */ - if (p->token[0] == '{') level++; - if (p->token[0] == '}') level--; - if (!level) break; + if ( p->token[0] == '{' ) { + level++; + } + if ( p->token[0] == '}' ) { + level--; + } + if ( !level ) { + break; + } - if( level == subMaterialLevel ) - { + if ( level == subMaterialLevel ) { /* set material name */ _pico_first_token( materialName ); - shadername_convert(materialName); - PicoSetShaderName( shader, materialName); + shadername_convert( materialName ); + PicoSetShaderName( shader, materialName ); /* set shader's transparency */ PicoSetShaderTransparency( shader,transValue ); @@ -926,52 +919,50 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) } /* parse submaterial index */ - if (!_pico_stricmp(p->token,"*submaterial")) - { + if ( !_pico_stricmp( p->token,"*submaterial" ) ) { /* allocate new pico shader */ - _pico_parse_int( p , &subMtlId ); + _pico_parse_int( p, &subMtlId ); shader = PicoNewShader( model ); - if (shader == NULL) - { + if ( shader == NULL ) { PicoFreeModel( model ); return NULL; - } + } subMaterialLevel = level; } /* parse material name */ - else if (!_pico_stricmp(p->token,"*material_name")) - { - char* name = _pico_parse(p,0); - if ( name == NULL) - _ase_error_return("Missing material name"); - - strcpy ( materialName , name ); + else if ( !_pico_stricmp( p->token,"*material_name" ) ) { + char* name = _pico_parse( p,0 ); + if ( name == NULL ) { + _ase_error_return( "Missing material name" ); + } + + strcpy( materialName, name ); /* skip rest and continue with next token */ _pico_parse_skip_rest( p ); continue; } /* parse material transparency */ - else if (!_pico_stricmp(p->token,"*material_transparency")) - { + else if ( !_pico_stricmp( p->token,"*material_transparency" ) ) { /* get transparency value from ase */ - if (!_pico_parse_float( p,&transValue )) - _ase_error_return("Material transparency parse error"); + if ( !_pico_parse_float( p,&transValue ) ) { + _ase_error_return( "Material transparency parse error" ); + } /* skip rest and continue with next token */ _pico_parse_skip_rest( p ); continue; } /* parse material shininess */ - else if (!_pico_stricmp(p->token,"*material_shine")) - { + else if ( !_pico_stricmp( p->token,"*material_shine" ) ) { /* remark: * - not sure but instead of '*material_shine' i might * need to use '*material_shinestrength' */ /* get shine value from ase */ - if (!_pico_parse_float( p,&shineValue )) - _ase_error_return("Material shine parse error"); + if ( !_pico_parse_float( p,&shineValue ) ) { + _ase_error_return( "Material shine parse error" ); + } /* scale ase shine range 0..1 to pico range 0..127 */ shineValue *= 128.0; @@ -981,12 +972,12 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) continue; } /* parse ambient material color */ - else if (!_pico_stricmp(p->token,"*material_ambient")) - { - picoVec3_t vec; + else if ( !_pico_stricmp( p->token,"*material_ambient" ) ) { + picoVec3_t vec; /* get r,g,b float values from ase */ - if (!_pico_parse_vec( p,vec )) - _ase_error_return("Material color parse error"); + if ( !_pico_parse_vec( p,vec ) ) { + _ase_error_return( "Material color parse error" ); + } /* setup 0..255 range color values */ ambientColor[ 0 ] = (int)( vec[ 0 ] * 255.0 ); @@ -999,13 +990,13 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) continue; } /* parse diffuse material color */ - else if (!_pico_stricmp(p->token,"*material_diffuse")) - { - picoVec3_t vec; + else if ( !_pico_stricmp( p->token,"*material_diffuse" ) ) { + picoVec3_t vec; /* get r,g,b float values from ase */ - if (!_pico_parse_vec( p,vec )) - _ase_error_return("Material color parse error"); + if ( !_pico_parse_vec( p,vec ) ) { + _ase_error_return( "Material color parse error" ); + } /* setup 0..255 range color */ diffuseColor[ 0 ] = (int)( vec[ 0 ] * 255.0 ); @@ -1018,13 +1009,13 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) continue; } /* parse specular material color */ - else if (!_pico_stricmp(p->token,"*material_specular")) - { - picoVec3_t vec; + else if ( !_pico_stricmp( p->token,"*material_specular" ) ) { + picoVec3_t vec; /* get r,g,b float values from ase */ - if (!_pico_parse_vec( p,vec )) - _ase_error_return("Material color parse error"); + if ( !_pico_parse_vec( p,vec ) ) { + _ase_error_return( "Material color parse error" ); + } /* setup 0..255 range color */ specularColor[ 0 ] = (int)( vec[ 0 ] * 255 ); @@ -1037,30 +1028,39 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) continue; } /* material diffuse map */ - else if (!_pico_stricmp(p->token,"*map_diffuse") ) - { + else if ( !_pico_stricmp( p->token,"*map_diffuse" ) ) { int sublevel = 0; /* parse material block */ - while( 1 ) + while ( 1 ) { /* get next token */ - if (_pico_parse(p,1) == NULL) break; - if (!strlen(p->token)) continue; - + if ( _pico_parse( p,1 ) == NULL ) { + break; + } + if ( !strlen( p->token ) ) { + continue; + } + /* handle levels */ - if (p->token[0] == '{') sublevel++; - if (p->token[0] == '}') sublevel--; - if (!sublevel) break; - + if ( p->token[0] == '{' ) { + sublevel++; + } + if ( p->token[0] == '}' ) { + sublevel--; + } + if ( !sublevel ) { + break; + } + /* parse diffuse map bitmap */ - if (!_pico_stricmp(p->token,"*bitmap")) - { - char* name = _pico_parse(p,0); - if (name == NULL) - _ase_error_return("Missing material map bitmap name"); - mapname = _pico_alloc ( strlen ( name ) + 1 ); - strcpy ( mapname, name ); + if ( !_pico_stricmp( p->token,"*bitmap" ) ) { + char* name = _pico_parse( p,0 ); + if ( name == NULL ) { + _ase_error_return( "Missing material map bitmap name" ); + } + mapname = _pico_alloc( strlen( name ) + 1 ); + strcpy( mapname, name ); /* skip rest and continue with next token */ _pico_parse_skip_rest( p ); continue; @@ -1071,18 +1071,16 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) } /* end material block */ - if( subMaterial == NULL ) - { + if ( subMaterial == NULL ) { /* allocate new pico shader */ shader = PicoNewShader( model ); - if (shader == NULL) - { + if ( shader == NULL ) { PicoFreeModel( model ); return NULL; } /* set material name */ - shadername_convert(materialName); + shadername_convert( materialName ); PicoSetShaderName( shader,materialName ); /* set shader's transparency */ @@ -1106,68 +1104,65 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) /* set material map name */ PicoSetShaderMapName( shader, mapname ); - /* extract shadername from bitmap path */ - if(mapname != NULL) - { - char* p = mapname; - - /* convert to shader-name format */ - shadername_convert(mapname); - { - /* remove extension */ - char* last_period = strrchr(p, '.'); - if(last_period != NULL) - { - *last_period = '\0'; - } - } - - /* find shader path */ - for(; *p != '\0'; ++p) - { - if(_pico_strnicmp(p, "models/", 7) == 0 || _pico_strnicmp(p, "textures/", 9) == 0) - { - break; - } - } - - if(*p != '\0') - { - /* set material name */ - PicoSetShaderName( shader,p ); - } - } - - /* this is just a material with 1 submaterial */ + /* extract shadername from bitmap path */ + if ( mapname != NULL ) { + char* p = mapname; + + /* convert to shader-name format */ + shadername_convert( mapname ); + { + /* remove extension */ + char* last_period = strrchr( p, '.' ); + if ( last_period != NULL ) { + *last_period = '\0'; + } + } + + /* find shader path */ + for (; *p != '\0'; ++p ) + { + if ( _pico_strnicmp( p, "models/", 7 ) == 0 || _pico_strnicmp( p, "textures/", 9 ) == 0 ) { + break; + } + } + + if ( *p != '\0' ) { + /* set material name */ + PicoSetShaderName( shader,p ); + } + } + + /* this is just a material with 1 submaterial */ subMaterial = _ase_add_submaterial( &materials, index, 0, shader ); } - + /* ydnar: free mapname */ - if( mapname != NULL ) + if ( mapname != NULL ) { _pico_free( mapname ); - } // !_pico_stricmp ( "*material" ) + } + } // !_pico_stricmp ( "*material" ) /* skip unparsed rest of line and continue */ _pico_parse_skip_rest( p ); } - + /* ydnar: finish existing surface */ - _ase_submit_triangles(model, materials, vertices, texcoords, colors, faces, numFaces, lastNodeName); - _pico_free(faces); - _pico_free(vertices); - _pico_free(texcoords); - _pico_free(colors); + _ase_submit_triangles( model, materials, vertices, texcoords, colors, faces, numFaces, lastNodeName ); + _pico_free( faces ); + _pico_free( vertices ); + _pico_free( texcoords ); + _pico_free( colors ); #ifdef DEBUG_PM_ASE - _ase_print_materials(materials); + _ase_print_materials( materials ); finish = clock(); - elapsed = (double)(finish - start) / CLOCKS_PER_SEC; + elapsed = (double)( finish - start ) / CLOCKS_PER_SEC; _pico_printf( PICO_NORMAL, "Loaded model in in %-.2f second(s)\n", elapsed ); #endif //DEBUG_PM_ASE - _ase_free_materials(&materials); + _ase_free_materials( &materials ); - _pico_free_parser( p ); + _pico_free_parser( p ); /* return allocated pico model */ return model; @@ -1176,15 +1171,15 @@ static picoModel_t *_ase_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleASE = { - "1.0", /* module version string */ - "Autodesk 3DSMAX ASCII", /* module display name */ - "Jared Hefty, seaw0lf", /* author's name */ - "2003 Jared Hefty, 2002 seaw0lf", /* module copyright */ + "1.0", /* module version string */ + "Autodesk 3DSMAX ASCII", /* module display name */ + "Jared Hefty, seaw0lf", /* author's name */ + "2003 Jared Hefty, 2002 seaw0lf", /* module copyright */ { - "ase",NULL,NULL,NULL /* default extensions to use */ + "ase",NULL,NULL,NULL /* default extensions to use */ }, - _ase_canload, /* validation routine */ - _ase_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _ase_canload, /* validation routine */ + _ase_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_fm.c b/libs/picomodel/pm_fm.c index 0fc65813..eefee2e7 100644 --- a/libs/picomodel/pm_fm.c +++ b/libs/picomodel/pm_fm.c @@ -1,40 +1,40 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ /* -Nurail: Used pm_md3.c (Randy Reddig) as a template. -*/ + Nurail: Used pm_md3.c (Randy Reddig) as a template. + */ /* marker */ #define PM_FM_C @@ -48,152 +48,141 @@ Nurail: Used pm_md3.c (Randy Reddig) as a template. typedef struct index_LUT_s { - short Vert; - short ST; - struct index_LUT_s *next; + short Vert; + short ST; + struct index_LUT_s *next; } index_LUT_t; typedef struct index_DUP_LUT_s { - short ST; - short OldVert; + short ST; + short OldVert; } index_DUP_LUT_t; // _fm_canload() -static int _fm_canload( PM_PARAMS_CANLOAD ) -{ - fm_t fm; - unsigned char *bb, *bb0; - int fm_file_pos; +static int _fm_canload( PM_PARAMS_CANLOAD ){ + fm_t fm; + unsigned char *bb, *bb0; + int fm_file_pos; - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); + bb0 = bb = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bb, buffer, bufSize ); // Header fm.fm_header_hdr = (fm_chunk_header_t *) bb; - fm_file_pos = sizeof(fm_chunk_header_t) + fm.fm_header_hdr->size; + fm_file_pos = sizeof( fm_chunk_header_t ) + fm.fm_header_hdr->size; #ifdef FM_VERBOSE_DBG _pico_printf( PICO_VERBOSE, "IDENT: %s\n", (unsigned char *) fm.fm_header_hdr->ident ); #endif - if( (strcmp(fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME)) ) - { + if ( ( strcmp( fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME ) ) ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n"); + _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_IDENT; } // check fm - if( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) - { + if ( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Header Version incorrect\n"); + _pico_printf( PICO_WARNING, "FM Header Version incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_VERSION; } // Skin - fm.fm_skin_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_skin_hdr->size; + fm.fm_skin_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_skin_hdr->size; #ifdef FM_VERBOSE_DBG _pico_printf( PICO_VERBOSE, "SKIN: %s\n", (unsigned char *) fm.fm_skin_hdr->ident ); #endif - if( (strcmp(fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME)) ) - { + if ( ( strcmp( fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME ) ) ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n"); + _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_IDENT; } // check fm - if( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) - { + if ( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n"); + _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_VERSION; } // st - fm.fm_st_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_st_hdr->size; + fm.fm_st_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_st_hdr->size; #ifdef FM_VERBOSE_DBG _pico_printf( PICO_VERBOSE, "ST: %s\n", (unsigned char *) fm.fm_st_hdr->ident ); #endif - if( (strcmp(fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME)) ) - { + if ( ( strcmp( fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME ) ) ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n"); + _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_IDENT; } // check fm - if( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) - { + if ( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM ST Version incorrect\n"); + _pico_printf( PICO_WARNING, "FM ST Version incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_VERSION; } // tri - fm.fm_tri_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_tri_hdr->size; + fm.fm_tri_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_tri_hdr->size; #ifdef FM_VERBOSE_DBG _pico_printf( PICO_VERBOSE, "TRI: %s\n", (unsigned char *) fm.fm_tri_hdr->ident ); #endif - if( (strcmp(fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME)) ) - { + if ( ( strcmp( fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME ) ) ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n"); + _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_IDENT; } // check fm - if( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) - { + if ( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n"); + _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_VERSION; } // frame - fm.fm_frame_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t); + fm.fm_frame_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ); #ifdef FM_VERBOSE_DBG _pico_printf( PICO_VERBOSE, "FRAME: %s\n", (unsigned char *) fm.fm_frame_hdr->ident ); #endif - if( (strcmp(fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME)) ) - { + if ( ( strcmp( fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME ) ) ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n"); + _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_IDENT; } // check fm - if( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) - { + if ( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) { #ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n"); + _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n" ); #endif - _pico_free(bb0); + _pico_free( bb0 ); return PICO_PMV_ERROR_VERSION; } @@ -204,156 +193,143 @@ static int _fm_canload( PM_PARAMS_CANLOAD ) // _fm_load() loads a Heretic 2 model file. -static picoModel_t *_fm_load( PM_PARAMS_LOAD ) -{ - int i, j, dups, dup_index; - int fm_file_pos; - index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; - index_DUP_LUT_t *p_index_LUT_DUPS; - - fm_vert_normal_t *vert; - - char skinname[FM_SKINPATHSIZE]; - fm_t fm; - fm_header_t *fm_head; - fm_st_t *texCoord; - fm_xyz_st_t *tri_verts; - fm_xyz_st_t *triangle; - fm_frame_t *frame; +static picoModel_t *_fm_load( PM_PARAMS_LOAD ){ + int i, j, dups, dup_index; + int fm_file_pos; + index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; + index_DUP_LUT_t *p_index_LUT_DUPS; + + fm_vert_normal_t *vert; + + char skinname[FM_SKINPATHSIZE]; + fm_t fm; + fm_header_t *fm_head; + fm_st_t *texCoord; + fm_xyz_st_t *tri_verts; + fm_xyz_st_t *triangle; + fm_frame_t *frame; picoByte_t *bb, *bb0; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); + + bb0 = bb = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bb, buffer, bufSize ); // Header Header fm.fm_header_hdr = (fm_chunk_header_t *) bb; - fm_file_pos = sizeof(fm_chunk_header_t) + fm.fm_header_hdr->size; - if( (strcmp(fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME)) ) - { - _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n"); - _pico_free(bb0); + fm_file_pos = sizeof( fm_chunk_header_t ) + fm.fm_header_hdr->size; + if ( ( strcmp( fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME ) ) ) { + _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n" ); + _pico_free( bb0 ); return NULL; } - if( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Header Version incorrect\n"); - _pico_free(bb0); + if ( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) { + _pico_printf( PICO_WARNING, "FM Header Version incorrect\n" ); + _pico_free( bb0 ); return NULL; } // Skin Header - fm.fm_skin_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_skin_hdr->size; - if( (strcmp(fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME)) ) - { - _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n"); - _pico_free(bb0); + fm.fm_skin_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_skin_hdr->size; + if ( ( strcmp( fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME ) ) ) { + _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n" ); + _pico_free( bb0 ); return NULL; } - if( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n"); - _pico_free(bb0); + if ( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) { + _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n" ); + _pico_free( bb0 ); return NULL; } // ST Header - fm.fm_st_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_st_hdr->size; - if( (strcmp(fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME)) ) - { - _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n"); - _pico_free(bb0); + fm.fm_st_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_st_hdr->size; + if ( ( strcmp( fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME ) ) ) { + _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n" ); + _pico_free( bb0 ); return NULL; } - if( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM ST Version incorrect\n"); - _pico_free(bb0); + if ( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) { + _pico_printf( PICO_WARNING, "FM ST Version incorrect\n" ); + _pico_free( bb0 ); return NULL; } // Tris Header - fm.fm_tri_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t) + fm.fm_tri_hdr->size; - if( (strcmp(fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME)) ) - { - _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n"); - _pico_free(bb0); + fm.fm_tri_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_tri_hdr->size; + if ( ( strcmp( fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME ) ) ) { + _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n" ); + _pico_free( bb0 ); return NULL; } - if( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n"); - _pico_free(bb0); + if ( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) { + _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n" ); + _pico_free( bb0 ); return NULL; } // Frame Header - fm.fm_frame_hdr = (fm_chunk_header_t *) (bb + fm_file_pos); - fm_file_pos += sizeof(fm_chunk_header_t); - if( (strcmp(fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME)) ) - { - _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n"); - _pico_free(bb0); + fm.fm_frame_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); + fm_file_pos += sizeof( fm_chunk_header_t ); + if ( ( strcmp( fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME ) ) ) { + _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n" ); + _pico_free( bb0 ); return NULL; } - if( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n"); - _pico_free(bb0); + if ( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) { + _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n" ); + _pico_free( bb0 ); return NULL; } // Header - fm_file_pos = sizeof(fm_chunk_header_t); - fm_head = fm.fm_header = (fm_header_t *) (bb + fm_file_pos); + fm_file_pos = sizeof( fm_chunk_header_t ); + fm_head = fm.fm_header = (fm_header_t *) ( bb + fm_file_pos ); fm_file_pos += fm.fm_header_hdr->size; // Skin - fm_file_pos += sizeof(fm_chunk_header_t); - fm.fm_skin = (fm_skinpath_t *) (bb + fm_file_pos); + fm_file_pos += sizeof( fm_chunk_header_t ); + fm.fm_skin = (fm_skinpath_t *) ( bb + fm_file_pos ); fm_file_pos += fm.fm_skin_hdr->size; // ST - fm_file_pos += sizeof(fm_chunk_header_t); - texCoord = fm.fm_st = (fm_st_t *) (bb + fm_file_pos); + fm_file_pos += sizeof( fm_chunk_header_t ); + texCoord = fm.fm_st = (fm_st_t *) ( bb + fm_file_pos ); fm_file_pos += fm.fm_st_hdr->size; // Tri - fm_file_pos += sizeof(fm_chunk_header_t); - tri_verts = fm.fm_tri = (fm_xyz_st_t *) (bb + fm_file_pos); + fm_file_pos += sizeof( fm_chunk_header_t ); + tri_verts = fm.fm_tri = (fm_xyz_st_t *) ( bb + fm_file_pos ); fm_file_pos += fm.fm_tri_hdr->size; // Frame - fm_file_pos += sizeof(fm_chunk_header_t); - frame = fm.fm_frame = (fm_frame_t *) (bb + fm_file_pos); + fm_file_pos += sizeof( fm_chunk_header_t ); + frame = fm.fm_frame = (fm_frame_t *) ( bb + fm_file_pos ); // do frame check - if( fm_head->numFrames < 1 ) - { + if ( fm_head->numFrames < 1 ) { _pico_printf( PICO_ERROR, "%s has 0 frames!", fileName ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - - if( frameNum < 0 || frameNum >= fm_head->numFrames ) - { + + if ( frameNum < 0 || frameNum >= fm_head->numFrames ) { _pico_printf( PICO_ERROR, "Invalid or out-of-range FM frame specified" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -370,7 +346,7 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) fm_head->numFrames = _pico_little_long( fm_head->numFrames ); // swap frame scale and translation - for( i = 0; i < 3; i++ ) + for ( i = 0; i < 3; i++ ) { frame->header.scale[ i ] = _pico_little_float( frame->header.scale[ i ] ); frame->header.translate[ i ] = _pico_little_float( frame->header.translate[ i ] ); @@ -378,9 +354,9 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) // swap triangles triangle = tri_verts; - for( i = 0; i < fm_head->numTris; i++, triangle++ ) + for ( i = 0; i < fm_head->numTris; i++, triangle++ ) { - for( j = 0; j < 3; j++ ) + for ( j = 0; j < 3; j++ ) { triangle->index_xyz[ j ] = _pico_little_short( triangle->index_xyz[ j ] ); triangle->index_st[ j ] = _pico_little_short( triangle->index_st[ j ] ); @@ -388,17 +364,17 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) } // swap st coords - for( i = 0; i < fm_head->numST; i++ ) + for ( i = 0; i < fm_head->numST; i++ ) { texCoord->s = _pico_little_short( texCoord[i].s ); texCoord->t = _pico_little_short( texCoord[i].t ); } // set Skin Name - strncpy(skinname, (const char *) fm.fm_skin, FM_SKINPATHSIZE ); + strncpy( skinname, (const char *) fm.fm_skin, FM_SKINPATHSIZE ); #ifdef FM_VERBOSE_DBG // Print out md2 values - _pico_printf(PICO_VERBOSE,"numSkins->%d numXYZ->%d numST->%d numTris->%d numFrames->%d\nSkin Name \"%s\"\n", fm_head->numSkins, fm_head->numXYZ, fm_head->numST, fm_head->numTris, fm_head->numFrames, &skinname ); + _pico_printf( PICO_VERBOSE,"numSkins->%d numXYZ->%d numST->%d numTris->%d numFrames->%d\nSkin Name \"%s\"\n", fm_head->numSkins, fm_head->numXYZ, fm_head->numST, fm_head->numTris, fm_head->numFrames, &skinname ); #endif // detox Skin name @@ -407,10 +383,9 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) /* create new pico model */ picoModel = PicoNewModel(); - if( picoModel == NULL ) - { + if ( picoModel == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -422,11 +397,10 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) // allocate new pico surface picoSurface = PicoNewSurface( picoModel ); - if( picoSurface == NULL ) - { + if ( picoSurface == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -434,11 +408,10 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); PicoSetSurfaceName( picoSurface, frame->header.name ); picoShader = PicoNewShader( picoModel ); - if( picoShader == NULL ) - { + if ( picoShader == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -448,8 +421,8 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) PicoSetSurfaceShader( picoSurface, picoShader ); // Init LUT for Verts - p_index_LUT = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t) * fm_head->numXYZ); - for(i=0; inumXYZ; i++) + p_index_LUT = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) * fm_head->numXYZ ); + for ( i = 0; i < fm_head->numXYZ; i++ ) { p_index_LUT[i].Vert = -1; p_index_LUT[i].ST = -1; @@ -460,31 +433,32 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) dups = 0; triangle = tri_verts; - for(i=0; inumTris; i++) + for ( i = 0; i < fm_head->numTris; i++ ) { - for(j=0; j<3; j++) + for ( j = 0; j < 3; j++ ) { - if (p_index_LUT[triangle->index_xyz[j]].ST == -1) // No Main Entry + if ( p_index_LUT[triangle->index_xyz[j]].ST == -1 ) { // No Main Entry p_index_LUT[triangle->index_xyz[j]].ST = triangle->index_st[j]; + } - else if (triangle->index_st[j] == p_index_LUT[triangle->index_xyz[j]].ST ) // Equal to Main Entry - { + else if ( triangle->index_st[j] == p_index_LUT[triangle->index_xyz[j]].ST ) { // Equal to Main Entry #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "-> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j]); + _pico_printf( PICO_NORMAL, "-> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); #endif continue; } - else if ( (p_index_LUT[triangle->index_xyz[j]].next == NULL) ) // Not equal to Main entry, and no LL entry - { // Add first entry of LL from Main - p_index_LUT2 = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t)); - if (p_index_LUT2 == NULL) - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n"); + else if ( ( p_index_LUT[triangle->index_xyz[j]].next == NULL ) ) { // Not equal to Main entry, and no LL entry + // Add first entry of LL from Main + p_index_LUT2 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); + if ( p_index_LUT2 == NULL ) { + _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); + } p_index_LUT[triangle->index_xyz[j]].next = (index_LUT_t *)p_index_LUT2; p_index_LUT2->Vert = dups; p_index_LUT2->ST = triangle->index_st[j]; p_index_LUT2->next = NULL; #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " ADDING first LL XYZ:%d DUP:%d ST:%d\n", triangle->index_xyz[j], dups, triangle->index_st[j]); + _pico_printf( PICO_NORMAL, " ADDING first LL XYZ:%d DUP:%d ST:%d\n", triangle->index_xyz[j], dups, triangle->index_st[j] ); #endif triangle->index_xyz[j] = dups + fm_head->numXYZ; // Make change in Tri hunk dups++; @@ -492,56 +466,56 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) else // Try to find in LL from Main Entry { p_index_LUT3 = p_index_LUT2 = p_index_LUT[triangle->index_xyz[j]].next; - while ( (p_index_LUT2 != NULL) && (triangle->index_xyz[j] != p_index_LUT2->Vert) ) // Walk down LL + while ( ( p_index_LUT2 != NULL ) && ( triangle->index_xyz[j] != p_index_LUT2->Vert ) ) // Walk down LL { p_index_LUT3 = p_index_LUT2; p_index_LUT2 = p_index_LUT2->next; } p_index_LUT2 = p_index_LUT3; - if ( triangle->index_st[j] == p_index_LUT2->ST ) // Found it - { + if ( triangle->index_st[j] == p_index_LUT2->ST ) { // Found it triangle->index_xyz[j] = p_index_LUT2->Vert + fm_head->numXYZ; // Make change in Tri hunk #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "--> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j]); + _pico_printf( PICO_NORMAL, "--> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); #endif continue; } - if ( p_index_LUT2->next == NULL) // Didn't find it. Add entry to LL. - { + if ( p_index_LUT2->next == NULL ) { // Didn't find it. Add entry to LL. // Add the Entry - p_index_LUT3 = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t)); - if (p_index_LUT3 == NULL) - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n"); + p_index_LUT3 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); + if ( p_index_LUT3 == NULL ) { + _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); + } p_index_LUT2->next = (index_LUT_t *)p_index_LUT3; p_index_LUT3->Vert = dups; p_index_LUT3->ST = triangle->index_st[j]; p_index_LUT3->next = NULL; #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " ADDING additional LL XYZ:%d DUP:%d NewXYZ:%d ST:%d\n", triangle->index_xyz[j], dups, dups + (fm_head->numXYZ), triangle->index_st[j]); + _pico_printf( PICO_NORMAL, " ADDING additional LL XYZ:%d DUP:%d NewXYZ:%d ST:%d\n", triangle->index_xyz[j], dups, dups + ( fm_head->numXYZ ), triangle->index_st[j] ); #endif triangle->index_xyz[j] = dups + fm_head->numXYZ; // Make change in Tri hunk dups++; } } #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "---> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j]); + _pico_printf( PICO_NORMAL, "---> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); #endif } triangle++; } // malloc and build array for Dup STs - p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc(sizeof(index_DUP_LUT_t) * dups); - if (p_index_LUT_DUPS == NULL) - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n"); + p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc( sizeof( index_DUP_LUT_t ) * dups ); + if ( p_index_LUT_DUPS == NULL ) { + _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); + } dup_index = 0; - for(i=0; inumXYZ; i++) + for ( i = 0; i < fm_head->numXYZ; i++ ) { p_index_LUT2 = p_index_LUT[i].next; - while (p_index_LUT2 != NULL) + while ( p_index_LUT2 != NULL ) { p_index_LUT_DUPS[p_index_LUT2->Vert].OldVert = i; p_index_LUT_DUPS[p_index_LUT2->Vert].ST = p_index_LUT2->ST; @@ -550,96 +524,94 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) } } #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " Dups = %d\n", dups); - _pico_printf( PICO_NORMAL, " Dup Index = %d\n", dup_index); + _pico_printf( PICO_NORMAL, " Dups = %d\n", dups ); + _pico_printf( PICO_NORMAL, " Dup Index = %d\n", dup_index ); #endif - for(i=0; inumXYZ; i++) + for ( i = 0; i < fm_head->numXYZ; i++ ) { #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "Vert: %4d\t%4d",i, p_index_LUT[i].ST); + _pico_printf( PICO_NORMAL, "Vert: %4d\t%4d",i, p_index_LUT[i].ST ); #endif - if (p_index_LUT[i].next != NULL) - { + if ( p_index_LUT[i].next != NULL ) { p_index_LUT2 = p_index_LUT[i].next; do { #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " %4d %4d", p_index_LUT2->Vert, p_index_LUT2->ST); + _pico_printf( PICO_NORMAL, " %4d %4d", p_index_LUT2->Vert, p_index_LUT2->ST ); #endif p_index_LUT2 = p_index_LUT2->next; - } while ( p_index_LUT2 != NULL); + } while ( p_index_LUT2 != NULL ); } #ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "\n"); + _pico_printf( PICO_NORMAL, "\n" ); #endif } #ifdef FM_VERBOSE_DBG - for(i=0; inumTris; i++) + for ( i = 0; i < fm_head->numTris; i++ ) { - for(j=0; j<3; j++) - _pico_printf( PICO_NORMAL, "Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j]); - _pico_printf( PICO_NORMAL, "\n"); + for ( j = 0; j < 3; j++ ) + _pico_printf( PICO_NORMAL, "Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); + _pico_printf( PICO_NORMAL, "\n" ); triangle++; } #endif // Build Picomodel triangle = tri_verts; - for( j = 0; j < fm_head->numTris; j++, triangle++ ) + for ( j = 0; j < fm_head->numTris; j++, triangle++ ) { - PicoSetSurfaceIndex( picoSurface, j*3 , triangle->index_xyz[0] ); - PicoSetSurfaceIndex( picoSurface, j*3+1 , triangle->index_xyz[1] ); - PicoSetSurfaceIndex( picoSurface, j*3+2 , triangle->index_xyz[2] ); + PicoSetSurfaceIndex( picoSurface, j * 3, triangle->index_xyz[0] ); + PicoSetSurfaceIndex( picoSurface, j * 3 + 1, triangle->index_xyz[1] ); + PicoSetSurfaceIndex( picoSurface, j * 3 + 2, triangle->index_xyz[2] ); } - vert = (fm_vert_normal_t*) ((picoByte_t*) (frame->verts) ); - for(i=0; i< fm_head->numXYZ; i++, vert++) + vert = (fm_vert_normal_t*) ( (picoByte_t*) ( frame->verts ) ); + for ( i = 0; i < fm_head->numXYZ; i++, vert++ ) { /* set vertex origin */ xyz[ 0 ] = vert->v[0] * frame->header.scale[0] + frame->header.translate[0]; xyz[ 1 ] = vert->v[1] * frame->header.scale[1] + frame->header.translate[1]; xyz[ 2 ] = vert->v[2] * frame->header.scale[2] + frame->header.translate[2]; - PicoSetSurfaceXYZ( picoSurface, i , xyz ); + PicoSetSurfaceXYZ( picoSurface, i, xyz ); /* set normal */ normal[ 0 ] = fm_normals[vert->lightnormalindex][0]; normal[ 1 ] = fm_normals[vert->lightnormalindex][1]; normal[ 2 ] = fm_normals[vert->lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i , normal ); + PicoSetSurfaceNormal( picoSurface, i, normal ); /* set st coords */ - st[ 0 ] = ((texCoord[p_index_LUT[i].ST].s) / ((float)fm_head->skinWidth)); - st[ 1 ] = (texCoord[p_index_LUT[i].ST].t / ((float)fm_head->skinHeight)); - PicoSetSurfaceST( picoSurface, 0, i , st ); + st[ 0 ] = ( ( texCoord[p_index_LUT[i].ST].s ) / ( (float)fm_head->skinWidth ) ); + st[ 1 ] = ( texCoord[p_index_LUT[i].ST].t / ( (float)fm_head->skinHeight ) ); + PicoSetSurfaceST( picoSurface, 0, i, st ); } - if (dups) - { - for(i=0; iverts[j].v[0] * frame->header.scale[0] + frame->header.translate[0]; xyz[ 1 ] = frame->verts[j].v[1] * frame->header.scale[1] + frame->header.translate[1]; xyz[ 2 ] = frame->verts[j].v[2] * frame->header.scale[2] + frame->header.translate[2]; - PicoSetSurfaceXYZ( picoSurface, i + fm_head->numXYZ , xyz ); + PicoSetSurfaceXYZ( picoSurface, i + fm_head->numXYZ, xyz ); /* set normal */ normal[ 0 ] = fm_normals[frame->verts[j].lightnormalindex][0]; normal[ 1 ] = fm_normals[frame->verts[j].lightnormalindex][1]; normal[ 2 ] = fm_normals[frame->verts[j].lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i + fm_head->numXYZ , normal ); + PicoSetSurfaceNormal( picoSurface, i + fm_head->numXYZ, normal ); /* set st coords */ - st[ 0 ] = ((texCoord[p_index_LUT_DUPS[i].ST].s) / ((float)fm_head->skinWidth)); - st[ 1 ] = (texCoord[p_index_LUT_DUPS[i].ST].t / ((float)fm_head->skinHeight)); - PicoSetSurfaceST( picoSurface, 0, i + fm_head->numXYZ , st ); + st[ 0 ] = ( ( texCoord[p_index_LUT_DUPS[i].ST].s ) / ( (float)fm_head->skinWidth ) ); + st[ 1 ] = ( texCoord[p_index_LUT_DUPS[i].ST].t / ( (float)fm_head->skinHeight ) ); + PicoSetSurfaceST( picoSurface, 0, i + fm_head->numXYZ, st ); } } @@ -647,29 +619,29 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) PicoSetSurfaceColor( picoSurface, 0, 0, color ); // Free up malloc'ed LL entries - for(i=0; inumXYZ; i++) + for ( i = 0; i < fm_head->numXYZ; i++ ) { - if(p_index_LUT[i].next != NULL) - { + if ( p_index_LUT[i].next != NULL ) { p_index_LUT2 = p_index_LUT[i].next; do { p_index_LUT3 = p_index_LUT2->next; - _pico_free(p_index_LUT2); + _pico_free( p_index_LUT2 ); p_index_LUT2 = p_index_LUT3; dups--; - } while (p_index_LUT2 != NULL); + } while ( p_index_LUT2 != NULL ); } } - if (dups) - _pico_printf(PICO_WARNING, " Not all LL mallocs freed\n"); + if ( dups ) { + _pico_printf( PICO_WARNING, " Not all LL mallocs freed\n" ); + } // Free malloc'ed LUTs - _pico_free(p_index_LUT); - _pico_free(p_index_LUT_DUPS); + _pico_free( p_index_LUT ); + _pico_free( p_index_LUT_DUPS ); /* return the new pico model */ - _pico_free(bb0); + _pico_free( bb0 ); return picoModel; } @@ -679,15 +651,15 @@ static picoModel_t *_fm_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleFM = { - "0.85", /* module version string */ - "Heretic 2 FM", /* module display name */ - "Nurail", /* author's name */ - "2003 Nurail", /* module copyright */ + "0.85", /* module version string */ + "Heretic 2 FM", /* module display name */ + "Nurail", /* author's name */ + "2003 Nurail", /* module copyright */ { - "fm", NULL, NULL, NULL /* default extensions to use */ + "fm", NULL, NULL, NULL /* default extensions to use */ }, - _fm_canload, /* validation routine */ - _fm_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _fm_canload, /* validation routine */ + _fm_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_fm.h b/libs/picomodel/pm_fm.h index 3fd5148e..6fa317ca 100644 --- a/libs/picomodel/pm_fm.h +++ b/libs/picomodel/pm_fm.h @@ -1,48 +1,48 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ // This header file is based from the following: /* - FlexModel.H - Header file for FlexModel file structure + FlexModel.H - Header file for FlexModel file structure - By Chris Burke - serotonin@earthlink.net -*/ + By Chris Burke + serotonin@earthlink.net + */ -#ifndef __PM_FM_H__ -#define __PM_FM_H__ +#ifndef __PM_FM_H__ +#define __PM_FM_H__ #include "picointernal.h" @@ -50,12 +50,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Absolute limits (from QData / QMView source) // -#define MAX_FM_TRIANGLES 2048 -#define MAX_FM_VERTS 2048 -#define MAX_FM_FRAMES 2048 -#define MAX_FM_SKINS 64 -#define MAX_FM_SKINNAME 64 -#define MAX_FM_MESH_NODES 16 +#define MAX_FM_TRIANGLES 2048 +#define MAX_FM_VERTS 2048 +#define MAX_FM_FRAMES 2048 +#define MAX_FM_SKINS 64 +#define MAX_FM_SKINNAME 64 +#define MAX_FM_MESH_NODES 16 #define DTRIVERTX_V0 0 #define DTRIVERTX_V1 1 @@ -74,7 +74,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SCALE_ADJUST_FACTOR 0.96 #define INFO_HEIGHT 5 -#define INFO_Y (SKINPAGE_HEIGHT-INFO_HEIGHT) +#define INFO_Y ( SKINPAGE_HEIGHT - INFO_HEIGHT ) #ifndef byte #define byte unsigned char @@ -84,45 +84,45 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Generic header on every chunk // -#define FM_MAXCHUNKIDENT 32L +#define FM_MAXCHUNKIDENT 32L typedef struct { - char ident[FM_MAXCHUNKIDENT]; - unsigned int version; - unsigned int size; + char ident[FM_MAXCHUNKIDENT]; + unsigned int version; + unsigned int size; } fm_chunk_header_t; // // The format of the "header" chunk // -#define FM_HEADERCHUNKNAME "header" -#define FM_HEADERCHUNKVER 2 -#define FM_HEADERCHUNKSIZE 40 +#define FM_HEADERCHUNKNAME "header" +#define FM_HEADERCHUNKVER 2 +#define FM_HEADERCHUNKSIZE 40 typedef struct { - int skinWidth; // in pixels - int skinHeight; // in pixels - int frameSize; // size of each frame (in bytes) - int numSkins; // number of skins - int numXYZ; // number of unique vertices in 3D space - int numST; // number of unique vertices in texture space - int numTris; // number of unique triangles - int numGLCmds; // # 32-bit elements in strip/fan command list - int numFrames; // number of animation frames - int numMeshNodes; // number of mesh nodes + int skinWidth; // in pixels + int skinHeight; // in pixels + int frameSize; // size of each frame (in bytes) + int numSkins; // number of skins + int numXYZ; // number of unique vertices in 3D space + int numST; // number of unique vertices in texture space + int numTris; // number of unique triangles + int numGLCmds; // # 32-bit elements in strip/fan command list + int numFrames; // number of animation frames + int numMeshNodes; // number of mesh nodes } fm_header_t; // // The format of an entry in the "skin" chunk. // The number of entries is given in the fmheader chunk // -#define FM_SKINCHUNKNAME "skin" -#define FM_SKINCHUNKVER 1 -#define FM_MAXPATHLENGTH 64L -#define FM_SKINPATHSIZE (FM_MAXPATHLENGTH) +#define FM_SKINCHUNKNAME "skin" +#define FM_SKINCHUNKVER 1 +#define FM_MAXPATHLENGTH 64L +#define FM_SKINPATHSIZE ( FM_MAXPATHLENGTH ) typedef struct { - char path[FM_SKINPATHSIZE]; // path, relative to 'base' + char path[FM_SKINPATHSIZE]; // path, relative to 'base' } fm_skinpath_t; // @@ -130,28 +130,28 @@ typedef struct // of unique skin texture (u, v) coordinates to be mapped // to verteces of the model // -#define FM_STCOORDCHUNKNAME "st coord" -#define FM_STCOORDCHUNKVER 1 -#define FM_STCOORDUVSIZE (2L + 2L) +#define FM_STCOORDCHUNKNAME "st coord" +#define FM_STCOORDCHUNKVER 1 +#define FM_STCOORDUVSIZE ( 2L + 2L ) typedef struct { - short s; - short t; + short s; + short t; } fm_st_t; // // The format of the "tris" chunk. This is a list of vertex indeces // in 3D space, and the corresponding vertex indeces in texture space. // -#define FM_TRISCHUNKNAME "tris" -#define FM_TRISCHUNKVER 1 -#define FM_TRISINFOSIZE (2L*3 + 2L*3) +#define FM_TRISCHUNKNAME "tris" +#define FM_TRISCHUNKVER 1 +#define FM_TRISINFOSIZE ( 2L * 3 + 2L * 3 ) typedef struct { - short index_xyz[3]; - short index_st[3]; + short index_xyz[3]; + short index_st[3]; } fm_xyz_st_t; @@ -160,208 +160,208 @@ typedef struct // frames, each specifying the coordinates and "light normal" index // of every vertex of the model in 3D space. // -#define FM_FRAMESCHUNKNAME "frames" -#define FM_FRAMESCHUNKVER 1 +#define FM_FRAMESCHUNKNAME "frames" +#define FM_FRAMESCHUNKVER 1 -#define FM_NUMVERTEXNORMALS 162 +#define FM_NUMVERTEXNORMALS 162 // Frame info typedef struct { - byte v[3]; // scaled by header info - byte lightnormalindex; // index in canned table of closest vertex normal + byte v[3]; // scaled by header info + byte lightnormalindex; // index in canned table of closest vertex normal } fm_vert_normal_t; typedef struct { - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name } fm_framehdr_t; typedef struct { - fm_framehdr_t header; // One header per frame - fm_vert_normal_t verts[1]; // variable number of these + fm_framehdr_t header; // One header per frame + fm_vert_normal_t verts[1]; // variable number of these } fm_frame_t; typedef struct { - fm_chunk_header_t *fm_header_hdr; - fm_header_t *fm_header; - fm_chunk_header_t *fm_skin_hdr; - fm_skinpath_t *fm_skin; - fm_chunk_header_t *fm_st_hdr; - fm_st_t *fm_st; - fm_chunk_header_t *fm_tri_hdr; - fm_xyz_st_t *fm_tri; - fm_chunk_header_t *fm_frame_hdr; - fm_frame_t *fm_frame; + fm_chunk_header_t *fm_header_hdr; + fm_header_t *fm_header; + fm_chunk_header_t *fm_skin_hdr; + fm_skinpath_t *fm_skin; + fm_chunk_header_t *fm_st_hdr; + fm_st_t *fm_st; + fm_chunk_header_t *fm_tri_hdr; + fm_xyz_st_t *fm_tri; + fm_chunk_header_t *fm_frame_hdr; + fm_frame_t *fm_frame; } fm_t; -float fm_normals[FM_NUMVERTEXNORMALS][3] = { - {-0.525731f, 0.000000f, 0.850651f}, - {-0.442863f, 0.238856f, 0.864188f}, - {-0.295242f, 0.000000f, 0.955423f}, - {-0.309017f, 0.500000f, 0.809017f}, - {-0.162460f, 0.262866f, 0.951056f}, - {0.000000f, 0.000000f, 1.000000f}, - {0.000000f, 0.850651f, 0.525731f}, - {-0.147621f, 0.716567f, 0.681718f}, - {0.147621f, 0.716567f, 0.681718f}, - {0.000000f, 0.525731f, 0.850651f}, - {0.309017f, 0.500000f, 0.809017f}, - {0.525731f, 0.000000f, 0.850651f}, - {0.295242f, 0.000000f, 0.955423f}, - {0.442863f, 0.238856f, 0.864188f}, - {0.162460f, 0.262866f, 0.951056f}, - {-0.681718f, 0.147621f, 0.716567f}, - {-0.809017f, 0.309017f, 0.500000f}, - {-0.587785f, 0.425325f, 0.688191f}, - {-0.850651f, 0.525731f, 0.000000f}, - {-0.864188f, 0.442863f, 0.238856f}, - {-0.716567f, 0.681718f, 0.147621f}, - {-0.688191f, 0.587785f, 0.425325f}, - {-0.500000f, 0.809017f, 0.309017f}, - {-0.238856f, 0.864188f, 0.442863f}, - {-0.425325f, 0.688191f, 0.587785f}, - {-0.716567f, 0.681718f, -0.147621f}, - {-0.500000f, 0.809017f, -0.309017f}, - {-0.525731f, 0.850651f, 0.000000f}, - {0.000000f, 0.850651f, -0.525731f}, - {-0.238856f, 0.864188f, -0.442863f}, - {0.000000f, 0.955423f, -0.295242f}, - {-0.262866f, 0.951056f, -0.162460f}, - {0.000000f, 1.000000f, 0.000000f}, - {0.000000f, 0.955423f, 0.295242f}, - {-0.262866f, 0.951056f, 0.162460f}, - {0.238856f, 0.864188f, 0.442863f}, - {0.262866f, 0.951056f, 0.162460f}, - {0.500000f, 0.809017f, 0.309017f}, - {0.238856f, 0.864188f, -0.442863f}, - {0.262866f, 0.951056f, -0.162460f}, - {0.500000f, 0.809017f, -0.309017f}, - {0.850651f, 0.525731f, 0.000000f}, - {0.716567f, 0.681718f, 0.147621f}, - {0.716567f, 0.681718f, -0.147621f}, - {0.525731f, 0.850651f, 0.000000f}, - {0.425325f, 0.688191f, 0.587785f}, - {0.864188f, 0.442863f, 0.238856f}, - {0.688191f, 0.587785f, 0.425325f}, - {0.809017f, 0.309017f, 0.500000f}, - {0.681718f, 0.147621f, 0.716567f}, - {0.587785f, 0.425325f, 0.688191f}, - {0.955423f, 0.295242f, 0.000000f}, - {1.000000f, 0.000000f, 0.000000f}, - {0.951056f, 0.162460f, 0.262866f}, - {0.850651f, -0.525731f, 0.000000f}, - {0.955423f, -0.295242f, 0.000000f}, - {0.864188f, -0.442863f, 0.238856f}, - {0.951056f, -0.162460f, 0.262866f}, - {0.809017f, -0.309017f, 0.500000f}, - {0.681718f, -0.147621f, 0.716567f}, - {0.850651f, 0.000000f, 0.525731f}, - {0.864188f, 0.442863f, -0.238856f}, - {0.809017f, 0.309017f, -0.500000f}, - {0.951056f, 0.162460f, -0.262866f}, - {0.525731f, 0.000000f, -0.850651f}, - {0.681718f, 0.147621f, -0.716567f}, - {0.681718f, -0.147621f, -0.716567f}, - {0.850651f, 0.000000f, -0.525731f}, - {0.809017f, -0.309017f, -0.500000f}, - {0.864188f, -0.442863f, -0.238856f}, - {0.951056f, -0.162460f, -0.262866f}, - {0.147621f, 0.716567f, -0.681718f}, - {0.309017f, 0.500000f, -0.809017f}, - {0.425325f, 0.688191f, -0.587785f}, - {0.442863f, 0.238856f, -0.864188f}, - {0.587785f, 0.425325f, -0.688191f}, - {0.688191f, 0.587785f, -0.425325f}, - {-0.147621f, 0.716567f, -0.681718f}, - {-0.309017f, 0.500000f, -0.809017f}, - {0.000000f, 0.525731f, -0.850651f}, - {-0.525731f, 0.000000f, -0.850651f}, - {-0.442863f, 0.238856f, -0.864188f}, - {-0.295242f, 0.000000f, -0.955423f}, - {-0.162460f, 0.262866f, -0.951056f}, - {0.000000f, 0.000000f, -1.000000f}, - {0.295242f, 0.000000f, -0.955423f}, - {0.162460f, 0.262866f, -0.951056f}, - {-0.442863f, -0.238856f, -0.864188f}, - {-0.309017f, -0.500000f, -0.809017f}, - {-0.162460f, -0.262866f, -0.951056f}, - {0.000000f, -0.850651f, -0.525731f}, - {-0.147621f, -0.716567f, -0.681718f}, - {0.147621f, -0.716567f, -0.681718f}, - {0.000000f, -0.525731f, -0.850651f}, - {0.309017f, -0.500000f, -0.809017f}, - {0.442863f, -0.238856f, -0.864188f}, - {0.162460f, -0.262866f, -0.951056f}, - {0.238856f, -0.864188f, -0.442863f}, - {0.500000f, -0.809017f, -0.309017f}, - {0.425325f, -0.688191f, -0.587785f}, - {0.716567f, -0.681718f, -0.147621f}, - {0.688191f, -0.587785f, -0.425325f}, - {0.587785f, -0.425325f, -0.688191f}, - {0.000000f, -0.955423f, -0.295242f}, - {0.000000f, -1.000000f, 0.000000f}, - {0.262866f, -0.951056f, -0.162460f}, - {0.000000f, -0.850651f, 0.525731f}, - {0.000000f, -0.955423f, 0.295242f}, - {0.238856f, -0.864188f, 0.442863f}, - {0.262866f, -0.951056f, 0.162460f}, - {0.500000f, -0.809017f, 0.309017f}, - {0.716567f, -0.681718f, 0.147621f}, - {0.525731f, -0.850651f, 0.000000f}, - {-0.238856f, -0.864188f, -0.442863f}, - {-0.500000f, -0.809017f, -0.309017f}, - {-0.262866f, -0.951056f, -0.162460f}, - {-0.850651f, -0.525731f, 0.000000f}, - {-0.716567f, -0.681718f, -0.147621f}, - {-0.716567f, -0.681718f, 0.147621f}, - {-0.525731f, -0.850651f, 0.000000f}, - {-0.500000f, -0.809017f, 0.309017f}, - {-0.238856f, -0.864188f, 0.442863f}, - {-0.262866f, -0.951056f, 0.162460f}, - {-0.864188f, -0.442863f, 0.238856f}, - {-0.809017f, -0.309017f, 0.500000f}, - {-0.688191f, -0.587785f, 0.425325f}, - {-0.681718f, -0.147621f, 0.716567f}, - {-0.442863f, -0.238856f, 0.864188f}, - {-0.587785f, -0.425325f, 0.688191f}, - {-0.309017f, -0.500000f, 0.809017f}, - {-0.147621f, -0.716567f, 0.681718f}, - {-0.425325f, -0.688191f, 0.587785f}, - {-0.162460f, -0.262866f, 0.951056f}, - {0.442863f, -0.238856f, 0.864188f}, - {0.162460f, -0.262866f, 0.951056f}, - {0.309017f, -0.500000f, 0.809017f}, - {0.147621f, -0.716567f, 0.681718f}, - {0.000000f, -0.525731f, 0.850651f}, - {0.425325f, -0.688191f, 0.587785f}, - {0.587785f, -0.425325f, 0.688191f}, - {0.688191f, -0.587785f, 0.425325f}, - {-0.955423f, 0.295242f, 0.000000f}, - {-0.951056f, 0.162460f, 0.262866f}, - {-1.000000f, 0.000000f, 0.000000f}, - {-0.850651f, 0.000000f, 0.525731f}, - {-0.955423f, -0.295242f, 0.000000f}, - {-0.951056f, -0.162460f, 0.262866f}, - {-0.864188f, 0.442863f, -0.238856f}, - {-0.951056f, 0.162460f, -0.262866f}, - {-0.809017f, 0.309017f, -0.500000f}, - {-0.864188f, -0.442863f, -0.238856f}, - {-0.951056f, -0.162460f, -0.262866f}, - {-0.809017f, -0.309017f, -0.500000f}, - {-0.681718f, 0.147621f, -0.716567f}, - {-0.681718f, -0.147621f, -0.716567f}, - {-0.850651f, 0.000000f, -0.525731f}, - {-0.688191f, 0.587785f, -0.425325f}, - {-0.587785f, 0.425325f, -0.688191f}, - {-0.425325f, 0.688191f, -0.587785f}, - {-0.425325f, -0.688191f, -0.587785f}, - {-0.587785f, -0.425325f, -0.688191f}, - {-0.688191f, -0.587785f, -0.425325f}, +float fm_normals[FM_NUMVERTEXNORMALS][3] = { + {-0.525731f, 0.000000f, 0.850651f}, + {-0.442863f, 0.238856f, 0.864188f}, + {-0.295242f, 0.000000f, 0.955423f}, + {-0.309017f, 0.500000f, 0.809017f}, + {-0.162460f, 0.262866f, 0.951056f}, + {0.000000f, 0.000000f, 1.000000f}, + {0.000000f, 0.850651f, 0.525731f}, + {-0.147621f, 0.716567f, 0.681718f}, + {0.147621f, 0.716567f, 0.681718f}, + {0.000000f, 0.525731f, 0.850651f}, + {0.309017f, 0.500000f, 0.809017f}, + {0.525731f, 0.000000f, 0.850651f}, + {0.295242f, 0.000000f, 0.955423f}, + {0.442863f, 0.238856f, 0.864188f}, + {0.162460f, 0.262866f, 0.951056f}, + {-0.681718f, 0.147621f, 0.716567f}, + {-0.809017f, 0.309017f, 0.500000f}, + {-0.587785f, 0.425325f, 0.688191f}, + {-0.850651f, 0.525731f, 0.000000f}, + {-0.864188f, 0.442863f, 0.238856f}, + {-0.716567f, 0.681718f, 0.147621f}, + {-0.688191f, 0.587785f, 0.425325f}, + {-0.500000f, 0.809017f, 0.309017f}, + {-0.238856f, 0.864188f, 0.442863f}, + {-0.425325f, 0.688191f, 0.587785f}, + {-0.716567f, 0.681718f, -0.147621f}, + {-0.500000f, 0.809017f, -0.309017f}, + {-0.525731f, 0.850651f, 0.000000f}, + {0.000000f, 0.850651f, -0.525731f}, + {-0.238856f, 0.864188f, -0.442863f}, + {0.000000f, 0.955423f, -0.295242f}, + {-0.262866f, 0.951056f, -0.162460f}, + {0.000000f, 1.000000f, 0.000000f}, + {0.000000f, 0.955423f, 0.295242f}, + {-0.262866f, 0.951056f, 0.162460f}, + {0.238856f, 0.864188f, 0.442863f}, + {0.262866f, 0.951056f, 0.162460f}, + {0.500000f, 0.809017f, 0.309017f}, + {0.238856f, 0.864188f, -0.442863f}, + {0.262866f, 0.951056f, -0.162460f}, + {0.500000f, 0.809017f, -0.309017f}, + {0.850651f, 0.525731f, 0.000000f}, + {0.716567f, 0.681718f, 0.147621f}, + {0.716567f, 0.681718f, -0.147621f}, + {0.525731f, 0.850651f, 0.000000f}, + {0.425325f, 0.688191f, 0.587785f}, + {0.864188f, 0.442863f, 0.238856f}, + {0.688191f, 0.587785f, 0.425325f}, + {0.809017f, 0.309017f, 0.500000f}, + {0.681718f, 0.147621f, 0.716567f}, + {0.587785f, 0.425325f, 0.688191f}, + {0.955423f, 0.295242f, 0.000000f}, + {1.000000f, 0.000000f, 0.000000f}, + {0.951056f, 0.162460f, 0.262866f}, + {0.850651f, -0.525731f, 0.000000f}, + {0.955423f, -0.295242f, 0.000000f}, + {0.864188f, -0.442863f, 0.238856f}, + {0.951056f, -0.162460f, 0.262866f}, + {0.809017f, -0.309017f, 0.500000f}, + {0.681718f, -0.147621f, 0.716567f}, + {0.850651f, 0.000000f, 0.525731f}, + {0.864188f, 0.442863f, -0.238856f}, + {0.809017f, 0.309017f, -0.500000f}, + {0.951056f, 0.162460f, -0.262866f}, + {0.525731f, 0.000000f, -0.850651f}, + {0.681718f, 0.147621f, -0.716567f}, + {0.681718f, -0.147621f, -0.716567f}, + {0.850651f, 0.000000f, -0.525731f}, + {0.809017f, -0.309017f, -0.500000f}, + {0.864188f, -0.442863f, -0.238856f}, + {0.951056f, -0.162460f, -0.262866f}, + {0.147621f, 0.716567f, -0.681718f}, + {0.309017f, 0.500000f, -0.809017f}, + {0.425325f, 0.688191f, -0.587785f}, + {0.442863f, 0.238856f, -0.864188f}, + {0.587785f, 0.425325f, -0.688191f}, + {0.688191f, 0.587785f, -0.425325f}, + {-0.147621f, 0.716567f, -0.681718f}, + {-0.309017f, 0.500000f, -0.809017f}, + {0.000000f, 0.525731f, -0.850651f}, + {-0.525731f, 0.000000f, -0.850651f}, + {-0.442863f, 0.238856f, -0.864188f}, + {-0.295242f, 0.000000f, -0.955423f}, + {-0.162460f, 0.262866f, -0.951056f}, + {0.000000f, 0.000000f, -1.000000f}, + {0.295242f, 0.000000f, -0.955423f}, + {0.162460f, 0.262866f, -0.951056f}, + {-0.442863f, -0.238856f, -0.864188f}, + {-0.309017f, -0.500000f, -0.809017f}, + {-0.162460f, -0.262866f, -0.951056f}, + {0.000000f, -0.850651f, -0.525731f}, + {-0.147621f, -0.716567f, -0.681718f}, + {0.147621f, -0.716567f, -0.681718f}, + {0.000000f, -0.525731f, -0.850651f}, + {0.309017f, -0.500000f, -0.809017f}, + {0.442863f, -0.238856f, -0.864188f}, + {0.162460f, -0.262866f, -0.951056f}, + {0.238856f, -0.864188f, -0.442863f}, + {0.500000f, -0.809017f, -0.309017f}, + {0.425325f, -0.688191f, -0.587785f}, + {0.716567f, -0.681718f, -0.147621f}, + {0.688191f, -0.587785f, -0.425325f}, + {0.587785f, -0.425325f, -0.688191f}, + {0.000000f, -0.955423f, -0.295242f}, + {0.000000f, -1.000000f, 0.000000f}, + {0.262866f, -0.951056f, -0.162460f}, + {0.000000f, -0.850651f, 0.525731f}, + {0.000000f, -0.955423f, 0.295242f}, + {0.238856f, -0.864188f, 0.442863f}, + {0.262866f, -0.951056f, 0.162460f}, + {0.500000f, -0.809017f, 0.309017f}, + {0.716567f, -0.681718f, 0.147621f}, + {0.525731f, -0.850651f, 0.000000f}, + {-0.238856f, -0.864188f, -0.442863f}, + {-0.500000f, -0.809017f, -0.309017f}, + {-0.262866f, -0.951056f, -0.162460f}, + {-0.850651f, -0.525731f, 0.000000f}, + {-0.716567f, -0.681718f, -0.147621f}, + {-0.716567f, -0.681718f, 0.147621f}, + {-0.525731f, -0.850651f, 0.000000f}, + {-0.500000f, -0.809017f, 0.309017f}, + {-0.238856f, -0.864188f, 0.442863f}, + {-0.262866f, -0.951056f, 0.162460f}, + {-0.864188f, -0.442863f, 0.238856f}, + {-0.809017f, -0.309017f, 0.500000f}, + {-0.688191f, -0.587785f, 0.425325f}, + {-0.681718f, -0.147621f, 0.716567f}, + {-0.442863f, -0.238856f, 0.864188f}, + {-0.587785f, -0.425325f, 0.688191f}, + {-0.309017f, -0.500000f, 0.809017f}, + {-0.147621f, -0.716567f, 0.681718f}, + {-0.425325f, -0.688191f, 0.587785f}, + {-0.162460f, -0.262866f, 0.951056f}, + {0.442863f, -0.238856f, 0.864188f}, + {0.162460f, -0.262866f, 0.951056f}, + {0.309017f, -0.500000f, 0.809017f}, + {0.147621f, -0.716567f, 0.681718f}, + {0.000000f, -0.525731f, 0.850651f}, + {0.425325f, -0.688191f, 0.587785f}, + {0.587785f, -0.425325f, 0.688191f}, + {0.688191f, -0.587785f, 0.425325f}, + {-0.955423f, 0.295242f, 0.000000f}, + {-0.951056f, 0.162460f, 0.262866f}, + {-1.000000f, 0.000000f, 0.000000f}, + {-0.850651f, 0.000000f, 0.525731f}, + {-0.955423f, -0.295242f, 0.000000f}, + {-0.951056f, -0.162460f, 0.262866f}, + {-0.864188f, 0.442863f, -0.238856f}, + {-0.951056f, 0.162460f, -0.262866f}, + {-0.809017f, 0.309017f, -0.500000f}, + {-0.864188f, -0.442863f, -0.238856f}, + {-0.951056f, -0.162460f, -0.262866f}, + {-0.809017f, -0.309017f, -0.500000f}, + {-0.681718f, 0.147621f, -0.716567f}, + {-0.681718f, -0.147621f, -0.716567f}, + {-0.850651f, 0.000000f, -0.525731f}, + {-0.688191f, 0.587785f, -0.425325f}, + {-0.587785f, 0.425325f, -0.688191f}, + {-0.425325f, 0.688191f, -0.587785f}, + {-0.425325f, -0.688191f, -0.587785f}, + {-0.587785f, -0.425325f, -0.688191f}, + {-0.688191f, -0.587785f, -0.425325f}, }; #endif diff --git a/libs/picomodel/pm_lwo.c b/libs/picomodel/pm_lwo.c index 09cdde9c..812496ae 100644 --- a/libs/picomodel/pm_lwo.c +++ b/libs/picomodel/pm_lwo.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ /* marker */ #define PM_LWO_C @@ -47,32 +47,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif /* helper functions */ -static const char *lwo_lwIDToStr( unsigned int lwID ) -{ +static const char *lwo_lwIDToStr( unsigned int lwID ){ static char lwIDStr[5]; - if (!lwID) - { + if ( !lwID ) { return "n/a"; } - lwIDStr[ 0 ] = (char)((lwID) >> 24); - lwIDStr[ 1 ] = (char)((lwID) >> 16); - lwIDStr[ 2 ] = (char)((lwID) >> 8); - lwIDStr[ 3 ] = (char)((lwID)); + lwIDStr[ 0 ] = (char)( ( lwID ) >> 24 ); + lwIDStr[ 1 ] = (char)( ( lwID ) >> 16 ); + lwIDStr[ 2 ] = (char)( ( lwID ) >> 8 ); + lwIDStr[ 3 ] = (char)( ( lwID ) ); lwIDStr[ 4 ] = '\0'; return lwIDStr; } /* -_lwo_canload() -validates a LightWave Object model file. btw, i use the -preceding underscore cause it's a static func referenced -by one structure only. -*/ -static int _lwo_canload( PM_PARAMS_CANLOAD ) -{ + _lwo_canload() + validates a LightWave Object model file. btw, i use the + preceding underscore cause it's a static func referenced + by one structure only. + */ +static int _lwo_canload( PM_PARAMS_CANLOAD ){ picoMemStream_t *s; unsigned int failID = 0; int failpos = -1; @@ -80,8 +77,7 @@ static int _lwo_canload( PM_PARAMS_CANLOAD ) /* create a new pico memorystream */ s = _pico_new_memstream( (const picoByte_t *)buffer, bufSize ); - if (s == NULL) - { + if ( s == NULL ) { return PICO_PMV_ERROR_MEMORY; } @@ -93,36 +89,35 @@ static int _lwo_canload( PM_PARAMS_CANLOAD ) } /* -_lwo_load() -loads a LightWave Object model file. -*/ -static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) -{ - picoMemStream_t *s; - unsigned int failID = 0; - int failpos = -1; - lwObject *obj; - lwSurface *surface; - lwLayer *layer; - lwPoint *pt; - lwPolygon *pol; - lwPolVert *v; - lwVMapPt *vm; - char name[ 256 ]; - int i, j, k, numverts; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - int defaultSTAxis[ 2 ]; - picoVec2_t defaultXYZtoSTScale; + _lwo_load() + loads a LightWave Object model file. + */ +static picoModel_t *_lwo_load( PM_PARAMS_LOAD ){ + picoMemStream_t *s; + unsigned int failID = 0; + int failpos = -1; + lwObject *obj; + lwSurface *surface; + lwLayer *layer; + lwPoint *pt; + lwPolygon *pol; + lwPolVert *v; + lwVMapPt *vm; + char name[ 256 ]; + int i, j, k, numverts; + + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + + int defaultSTAxis[ 2 ]; + picoVec2_t defaultXYZtoSTScale; picoVertexCombinationHash_t **hashTable; - picoVertexCombinationHash_t *vertexCombinationHash; + picoVertexCombinationHash_t *vertexCombinationHash; #ifdef DEBUG_PM_LWO clock_t load_start, load_finish, convert_start, convert_finish; @@ -132,16 +127,14 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) #endif /* do frame check */ - if( frameNum < 0 || frameNum >= 1 ) - { + if ( frameNum < 0 || frameNum >= 1 ) { _pico_printf( PICO_ERROR, "Invalid or out-of-range LWO frame specified" ); return NULL; } /* create a new pico memorystream */ s = _pico_new_memstream( (const picoByte_t *)buffer, bufSize ); - if (s == NULL) - { + if ( s == NULL ) { return NULL; } @@ -149,24 +142,23 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) _pico_free_memstream( s ); - if( !obj ) { + if ( !obj ) { _pico_printf( PICO_ERROR, "Couldn't load LWO file, failed on ID '%s', position %d", lwo_lwIDToStr( failID ), failpos ); return NULL; } #ifdef DEBUG_PM_LWO convert_start = load_finish = clock(); - load_elapsed = (double)(load_finish - load_start) / CLOCKS_PER_SEC; + load_elapsed = (double)( load_finish - load_start ) / CLOCKS_PER_SEC; #endif /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - + pico model creation + ------------------------------------------------- */ + /* create a new pico model */ picoModel = PicoNewModel(); - if (picoModel == NULL) - { + if ( picoModel == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); return NULL; } @@ -181,8 +173,7 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) layer = &obj->layer[0]; /* warn the user that other layers are discarded */ - if (obj->nlayers > 1) - { + if ( obj->nlayers > 1 ) { _pico_printf( PICO_WARNING, "LWO loader discards any geometry data not in Layer 1 (%d layers found)", obj->nlayers ); } @@ -190,25 +181,23 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) normal[ 0 ] = normal[ 1 ] = normal[ 2 ] = 0.f; /* setup default st map */ - st[ 0 ] = st[ 1 ] = 0.f; /* st[0] holds max, st[1] holds max par one */ + st[ 0 ] = st[ 1 ] = 0.f; /* st[0] holds max, st[1] holds max par one */ defaultSTAxis[ 0 ] = 0; defaultSTAxis[ 1 ] = 1; - for( i = 0; i < 3; i++ ) + for ( i = 0; i < 3; i++ ) { float min = layer->bbox[ i ]; float max = layer->bbox[ i + 3 ]; float size = max - min; - - if (size > st[ 0 ]) - { + + if ( size > st[ 0 ] ) { defaultSTAxis[ 1 ] = defaultSTAxis[ 0 ]; defaultSTAxis[ 0 ] = i; st[ 1 ] = st[ 0 ]; st[ 0 ] = size; } - else if (size > st[ 1 ]) - { + else if ( size > st[ 1 ] ) { defaultSTAxis[ 1 ] = i; st[ 1 ] = size; } @@ -218,12 +207,11 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) /* LWO surfaces become pico surfaces */ surface = obj->surf; - while (surface) + while ( surface ) { /* allocate new pico surface */ picoSurface = PicoNewSurface( picoModel ); - if (picoSurface == NULL) - { + if ( picoSurface == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); PicoFreeModel( picoModel ); lwFreeObject( obj ); @@ -238,8 +226,7 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) /* create new pico shader */ picoShader = PicoNewShader( picoModel ); - if (picoShader == NULL) - { + if ( picoShader == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); PicoFreeModel( picoModel ); lwFreeObject( obj ); @@ -247,7 +234,7 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) } /* detox and set shader name */ - strncpy( name, surface->name, sizeof(name) ); + strncpy( name, surface->name, sizeof( name ) ); _pico_first_token( name ); _pico_setfext( name, "" ); _pico_unixify( name ); @@ -261,35 +248,33 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) hashTable = PicoNewVertexCombinationHashTable(); - if (hashTable == NULL) - { + if ( hashTable == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate hash table" ); PicoFreeModel( picoModel ); lwFreeObject( obj ); return NULL; } - for( i = 0, pol = layer->polygon.pol; i < layer->polygon.count; i++, pol++ ) + for ( i = 0, pol = layer->polygon.pol; i < layer->polygon.count; i++, pol++ ) { /* does this polygon belong to this surface? */ - if (pol->surf != surface) + if ( pol->surf != surface ) { continue; + } /* we only support polygons of the FACE type */ - if (pol->type != ID_FACE) - { + if ( pol->type != ID_FACE ) { _pico_printf( PICO_WARNING, "LWO loader discarded a polygon because it's type != FACE (%s)", lwo_lwIDToStr( pol->type ) ); continue; } /* NOTE: LWO has support for non-convex polygons, do we want to store them as well? */ - if (pol->nverts != 3) - { + if ( pol->nverts != 3 ) { _pico_printf( PICO_WARNING, "LWO loader discarded a polygon because it has != 3 verts (%d)", pol->nverts ); continue; } - for( j = 0, v = pol->v; j < 3; j++, v++ ) + for ( j = 0, v = pol->v; j < 3; j++, v++ ) { pt = &layer->point.pt[ v->index ]; @@ -300,83 +285,76 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) /* doom3 lwo data doesn't seem to have smoothing-angle information */ #if 0 - if(surface->smooth <= 0) - { - /* use face normals */ - normal[ 0 ] = v->norm[ 0 ]; - normal[ 1 ] = v->norm[ 2 ]; - normal[ 2 ] = v->norm[ 1 ]; - } - else + if ( surface->smooth <= 0 ) { + /* use face normals */ + normal[ 0 ] = v->norm[ 0 ]; + normal[ 1 ] = v->norm[ 2 ]; + normal[ 2 ] = v->norm[ 1 ]; + } + else #endif - { - /* smooth normals later */ - normal[ 0 ] = 0; - normal[ 1 ] = 0; - normal[ 2 ] = 0; - } + { + /* smooth normals later */ + normal[ 0 ] = 0; + normal[ 1 ] = 0; + normal[ 2 ] = 0; + } st[ 0 ] = xyz[ defaultSTAxis[ 0 ] ] * defaultXYZtoSTScale[ 0 ]; st[ 1 ] = xyz[ defaultSTAxis[ 1 ] ] * defaultXYZtoSTScale[ 1 ]; - color[ 0 ] = (picoByte_t)(surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF); - color[ 1 ] = (picoByte_t)(surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF); - color[ 2 ] = (picoByte_t)(surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF); + color[ 0 ] = (picoByte_t)( surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); + color[ 1 ] = (picoByte_t)( surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); + color[ 2 ] = (picoByte_t)( surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); color[ 3 ] = 0xFF; /* set from points */ - for( k = 0, vm = pt->vm; k < pt->nvmaps; k++, vm++ ) + for ( k = 0, vm = pt->vm; k < pt->nvmaps; k++, vm++ ) { - if (vm->vmap->type == LWID_('T','X','U','V')) - { + if ( vm->vmap->type == LWID_( 'T','X','U','V' ) ) { /* set st coords */ st[ 0 ] = vm->vmap->val[ vm->index ][ 0 ]; st[ 1 ] = 1.f - vm->vmap->val[ vm->index ][ 1 ]; } - else if (vm->vmap->type == LWID_('R','G','B','A')) - { + else if ( vm->vmap->type == LWID_( 'R','G','B','A' ) ) { /* set rgba */ - color[ 0 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF); - color[ 1 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF); - color[ 2 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF); - color[ 3 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 3 ] * 0xFF); + color[ 0 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); + color[ 1 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); + color[ 2 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); + color[ 3 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 3 ] * 0xFF ); } } /* override with polygon data */ - for( k = 0, vm = v->vm; k < v->nvmaps; k++, vm++ ) + for ( k = 0, vm = v->vm; k < v->nvmaps; k++, vm++ ) { - if (vm->vmap->type == LWID_('T','X','U','V')) - { + if ( vm->vmap->type == LWID_( 'T','X','U','V' ) ) { /* set st coords */ st[ 0 ] = vm->vmap->val[ vm->index ][ 0 ]; st[ 1 ] = 1.f - vm->vmap->val[ vm->index ][ 1 ]; } - else if (vm->vmap->type == LWID_('R','G','B','A')) - { + else if ( vm->vmap->type == LWID_( 'R','G','B','A' ) ) { /* set rgba */ - color[ 0 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF); - color[ 1 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF); - color[ 2 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF); - color[ 3 ] = (picoByte_t)(vm->vmap->val[ vm->index ][ 3 ] * 0xFF); + color[ 0 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); + color[ 1 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); + color[ 2 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); + color[ 3 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 3 ] * 0xFF ); } } /* find vertex in this surface and if we can't find it there create it */ vertexCombinationHash = PicoFindVertexCombinationInHashTable( hashTable, xyz, normal, st, color ); - if (vertexCombinationHash) - { + if ( vertexCombinationHash ) { /* found an existing one */ - PicoSetSurfaceIndex( picoSurface, (i * 3 + j ), vertexCombinationHash->index ); + PicoSetSurfaceIndex( picoSurface, ( i * 3 + j ), vertexCombinationHash->index ); } else { /* it is a new one */ vertexCombinationHash = PicoAddVertexCombinationToHashTable( hashTable, xyz, normal, st, color, (picoIndex_t) numverts ); - if (vertexCombinationHash == NULL) - { + if ( vertexCombinationHash == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate hash bucket entry table" ); PicoFreeVertexCombinationHashTable( hashTable ); PicoFreeModel( picoModel ); @@ -397,7 +375,7 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) PicoSetSurfaceST( picoSurface, 0, numverts, st ); /* set index */ - PicoSetSurfaceIndex( picoSurface, (i * 3 + j ), (picoIndex_t) numverts ); + PicoSetSurfaceIndex( picoSurface, ( i * 3 + j ), (picoIndex_t) numverts ); numverts++; } @@ -407,7 +385,7 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) /* free the hashtable */ PicoFreeVertexCombinationHashTable( hashTable ); - /* get next surface */ + /* get next surface */ surface = surface->next; } @@ -419,8 +397,8 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) #ifdef DEBUG_PM_LWO load_finish = clock(); - load_elapsed += (double)(load_finish - load_start) / CLOCKS_PER_SEC; - convert_elapsed = (double)(convert_finish - convert_start) / CLOCKS_PER_SEC; + load_elapsed += (double)( load_finish - load_start ) / CLOCKS_PER_SEC; + convert_elapsed = (double)( convert_finish - convert_start ) / CLOCKS_PER_SEC; _pico_printf( PICO_NORMAL, "Loaded model in in %-.2f second(s) (loading: %-.2fs converting: %-.2fs)\n", load_elapsed + convert_elapsed, load_elapsed, convert_elapsed ); #endif @@ -431,15 +409,15 @@ static picoModel_t *_lwo_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleLWO = { - "1.0", /* module version string */ - "LightWave Object", /* module display name */ - "Arnout van Meer", /* author's name */ - "2003 Arnout van Meer, 2000 Ernie Wright", /* module copyright */ + "1.0", /* module version string */ + "LightWave Object", /* module display name */ + "Arnout van Meer", /* author's name */ + "2003 Arnout van Meer, 2000 Ernie Wright", /* module copyright */ { - "lwo", NULL, NULL, NULL /* default extensions to use */ + "lwo", NULL, NULL, NULL /* default extensions to use */ }, - _lwo_canload, /* validation routine */ - _lwo_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _lwo_canload, /* validation routine */ + _lwo_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_md2.c b/libs/picomodel/pm_md2.c index 19b5689c..28cf384e 100644 --- a/libs/picomodel/pm_md2.c +++ b/libs/picomodel/pm_md2.c @@ -1,40 +1,40 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ /* -Nurail: Used pm_md3.c (Randy Reddig) as a template. -*/ + Nurail: Used pm_md3.c (Randy Reddig) as a template. + */ /* marker */ @@ -45,16 +45,16 @@ Nurail: Used pm_md3.c (Randy Reddig) as a template. /* md2 model format */ -#define MD2_MAGIC "IDP2" -#define MD2_VERSION 8 +#define MD2_MAGIC "IDP2" +#define MD2_VERSION 8 -#define MD2_NUMVERTEXNORMALS 162 -#define MD2_MAX_SKINNAME 64 -#define MD2_MAX_TRIANGLES 4096 -#define MD2_MAX_VERTS 2048 -#define MD2_MAX_FRAMES 512 -#define MD2_MAX_MD2SKINS 32 -#define MD2_MAX_SKINNAME 64 +#define MD2_NUMVERTEXNORMALS 162 +#define MD2_MAX_SKINNAME 64 +#define MD2_MAX_TRIANGLES 4096 +#define MD2_MAX_VERTS 2048 +#define MD2_MAX_FRAMES 512 +#define MD2_MAX_MD2SKINS 32 +#define MD2_MAX_SKINNAME 64 #ifndef byte #define byte unsigned char @@ -62,43 +62,43 @@ Nurail: Used pm_md3.c (Randy Reddig) as a template. typedef struct index_LUT_s { - short Vert; - short ST; - struct index_LUT_s *next; + short Vert; + short ST; + struct index_LUT_s *next; } index_LUT_t; typedef struct index_DUP_LUT_s { - short ST; - short OldVert; + short ST; + short OldVert; } index_DUP_LUT_t; typedef struct { - short s; - short t; + short s; + short t; } md2St_t; typedef struct { - short index_xyz[3]; - short index_st[3]; + short index_xyz[3]; + short index_st[3]; } md2Triangle_t; typedef struct { - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; + byte v[3]; // scaled byte to fit in frame mins/maxs + byte lightnormalindex; } md2XyzNormal_t; typedef struct md2Frame_s { - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - md2XyzNormal_t verts[1]; // variable sized + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name from grabbing + md2XyzNormal_t verts[1]; // variable sized } md2Frame_t; @@ -106,218 +106,220 @@ md2Frame_t; /* md2 model file md2 structure */ typedef struct md2_s { - char magic[ 4 ]; - int version; - - int skinWidth; - int skinHeight; - int frameSize; - - int numSkins; - int numXYZ; - int numST; - int numTris; - int numGLCmds; - int numFrames; - - int ofsSkins; - int ofsST; - int ofsTris; - int ofsFrames; - int ofsGLCmds; - int ofsEnd; + char magic[ 4 ]; + int version; + + int skinWidth; + int skinHeight; + int frameSize; + + int numSkins; + int numXYZ; + int numST; + int numTris; + int numGLCmds; + int numFrames; + + int ofsSkins; + int ofsST; + int ofsTris; + int ofsFrames; + int ofsGLCmds; + int ofsEnd; } md2_t; -float md2_normals[ MD2_NUMVERTEXNORMALS ][ 3 ] = +float md2_normals[ MD2_NUMVERTEXNORMALS ][ 3 ] = { { -0.525731f, 0.000000f, 0.850651f }, - { -0.442863f, 0.238856f, 0.864188f }, - { -0.295242f, 0.000000f, 0.955423f }, - { -0.309017f, 0.500000f, 0.809017f }, - { -0.162460f, 0.262866f, 0.951056f }, + { -0.442863f, 0.238856f, 0.864188f }, + { -0.295242f, 0.000000f, 0.955423f }, + { -0.309017f, 0.500000f, 0.809017f }, + { -0.162460f, 0.262866f, 0.951056f }, { 0.000000f, 0.000000f, 1.000000f }, { 0.000000f, 0.850651f, 0.525731f }, { -0.147621f, 0.716567f, 0.681718f }, - { 0.147621f, 0.716567f, 0.681718f }, - { 0.000000f, 0.525731f, 0.850651f }, - { 0.309017f, 0.500000f, 0.809017f }, - { 0.525731f, 0.000000f, 0.850651f }, - { 0.295242f, 0.000000f, 0.955423f }, - { 0.442863f, 0.238856f, 0.864188f }, - { 0.162460f, 0.262866f, 0.951056f }, - { -0.681718f, 0.147621f, 0.716567f }, - { -0.809017f, 0.309017f, 0.500000f }, - { -0.587785f, 0.425325f, 0.688191f }, - { -0.850651f, 0.525731f, 0.000000f }, - { -0.864188f, 0.442863f, 0.238856f }, - { -0.716567f, 0.681718f, 0.147621f }, - { -0.688191f, 0.587785f, 0.425325f }, - { -0.500000f, 0.809017f, 0.309017f }, - { -0.238856f, 0.864188f, 0.442863f }, - { -0.425325f, 0.688191f, 0.587785f }, - { -0.716567f, 0.681718f, -0.147621f }, - { -0.500000f, 0.809017f, -0.309017f }, - { -0.525731f, 0.850651f, 0.000000f }, - { 0.000000f, 0.850651f, -0.525731f }, - { -0.238856f, 0.864188f, -0.442863f }, - { 0.000000f, 0.955423f, -0.295242f }, - { -0.262866f, 0.951056f, -0.162460f }, - { 0.000000f, 1.000000f, 0.000000f }, - { 0.000000f, 0.955423f, 0.295242f }, - { -0.262866f, 0.951056f, 0.162460f }, - { 0.238856f, 0.864188f, 0.442863f }, - { 0.262866f, 0.951056f, 0.162460f }, - { 0.500000f, 0.809017f, 0.309017f }, - { 0.238856f, 0.864188f, -0.442863f }, - { 0.262866f, 0.951056f, -0.162460f }, - { 0.500000f, 0.809017f, -0.309017f }, - { 0.850651f, 0.525731f, 0.000000f }, - { 0.716567f, 0.681718f, 0.147621f }, - { 0.716567f, 0.681718f, -0.147621f }, - { 0.525731f, 0.850651f, 0.000000f }, - { 0.425325f, 0.688191f, 0.587785f }, - { 0.864188f, 0.442863f, 0.238856f }, - { 0.688191f, 0.587785f, 0.425325f }, - { 0.809017f, 0.309017f, 0.500000f }, - { 0.681718f, 0.147621f, 0.716567f }, - { 0.587785f, 0.425325f, 0.688191f }, - { 0.955423f, 0.295242f, 0.000000f }, - { 1.000000f, 0.000000f, 0.000000f }, - { 0.951056f, 0.162460f, 0.262866f }, - { 0.850651f, -0.525731f, 0.000000f }, - { 0.955423f, -0.295242f, 0.000000f }, - { 0.864188f, -0.442863f, 0.238856f }, - { 0.951056f, -0.162460f, 0.262866f }, - { 0.809017f, -0.309017f, 0.500000f }, - { 0.681718f, -0.147621f, 0.716567f }, - { 0.850651f, 0.000000f, 0.525731f }, - { 0.864188f, 0.442863f, -0.238856f }, - { 0.809017f, 0.309017f, -0.500000f }, - { 0.951056f, 0.162460f, -0.262866f }, - { 0.525731f, 0.000000f, -0.850651f }, - { 0.681718f, 0.147621f, -0.716567f }, - { 0.681718f, -0.147621f, -0.716567f }, - { 0.850651f, 0.000000f, -0.525731f }, - { 0.809017f, -0.309017f, -0.500000f }, - { 0.864188f, -0.442863f, -0.238856f }, - { 0.951056f, -0.162460f, -0.262866f }, - { 0.147621f, 0.716567f, -0.681718f }, - { 0.309017f, 0.500000f, -0.809017f }, - { 0.425325f, 0.688191f, -0.587785f }, - { 0.442863f, 0.238856f, -0.864188f }, - { 0.587785f, 0.425325f, -0.688191f }, - { 0.688191f, 0.587785f, -0.425325f }, - { -0.147621f, 0.716567f, -0.681718f }, - { -0.309017f, 0.500000f, -0.809017f }, - { 0.000000f, 0.525731f, -0.850651f }, - { -0.525731f, 0.000000f, -0.850651f }, - { -0.442863f, 0.238856f, -0.864188f }, - { -0.295242f, 0.000000f, -0.955423f }, - { -0.162460f, 0.262866f, -0.951056f }, - { 0.000000f, 0.000000f, -1.000000f }, - { 0.295242f, 0.000000f, -0.955423f }, - { 0.162460f, 0.262866f, -0.951056f }, - { -0.442863f, -0.238856f, -0.864188f }, - { -0.309017f, -0.500000f, -0.809017f }, - { -0.162460f, -0.262866f, -0.951056f }, - { 0.000000f, -0.850651f, -0.525731f }, - { -0.147621f, -0.716567f, -0.681718f }, - { 0.147621f, -0.716567f, -0.681718f }, - { 0.000000f, -0.525731f, -0.850651f }, - { 0.309017f, -0.500000f, -0.809017f }, - { 0.442863f, -0.238856f, -0.864188f }, - { 0.162460f, -0.262866f, -0.951056f }, - { 0.238856f, -0.864188f, -0.442863f }, - { 0.500000f, -0.809017f, -0.309017f }, - { 0.425325f, -0.688191f, -0.587785f }, - { 0.716567f, -0.681718f, -0.147621f }, - { 0.688191f, -0.587785f, -0.425325f }, - { 0.587785f, -0.425325f, -0.688191f }, - { 0.000000f, -0.955423f, -0.295242f }, - { 0.000000f, -1.000000f, 0.000000f }, - { 0.262866f, -0.951056f, -0.162460f }, - { 0.000000f, -0.850651f, 0.525731f }, - { 0.000000f, -0.955423f, 0.295242f }, - { 0.238856f, -0.864188f, 0.442863f }, - { 0.262866f, -0.951056f, 0.162460f }, - { 0.500000f, -0.809017f, 0.309017f }, - { 0.716567f, -0.681718f, 0.147621f }, - { 0.525731f, -0.850651f, 0.000000f }, - { -0.238856f, -0.864188f, -0.442863f }, - { -0.500000f, -0.809017f, -0.309017f }, - { -0.262866f, -0.951056f, -0.162460f }, - { -0.850651f, -0.525731f, 0.000000f }, - { -0.716567f, -0.681718f, -0.147621f }, - { -0.716567f, -0.681718f, 0.147621f }, - { -0.525731f, -0.850651f, 0.000000f }, - { -0.500000f, -0.809017f, 0.309017f }, - { -0.238856f, -0.864188f, 0.442863f }, - { -0.262866f, -0.951056f, 0.162460f }, - { -0.864188f, -0.442863f, 0.238856f }, - { -0.809017f, -0.309017f, 0.500000f }, - { -0.688191f, -0.587785f, 0.425325f }, - { -0.681718f, -0.147621f, 0.716567f }, - { -0.442863f, -0.238856f, 0.864188f }, - { -0.587785f, -0.425325f, 0.688191f }, - { -0.309017f, -0.500000f, 0.809017f }, - { -0.147621f, -0.716567f, 0.681718f }, - { -0.425325f, -0.688191f, 0.587785f }, - { -0.162460f, -0.262866f, 0.951056f }, - { 0.442863f, -0.238856f, 0.864188f }, - { 0.162460f, -0.262866f, 0.951056f }, - { 0.309017f, -0.500000f, 0.809017f }, - { 0.147621f, -0.716567f, 0.681718f }, - { 0.000000f, -0.525731f, 0.850651f }, - { 0.425325f, -0.688191f, 0.587785f }, - { 0.587785f, -0.425325f, 0.688191f }, - { 0.688191f, -0.587785f, 0.425325f }, - { -0.955423f, 0.295242f, 0.000000f }, - { -0.951056f, 0.162460f, 0.262866f }, - { -1.000000f, 0.000000f, 0.000000f }, - { -0.850651f, 0.000000f, 0.525731f }, - { -0.955423f, -0.295242f, 0.000000f }, - { -0.951056f, -0.162460f, 0.262866f }, - { -0.864188f, 0.442863f, -0.238856f }, - { -0.951056f, 0.162460f, -0.262866f }, - { -0.809017f, 0.309017f, -0.500000f }, + { 0.147621f, 0.716567f, 0.681718f }, + { 0.000000f, 0.525731f, 0.850651f }, + { 0.309017f, 0.500000f, 0.809017f }, + { 0.525731f, 0.000000f, 0.850651f }, + { 0.295242f, 0.000000f, 0.955423f }, + { 0.442863f, 0.238856f, 0.864188f }, + { 0.162460f, 0.262866f, 0.951056f }, + { -0.681718f, 0.147621f, 0.716567f }, + { -0.809017f, 0.309017f, 0.500000f }, + { -0.587785f, 0.425325f, 0.688191f }, + { -0.850651f, 0.525731f, 0.000000f }, + { -0.864188f, 0.442863f, 0.238856f }, + { -0.716567f, 0.681718f, 0.147621f }, + { -0.688191f, 0.587785f, 0.425325f }, + { -0.500000f, 0.809017f, 0.309017f }, + { -0.238856f, 0.864188f, 0.442863f }, + { -0.425325f, 0.688191f, 0.587785f }, + { -0.716567f, 0.681718f, -0.147621f }, + { -0.500000f, 0.809017f, -0.309017f }, + { -0.525731f, 0.850651f, 0.000000f }, + { 0.000000f, 0.850651f, -0.525731f }, + { -0.238856f, 0.864188f, -0.442863f }, + { 0.000000f, 0.955423f, -0.295242f }, + { -0.262866f, 0.951056f, -0.162460f }, + { 0.000000f, 1.000000f, 0.000000f }, + { 0.000000f, 0.955423f, 0.295242f }, + { -0.262866f, 0.951056f, 0.162460f }, + { 0.238856f, 0.864188f, 0.442863f }, + { 0.262866f, 0.951056f, 0.162460f }, + { 0.500000f, 0.809017f, 0.309017f }, + { 0.238856f, 0.864188f, -0.442863f }, + { 0.262866f, 0.951056f, -0.162460f }, + { 0.500000f, 0.809017f, -0.309017f }, + { 0.850651f, 0.525731f, 0.000000f }, + { 0.716567f, 0.681718f, 0.147621f }, + { 0.716567f, 0.681718f, -0.147621f }, + { 0.525731f, 0.850651f, 0.000000f }, + { 0.425325f, 0.688191f, 0.587785f }, + { 0.864188f, 0.442863f, 0.238856f }, + { 0.688191f, 0.587785f, 0.425325f }, + { 0.809017f, 0.309017f, 0.500000f }, + { 0.681718f, 0.147621f, 0.716567f }, + { 0.587785f, 0.425325f, 0.688191f }, + { 0.955423f, 0.295242f, 0.000000f }, + { 1.000000f, 0.000000f, 0.000000f }, + { 0.951056f, 0.162460f, 0.262866f }, + { 0.850651f, -0.525731f, 0.000000f }, + { 0.955423f, -0.295242f, 0.000000f }, + { 0.864188f, -0.442863f, 0.238856f }, + { 0.951056f, -0.162460f, 0.262866f }, + { 0.809017f, -0.309017f, 0.500000f }, + { 0.681718f, -0.147621f, 0.716567f }, + { 0.850651f, 0.000000f, 0.525731f }, + { 0.864188f, 0.442863f, -0.238856f }, + { 0.809017f, 0.309017f, -0.500000f }, + { 0.951056f, 0.162460f, -0.262866f }, + { 0.525731f, 0.000000f, -0.850651f }, + { 0.681718f, 0.147621f, -0.716567f }, + { 0.681718f, -0.147621f, -0.716567f }, + { 0.850651f, 0.000000f, -0.525731f }, + { 0.809017f, -0.309017f, -0.500000f }, + { 0.864188f, -0.442863f, -0.238856f }, + { 0.951056f, -0.162460f, -0.262866f }, + { 0.147621f, 0.716567f, -0.681718f }, + { 0.309017f, 0.500000f, -0.809017f }, + { 0.425325f, 0.688191f, -0.587785f }, + { 0.442863f, 0.238856f, -0.864188f }, + { 0.587785f, 0.425325f, -0.688191f }, + { 0.688191f, 0.587785f, -0.425325f }, + { -0.147621f, 0.716567f, -0.681718f }, + { -0.309017f, 0.500000f, -0.809017f }, + { 0.000000f, 0.525731f, -0.850651f }, + { -0.525731f, 0.000000f, -0.850651f }, + { -0.442863f, 0.238856f, -0.864188f }, + { -0.295242f, 0.000000f, -0.955423f }, + { -0.162460f, 0.262866f, -0.951056f }, + { 0.000000f, 0.000000f, -1.000000f }, + { 0.295242f, 0.000000f, -0.955423f }, + { 0.162460f, 0.262866f, -0.951056f }, + { -0.442863f, -0.238856f, -0.864188f }, + { -0.309017f, -0.500000f, -0.809017f }, + { -0.162460f, -0.262866f, -0.951056f }, + { 0.000000f, -0.850651f, -0.525731f }, + { -0.147621f, -0.716567f, -0.681718f }, + { 0.147621f, -0.716567f, -0.681718f }, + { 0.000000f, -0.525731f, -0.850651f }, + { 0.309017f, -0.500000f, -0.809017f }, + { 0.442863f, -0.238856f, -0.864188f }, + { 0.162460f, -0.262866f, -0.951056f }, + { 0.238856f, -0.864188f, -0.442863f }, + { 0.500000f, -0.809017f, -0.309017f }, + { 0.425325f, -0.688191f, -0.587785f }, + { 0.716567f, -0.681718f, -0.147621f }, + { 0.688191f, -0.587785f, -0.425325f }, + { 0.587785f, -0.425325f, -0.688191f }, + { 0.000000f, -0.955423f, -0.295242f }, + { 0.000000f, -1.000000f, 0.000000f }, + { 0.262866f, -0.951056f, -0.162460f }, + { 0.000000f, -0.850651f, 0.525731f }, + { 0.000000f, -0.955423f, 0.295242f }, + { 0.238856f, -0.864188f, 0.442863f }, + { 0.262866f, -0.951056f, 0.162460f }, + { 0.500000f, -0.809017f, 0.309017f }, + { 0.716567f, -0.681718f, 0.147621f }, + { 0.525731f, -0.850651f, 0.000000f }, + { -0.238856f, -0.864188f, -0.442863f }, + { -0.500000f, -0.809017f, -0.309017f }, + { -0.262866f, -0.951056f, -0.162460f }, + { -0.850651f, -0.525731f, 0.000000f }, + { -0.716567f, -0.681718f, -0.147621f }, + { -0.716567f, -0.681718f, 0.147621f }, + { -0.525731f, -0.850651f, 0.000000f }, + { -0.500000f, -0.809017f, 0.309017f }, + { -0.238856f, -0.864188f, 0.442863f }, + { -0.262866f, -0.951056f, 0.162460f }, + { -0.864188f, -0.442863f, 0.238856f }, + { -0.809017f, -0.309017f, 0.500000f }, + { -0.688191f, -0.587785f, 0.425325f }, + { -0.681718f, -0.147621f, 0.716567f }, + { -0.442863f, -0.238856f, 0.864188f }, + { -0.587785f, -0.425325f, 0.688191f }, + { -0.309017f, -0.500000f, 0.809017f }, + { -0.147621f, -0.716567f, 0.681718f }, + { -0.425325f, -0.688191f, 0.587785f }, + { -0.162460f, -0.262866f, 0.951056f }, + { 0.442863f, -0.238856f, 0.864188f }, + { 0.162460f, -0.262866f, 0.951056f }, + { 0.309017f, -0.500000f, 0.809017f }, + { 0.147621f, -0.716567f, 0.681718f }, + { 0.000000f, -0.525731f, 0.850651f }, + { 0.425325f, -0.688191f, 0.587785f }, + { 0.587785f, -0.425325f, 0.688191f }, + { 0.688191f, -0.587785f, 0.425325f }, + { -0.955423f, 0.295242f, 0.000000f }, + { -0.951056f, 0.162460f, 0.262866f }, + { -1.000000f, 0.000000f, 0.000000f }, + { -0.850651f, 0.000000f, 0.525731f }, + { -0.955423f, -0.295242f, 0.000000f }, + { -0.951056f, -0.162460f, 0.262866f }, + { -0.864188f, 0.442863f, -0.238856f }, + { -0.951056f, 0.162460f, -0.262866f }, + { -0.809017f, 0.309017f, -0.500000f }, { -0.864188f, -0.442863f, -0.238856f }, - { -0.951056f, -0.162460f, -0.262866f }, - { -0.809017f, -0.309017f, -0.500000f }, - { -0.681718f, 0.147621f, -0.716567f }, - { -0.681718f, -0.147621f, -0.716567f }, - { -0.850651f, 0.000000f, -0.525731f }, - { -0.688191f, 0.587785f, -0.425325f }, - { -0.587785f, 0.425325f, -0.688191f }, - { -0.425325f, 0.688191f, -0.587785f }, - { -0.425325f, -0.688191f, -0.587785f }, - { -0.587785f, -0.425325f, -0.688191f }, - { -0.688191f, -0.587785f, -0.425325f }, + { -0.951056f, -0.162460f, -0.262866f }, + { -0.809017f, -0.309017f, -0.500000f }, + { -0.681718f, 0.147621f, -0.716567f }, + { -0.681718f, -0.147621f, -0.716567f }, + { -0.850651f, 0.000000f, -0.525731f }, + { -0.688191f, 0.587785f, -0.425325f }, + { -0.587785f, 0.425325f, -0.688191f }, + { -0.425325f, 0.688191f, -0.587785f }, + { -0.425325f, -0.688191f, -0.587785f }, + { -0.587785f, -0.425325f, -0.688191f }, + { -0.688191f, -0.587785f, -0.425325f }, }; // _md2_canload() -static int _md2_canload( PM_PARAMS_CANLOAD ) -{ - const md2_t *md2; +static int _md2_canload( PM_PARAMS_CANLOAD ){ + const md2_t *md2; /* sanity check */ - if( (size_t) bufSize < ( sizeof( *md2 ) * 2) ) + if ( (size_t) bufSize < ( sizeof( *md2 ) * 2 ) ) { return PICO_PMV_ERROR_SIZE; - + } + /* set as md2 */ md2 = (const md2_t*) buffer; - + /* check md2 magic */ - if( *((const int*) md2->magic) != *((const int*) MD2_MAGIC) ) + if ( *( (const int*) md2->magic ) != *( (const int*) MD2_MAGIC ) ) { return PICO_PMV_ERROR_IDENT; - + } + /* check md2 version */ - if( _pico_little_long( md2->version ) != MD2_VERSION ) + if ( _pico_little_long( md2->version ) != MD2_VERSION ) { return PICO_PMV_ERROR_VERSION; + } - /* file seems to be a valid md2 */ + /* file seems to be a valid md2 */ return PICO_PMV_OK; } @@ -326,43 +328,41 @@ static int _md2_canload( PM_PARAMS_CANLOAD ) // _md2_load() loads a quake2 md2 model file. -static picoModel_t *_md2_load( PM_PARAMS_LOAD ) -{ - int i, j, dups, dup_index; - index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; - index_DUP_LUT_t *p_index_LUT_DUPS; - md2Triangle_t *p_md2Triangle; - - char skinname[ MD2_MAX_SKINNAME ]; - md2_t *md2; - md2St_t *texCoord; - md2Frame_t *frame; - md2Triangle_t *triangle; - md2XyzNormal_t *vertex; +static picoModel_t *_md2_load( PM_PARAMS_LOAD ){ + int i, j, dups, dup_index; + index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; + index_DUP_LUT_t *p_index_LUT_DUPS; + md2Triangle_t *p_md2Triangle; + + char skinname[ MD2_MAX_SKINNAME ]; + md2_t *md2; + md2St_t *texCoord; + md2Frame_t *frame; + md2Triangle_t *triangle; + md2XyzNormal_t *vertex; picoByte_t *bb, *bb0; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + /* set as md2 */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - md2 = (md2_t*) bb; + bb0 = bb = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bb, buffer, bufSize ); + md2 = (md2_t*) bb; /* check ident and version */ - if( *((const int*) md2->magic) != *((const int*) MD2_MAGIC) || _pico_little_long( md2->version ) != MD2_VERSION ) - { + if ( *( (const int*) md2->magic ) != *( (const int*) MD2_MAGIC ) || _pico_little_long( md2->version ) != MD2_VERSION ) { /* not an md2 file (todo: set error) */ _pico_printf( PICO_ERROR, "%s is not an MD2 File!", fileName ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + // swap md2 md2->version = _pico_little_long( md2->version ); @@ -385,35 +385,33 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) md2->ofsEnd = _pico_little_long( md2->ofsEnd ); // do frame check - if( md2->numFrames < 1 ) - { + if ( md2->numFrames < 1 ) { _pico_printf( PICO_ERROR, "%s has 0 frames!", fileName ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - - if( frameNum < 0 || frameNum >= md2->numFrames ) - { + + if ( frameNum < 0 || frameNum >= md2->numFrames ) { _pico_printf( PICO_ERROR, "Invalid or out-of-range MD2 frame specified" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } // Setup Frame - frame = (md2Frame_t *) (bb + md2->ofsFrames + (sizeof(md2Frame_t) * frameNum)); + frame = (md2Frame_t *) ( bb + md2->ofsFrames + ( sizeof( md2Frame_t ) * frameNum ) ); // swap frame scale and translation - for( i = 0; i < 3; i++ ) + for ( i = 0; i < 3; i++ ) { frame->scale[ i ] = _pico_little_float( frame->scale[ i ] ); frame->translate[ i ] = _pico_little_float( frame->translate[ i ] ); } // swap triangles - triangle = (md2Triangle_t *) ((picoByte_t *) (bb + md2->ofsTris) ); - for( i = 0; i < md2->numTris; i++, triangle++ ) + triangle = (md2Triangle_t *) ( (picoByte_t *) ( bb + md2->ofsTris ) ); + for ( i = 0; i < md2->numTris; i++, triangle++ ) { - for( j = 0; j < 3; j++ ) + for ( j = 0; j < 3; j++ ) { triangle->index_xyz[ j ] = _pico_little_short( triangle->index_xyz[ j ] ); triangle->index_st[ j ] = _pico_little_short( triangle->index_st[ j ] ); @@ -421,18 +419,18 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) } // swap st coords - texCoord = (md2St_t*) ((picoByte_t *) (bb + md2->ofsST) ); - for( i = 0; i < md2->numST; i++, texCoord++ ) + texCoord = (md2St_t*) ( (picoByte_t *) ( bb + md2->ofsST ) ); + for ( i = 0; i < md2->numST; i++, texCoord++ ) { texCoord->s = _pico_little_short( texCoord->s ); texCoord->t = _pico_little_short( texCoord->t ); } // set Skin Name - strncpy(skinname, (const char *) (bb + md2->ofsSkins), MD2_MAX_SKINNAME ); + strncpy( skinname, (const char *) ( bb + md2->ofsSkins ), MD2_MAX_SKINNAME ); // Print out md2 values - _pico_printf(PICO_VERBOSE,"Skins: %d Verts: %d STs: %d Triangles: %d Frames: %d\nSkin Name \"%s\"\n", md2->numSkins, md2->numXYZ, md2->numST, md2->numTris, md2->numFrames, &skinname ); + _pico_printf( PICO_VERBOSE,"Skins: %d Verts: %d STs: %d Triangles: %d Frames: %d\nSkin Name \"%s\"\n", md2->numSkins, md2->numXYZ, md2->numST, md2->numTris, md2->numFrames, &skinname ); // detox Skin name _pico_setfext( skinname, "" ); @@ -440,10 +438,9 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) /* create new pico model */ picoModel = PicoNewModel(); - if( picoModel == NULL ) - { + if ( picoModel == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -455,11 +452,10 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) // allocate new pico surface picoSurface = PicoNewSurface( picoModel ); - if( picoSurface == NULL ) - { + if ( picoSurface == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -467,11 +463,10 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); PicoSetSurfaceName( picoSurface, frame->name ); picoShader = PicoNewShader( picoModel ); - if( picoShader == NULL ) - { + if ( picoShader == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } @@ -481,8 +476,8 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) PicoSetSurfaceShader( picoSurface, picoShader ); // Init LUT for Verts - p_index_LUT = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t) * md2->numXYZ); - for(i=0; inumXYZ; i++) + p_index_LUT = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) * md2->numXYZ ); + for ( i = 0; i < md2->numXYZ; i++ ) { p_index_LUT[i].Vert = -1; p_index_LUT[i].ST = -1; @@ -491,22 +486,25 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) // Fill in Look Up Table, and allocate/fill Linked List from vert array as needed for dup STs per Vert. dups = 0; - for(i=0; inumTris; i++) + for ( i = 0; i < md2->numTris; i++ ) { - p_md2Triangle = (md2Triangle_t *) ( bb + md2->ofsTris + (sizeof(md2Triangle_t)*i)); - for(j=0; j<3; j++) + p_md2Triangle = (md2Triangle_t *) ( bb + md2->ofsTris + ( sizeof( md2Triangle_t ) * i ) ); + for ( j = 0; j < 3; j++ ) { - if (p_index_LUT[p_md2Triangle->index_xyz[j]].ST == -1) // No Main Entry + if ( p_index_LUT[p_md2Triangle->index_xyz[j]].ST == -1 ) { // No Main Entry p_index_LUT[p_md2Triangle->index_xyz[j]].ST = p_md2Triangle->index_st[j]; + } - else if (p_md2Triangle->index_st[j] == p_index_LUT[p_md2Triangle->index_xyz[j]].ST ) // Equal to Main Entry + else if ( p_md2Triangle->index_st[j] == p_index_LUT[p_md2Triangle->index_xyz[j]].ST ) { // Equal to Main Entry continue; + } - else if ( (p_index_LUT[p_md2Triangle->index_xyz[j]].next == NULL) ) // Not equal to Main entry, and no LL entry - { // Add first entry of LL from Main - p_index_LUT2 = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t)); - if (p_index_LUT2 == NULL) - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n"); + else if ( ( p_index_LUT[p_md2Triangle->index_xyz[j]].next == NULL ) ) { // Not equal to Main entry, and no LL entry + // Add first entry of LL from Main + p_index_LUT2 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); + if ( p_index_LUT2 == NULL ) { + _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); + } p_index_LUT[p_md2Triangle->index_xyz[j]].next = (index_LUT_t *)p_index_LUT2; p_index_LUT2->Vert = dups; p_index_LUT2->ST = p_md2Triangle->index_st[j]; @@ -517,25 +515,24 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) else // Try to find in LL from Main Entry { p_index_LUT3 = p_index_LUT2 = p_index_LUT[p_md2Triangle->index_xyz[j]].next; - while ( (p_index_LUT2 != NULL) && (p_md2Triangle->index_xyz[j] != p_index_LUT2->Vert) ) // Walk down LL + while ( ( p_index_LUT2 != NULL ) && ( p_md2Triangle->index_xyz[j] != p_index_LUT2->Vert ) ) // Walk down LL { p_index_LUT3 = p_index_LUT2; p_index_LUT2 = p_index_LUT2->next; } p_index_LUT2 = p_index_LUT3; - if ( p_md2Triangle->index_st[j] == p_index_LUT2->ST ) // Found it - { + if ( p_md2Triangle->index_st[j] == p_index_LUT2->ST ) { // Found it p_md2Triangle->index_xyz[j] = p_index_LUT2->Vert + md2->numXYZ; // Make change in Tri hunk continue; } - if ( p_index_LUT2->next == NULL) // Didn't find it. Add entry to LL. - { + if ( p_index_LUT2->next == NULL ) { // Didn't find it. Add entry to LL. // Add the Entry - p_index_LUT3 = (index_LUT_t *)_pico_alloc(sizeof(index_LUT_t)); - if (p_index_LUT3 == NULL) - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n"); + p_index_LUT3 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); + if ( p_index_LUT3 == NULL ) { + _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); + } p_index_LUT2->next = (index_LUT_t *)p_index_LUT3; p_index_LUT3->Vert = p_md2Triangle->index_xyz[j]; p_index_LUT3->ST = p_md2Triangle->index_st[j]; @@ -548,15 +545,16 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) } // malloc and build array for Dup STs - p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc(sizeof(index_DUP_LUT_t) * dups); - if (p_index_LUT_DUPS == NULL) - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n"); + p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc( sizeof( index_DUP_LUT_t ) * dups ); + if ( p_index_LUT_DUPS == NULL ) { + _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); + } dup_index = 0; - for(i=0; inumXYZ; i++) + for ( i = 0; i < md2->numXYZ; i++ ) { p_index_LUT2 = p_index_LUT[i].next; - while (p_index_LUT2 != NULL) + while ( p_index_LUT2 != NULL ) { p_index_LUT_DUPS[p_index_LUT2->Vert].OldVert = i; p_index_LUT_DUPS[p_index_LUT2->Vert].ST = p_index_LUT2->ST; @@ -566,57 +564,56 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) } // Build Picomodel - triangle = (md2Triangle_t *) ((picoByte_t *) (bb + md2->ofsTris) ); - texCoord = (md2St_t*) ((picoByte_t *) (bb + md2->ofsST) ); - vertex = (md2XyzNormal_t*) ((picoByte_t*) (frame->verts) ); - for( j = 0; j < md2->numTris; j++, triangle++ ) + triangle = (md2Triangle_t *) ( (picoByte_t *) ( bb + md2->ofsTris ) ); + texCoord = (md2St_t*) ( (picoByte_t *) ( bb + md2->ofsST ) ); + vertex = (md2XyzNormal_t*) ( (picoByte_t*) ( frame->verts ) ); + for ( j = 0; j < md2->numTris; j++, triangle++ ) { - PicoSetSurfaceIndex( picoSurface, j*3 , triangle->index_xyz[0] ); - PicoSetSurfaceIndex( picoSurface, j*3+1 , triangle->index_xyz[1] ); - PicoSetSurfaceIndex( picoSurface, j*3+2 , triangle->index_xyz[2] ); + PicoSetSurfaceIndex( picoSurface, j * 3, triangle->index_xyz[0] ); + PicoSetSurfaceIndex( picoSurface, j * 3 + 1, triangle->index_xyz[1] ); + PicoSetSurfaceIndex( picoSurface, j * 3 + 2, triangle->index_xyz[2] ); } - for(i=0; i< md2->numXYZ; i++, vertex++) + for ( i = 0; i < md2->numXYZ; i++, vertex++ ) { /* set vertex origin */ xyz[ 0 ] = vertex->v[0] * frame->scale[0] + frame->translate[0]; xyz[ 1 ] = vertex->v[1] * frame->scale[1] + frame->translate[1]; xyz[ 2 ] = vertex->v[2] * frame->scale[2] + frame->translate[2]; - PicoSetSurfaceXYZ( picoSurface, i , xyz ); + PicoSetSurfaceXYZ( picoSurface, i, xyz ); /* set normal */ normal[ 0 ] = md2_normals[vertex->lightnormalindex][0]; normal[ 1 ] = md2_normals[vertex->lightnormalindex][1]; normal[ 2 ] = md2_normals[vertex->lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i , normal ); + PicoSetSurfaceNormal( picoSurface, i, normal ); /* set st coords */ - st[ 0 ] = ((texCoord[p_index_LUT[i].ST].s) / ((float)md2->skinWidth)); - st[ 1 ] = (texCoord[p_index_LUT[i].ST].t / ((float)md2->skinHeight)); - PicoSetSurfaceST( picoSurface, 0, i , st ); + st[ 0 ] = ( ( texCoord[p_index_LUT[i].ST].s ) / ( (float)md2->skinWidth ) ); + st[ 1 ] = ( texCoord[p_index_LUT[i].ST].t / ( (float)md2->skinHeight ) ); + PicoSetSurfaceST( picoSurface, 0, i, st ); } - if (dups) - { - for(i=0; iverts[j].v[0] * frame->scale[0] + frame->translate[0]; xyz[ 1 ] = frame->verts[j].v[1] * frame->scale[1] + frame->translate[1]; xyz[ 2 ] = frame->verts[j].v[2] * frame->scale[2] + frame->translate[2]; - PicoSetSurfaceXYZ( picoSurface, i + md2->numXYZ , xyz ); + PicoSetSurfaceXYZ( picoSurface, i + md2->numXYZ, xyz ); /* set normal */ normal[ 0 ] = md2_normals[frame->verts[j].lightnormalindex][0]; normal[ 1 ] = md2_normals[frame->verts[j].lightnormalindex][1]; normal[ 2 ] = md2_normals[frame->verts[j].lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i + md2->numXYZ , normal ); + PicoSetSurfaceNormal( picoSurface, i + md2->numXYZ, normal ); /* set st coords */ - st[ 0 ] = ((texCoord[p_index_LUT_DUPS[i].ST].s) / ((float)md2->skinWidth)); - st[ 1 ] = (texCoord[p_index_LUT_DUPS[i].ST].t / ((float)md2->skinHeight)); - PicoSetSurfaceST( picoSurface, 0, i + md2->numXYZ , st ); + st[ 0 ] = ( ( texCoord[p_index_LUT_DUPS[i].ST].s ) / ( (float)md2->skinWidth ) ); + st[ 1 ] = ( texCoord[p_index_LUT_DUPS[i].ST].t / ( (float)md2->skinHeight ) ); + PicoSetSurfaceST( picoSurface, 0, i + md2->numXYZ, st ); } } @@ -624,29 +621,29 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) PicoSetSurfaceColor( picoSurface, 0, 0, color ); // Free up malloc'ed LL entries - for(i=0; inumXYZ; i++) + for ( i = 0; i < md2->numXYZ; i++ ) { - if(p_index_LUT[i].next != NULL) - { + if ( p_index_LUT[i].next != NULL ) { p_index_LUT2 = p_index_LUT[i].next; do { p_index_LUT3 = p_index_LUT2->next; - _pico_free(p_index_LUT2); + _pico_free( p_index_LUT2 ); p_index_LUT2 = p_index_LUT3; dups--; - } while (p_index_LUT2 != NULL); + } while ( p_index_LUT2 != NULL ); } } - if (dups) - _pico_printf(PICO_WARNING, " Not all LL mallocs freed\n"); + if ( dups ) { + _pico_printf( PICO_WARNING, " Not all LL mallocs freed\n" ); + } // Free malloc'ed LUTs - _pico_free(p_index_LUT); - _pico_free(p_index_LUT_DUPS); + _pico_free( p_index_LUT ); + _pico_free( p_index_LUT_DUPS ); /* return the new pico model */ - _pico_free(bb0); + _pico_free( bb0 ); return picoModel; } @@ -656,15 +653,15 @@ static picoModel_t *_md2_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleMD2 = { - "0.875", /* module version string */ - "Quake 2 MD2", /* module display name */ - "Nurail", /* author's name */ - "2003 Nurail", /* module copyright */ + "0.875", /* module version string */ + "Quake 2 MD2", /* module display name */ + "Nurail", /* author's name */ + "2003 Nurail", /* module copyright */ { - "md2", NULL, NULL, NULL /* default extensions to use */ + "md2", NULL, NULL, NULL /* default extensions to use */ }, - _md2_canload, /* validation routine */ - _md2_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _md2_canload, /* validation routine */ + _md2_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_md3.c b/libs/picomodel/pm_md3.c index b22704da..f014c437 100644 --- a/libs/picomodel/pm_md3.c +++ b/libs/picomodel/pm_md3.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -45,72 +45,72 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* md3 model format */ -#define MD3_MAGIC "IDP3" -#define MD3_VERSION 15 +#define MD3_MAGIC "IDP3" +#define MD3_VERSION 15 /* md3 vertex scale */ -#define MD3_SCALE (1.0f / 64.0f) +#define MD3_SCALE ( 1.0f / 64.0f ) /* md3 model frame information */ typedef struct md3Frame_s { - float bounds[ 2 ][ 3 ]; - float localOrigin[ 3 ]; - float radius; - char creator[ 16 ]; + float bounds[ 2 ][ 3 ]; + float localOrigin[ 3 ]; + float radius; + char creator[ 16 ]; } md3Frame_t; /* md3 model tag information */ typedef struct md3Tag_s { - char name[ 64 ]; - float origin[ 3 ]; - float axis[ 3 ][ 3 ]; + char name[ 64 ]; + float origin[ 3 ]; + float axis[ 3 ][ 3 ]; } md3Tag_t; /* md3 surface md3 (one object mesh) */ typedef struct md3Surface_s { - char magic[ 4 ]; - char name[ 64 ]; /* polyset name */ - int flags; - int numFrames; /* all model surfaces should have the same */ - int numShaders; /* all model surfaces should have the same */ - int numVerts; - int numTriangles; - int ofsTriangles; - int ofsShaders; /* offset from start of md3Surface_t */ - int ofsSt; /* texture coords are common for all frames */ - int ofsVertexes; /* numVerts * numFrames */ - int ofsEnd; /* next surface follows */ + char magic[ 4 ]; + char name[ 64 ]; /* polyset name */ + int flags; + int numFrames; /* all model surfaces should have the same */ + int numShaders; /* all model surfaces should have the same */ + int numVerts; + int numTriangles; + int ofsTriangles; + int ofsShaders; /* offset from start of md3Surface_t */ + int ofsSt; /* texture coords are common for all frames */ + int ofsVertexes; /* numVerts * numFrames */ + int ofsEnd; /* next surface follows */ } md3Surface_t; typedef struct md3Shader_s { - char name[ 64 ]; - int shaderIndex; /* for ingame use */ + char name[ 64 ]; + int shaderIndex; /* for ingame use */ } md3Shader_t; typedef struct md3Triangle_s { - int indexes[ 3 ]; + int indexes[ 3 ]; } md3Triangle_t; typedef struct md3TexCoord_s { - float st[ 2 ]; + float st[ 2 ]; } md3TexCoord_t; typedef struct md3Vertex_s { - short xyz[ 3 ]; - short normal; + short xyz[ 3 ]; + short normal; } md3Vertex_t; @@ -118,18 +118,18 @@ md3Vertex_t; /* md3 model file md3 structure */ typedef struct md3_s { - char magic[ 4 ]; /* MD3_MAGIC */ - int version; - char name[ 64 ]; /* model name */ - int flags; - int numFrames; - int numTags; - int numSurfaces; - int numSkins; /* number of skins for the mesh */ - int ofsFrames; /* offset for first frame */ - int ofsTags; /* numFrames * numTags */ - int ofsSurfaces; /* first surface, others follow */ - int ofsEnd; /* end of file */ + char magic[ 4 ]; /* MD3_MAGIC */ + int version; + char name[ 64 ]; /* model name */ + int flags; + int numFrames; + int numTags; + int numSurfaces; + int numSkins; /* number of skins for the mesh */ + int ofsFrames; /* offset for first frame */ + int ofsTags; /* numFrames * numTags */ + int ofsSurfaces; /* first surface, others follow */ + int ofsEnd; /* end of file */ } md3_t; @@ -137,32 +137,34 @@ md3_t; /* -_md3_canload() -validates a quake3 arena md3 model file. btw, i use the -preceding underscore cause it's a static func referenced -by one structure only. -*/ + _md3_canload() + validates a quake3 arena md3 model file. btw, i use the + preceding underscore cause it's a static func referenced + by one structure only. + */ + +static int _md3_canload( PM_PARAMS_CANLOAD ){ + const md3_t *md3; -static int _md3_canload( PM_PARAMS_CANLOAD ) -{ - const md3_t *md3; - /* sanity check */ - if( (size_t) bufSize < ( sizeof( *md3 ) * 2) ) + if ( (size_t) bufSize < ( sizeof( *md3 ) * 2 ) ) { return PICO_PMV_ERROR_SIZE; - + } + /* set as md3 */ - md3 = (const md3_t*) buffer; - + md3 = (const md3_t*) buffer; + /* check md3 magic */ - if( *((const int*) md3->magic) != *((const int*) MD3_MAGIC) ) + if ( *( (const int*) md3->magic ) != *( (const int*) MD3_MAGIC ) ) { return PICO_PMV_ERROR_IDENT; - + } + /* check md3 version */ - if( _pico_little_long( md3->version ) != MD3_VERSION ) + if ( _pico_little_long( md3->version ) != MD3_VERSION ) { return PICO_PMV_ERROR_VERSION; - + } + /* file seems to be a valid md3 */ return PICO_PMV_OK; } @@ -170,49 +172,47 @@ static int _md3_canload( PM_PARAMS_CANLOAD ) /* -_md3_load() -loads a quake3 arena md3 model file. -*/ + _md3_load() + loads a quake3 arena md3 model file. + */ + +static picoModel_t *_md3_load( PM_PARAMS_LOAD ){ + int i, j; + picoByte_t *bb, *bb0; + md3_t *md3; + md3Surface_t *surface; + md3Shader_t *shader; + md3TexCoord_t *texCoord; + md3Frame_t *frame; + md3Triangle_t *triangle; + md3Vertex_t *vertex; + double lat, lng; + + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + -static picoModel_t *_md3_load( PM_PARAMS_LOAD ) -{ - int i, j; - picoByte_t *bb, *bb0; - md3_t *md3; - md3Surface_t *surface; - md3Shader_t *shader; - md3TexCoord_t *texCoord; - md3Frame_t *frame; - md3Triangle_t *triangle; - md3Vertex_t *vertex; - double lat, lng; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - /* ------------------------------------------------- - md3 loading - ------------------------------------------------- */ + md3 loading + ------------------------------------------------- */ /* set as md3 */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - md3 = (md3_t*) bb; - + bb0 = bb = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bb, buffer, bufSize ); + md3 = (md3_t*) bb; + /* check ident and version */ - if( *((int*) md3->magic) != *((int*) MD3_MAGIC) || _pico_little_long( md3->version ) != MD3_VERSION ) - { + if ( *( (int*) md3->magic ) != *( (int*) MD3_MAGIC ) || _pico_little_long( md3->version ) != MD3_VERSION ) { /* not an md3 file (todo: set error) */ - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* swap md3; sea: swaps fixed */ md3->version = _pico_little_long( md3->version ); md3->numFrames = _pico_little_long( md3->numFrames ); @@ -223,38 +223,36 @@ static picoModel_t *_md3_load( PM_PARAMS_LOAD ) md3->ofsTags = _pico_little_long( md3->ofsTags ); md3->ofsSurfaces = _pico_little_long( md3->ofsSurfaces ); md3->ofsEnd = _pico_little_long( md3->ofsEnd ); - + /* do frame check */ - if( md3->numFrames < 1 ) - { + if ( md3->numFrames < 1 ) { _pico_printf( PICO_ERROR, "MD3 with 0 frames" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - - if( frameNum < 0 || frameNum >= md3->numFrames ) - { + + if ( frameNum < 0 || frameNum >= md3->numFrames ) { _pico_printf( PICO_ERROR, "Invalid or out-of-range MD3 frame specified" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* swap frames */ - frame = (md3Frame_t*) (bb + md3->ofsFrames ); - for( i = 0; i < md3->numFrames; i++, frame++ ) + frame = (md3Frame_t*) ( bb + md3->ofsFrames ); + for ( i = 0; i < md3->numFrames; i++, frame++ ) { frame->radius = _pico_little_float( frame->radius ); - for( j = 0; j < 3; j++ ) + for ( j = 0; j < 3; j++ ) { frame->bounds[ 0 ][ j ] = _pico_little_float( frame->bounds[ 0 ][ j ] ); frame->bounds[ 1 ][ j ] = _pico_little_float( frame->bounds[ 1 ][ j ] ); frame->localOrigin[ j ] = _pico_little_float( frame->localOrigin[ j ] ); } } - + /* swap surfaces */ - surface = (md3Surface_t*) (bb + md3->ofsSurfaces); - for( i = 0; i < md3->numSurfaces; i++ ) + surface = (md3Surface_t*) ( bb + md3->ofsSurfaces ); + for ( i = 0; i < md3->numSurfaces; i++ ) { /* swap surface md3; sea: swaps fixed */ surface->flags = _pico_little_long( surface->flags ); @@ -267,132 +265,129 @@ static picoModel_t *_md3_load( PM_PARAMS_LOAD ) surface->ofsSt = _pico_little_long( surface->ofsSt ); surface->ofsVertexes = _pico_little_long( surface->ofsVertexes ); surface->ofsEnd = _pico_little_long( surface->ofsEnd ); - + /* swap triangles */ - triangle = (md3Triangle_t*) ((picoByte_t*) surface + surface->ofsTriangles); - for( j = 0; j < surface->numTriangles; j++, triangle++ ) + triangle = (md3Triangle_t*) ( (picoByte_t*) surface + surface->ofsTriangles ); + for ( j = 0; j < surface->numTriangles; j++, triangle++ ) { /* sea: swaps fixed */ triangle->indexes[ 0 ] = _pico_little_long( triangle->indexes[ 0 ] ); triangle->indexes[ 1 ] = _pico_little_long( triangle->indexes[ 1 ] ); triangle->indexes[ 2 ] = _pico_little_long( triangle->indexes[ 2 ] ); } - + /* swap st coords */ - texCoord = (md3TexCoord_t*) ((picoByte_t*) surface + surface->ofsSt); - for( j = 0; j < surface->numVerts; j++, texCoord++ ) + texCoord = (md3TexCoord_t*) ( (picoByte_t*) surface + surface->ofsSt ); + for ( j = 0; j < surface->numVerts; j++, texCoord++ ) { texCoord->st[ 0 ] = _pico_little_float( texCoord->st[ 0 ] ); texCoord->st[ 1 ] = _pico_little_float( texCoord->st[ 1 ] ); } - + /* swap xyz/normals */ - vertex = (md3Vertex_t*) ((picoByte_t*) surface + surface->ofsVertexes); - for( j = 0; j < (surface->numVerts * surface->numFrames); j++, vertex++) + vertex = (md3Vertex_t*) ( (picoByte_t*) surface + surface->ofsVertexes ); + for ( j = 0; j < ( surface->numVerts * surface->numFrames ); j++, vertex++ ) { vertex->xyz[ 0 ] = _pico_little_short( vertex->xyz[ 0 ] ); vertex->xyz[ 1 ] = _pico_little_short( vertex->xyz[ 1 ] ); vertex->xyz[ 2 ] = _pico_little_short( vertex->xyz[ 2 ] ); - vertex->normal = _pico_little_short( vertex->normal ); + vertex->normal = _pico_little_short( vertex->normal ); } - + /* get next surface */ - surface = (md3Surface_t*) ((picoByte_t*) surface + surface->ofsEnd); + surface = (md3Surface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); } - + /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - + pico model creation + ------------------------------------------------- */ + /* create new pico model */ picoModel = PicoNewModel(); - if( picoModel == NULL ) - { + if ( picoModel == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* do model setup */ PicoSetModelFrameNum( picoModel, frameNum ); PicoSetModelNumFrames( picoModel, md3->numFrames ); /* sea */ PicoSetModelName( picoModel, fileName ); PicoSetModelFileName( picoModel, fileName ); - + /* md3 surfaces become picomodel surfaces */ - surface = (md3Surface_t*) (bb + md3->ofsSurfaces); - + surface = (md3Surface_t*) ( bb + md3->ofsSurfaces ); + /* run through md3 surfaces */ - for( i = 0; i < md3->numSurfaces; i++ ) + for ( i = 0; i < md3->numSurfaces; i++ ) { /* allocate new pico surface */ picoSurface = PicoNewSurface( picoModel ); - if( picoSurface == NULL ) - { + if ( picoSurface == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); PicoFreeModel( picoModel ); /* sea */ - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* md3 model surfaces are all triangle meshes */ PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - + /* set surface name */ PicoSetSurfaceName( picoSurface, surface->name ); - + /* create new pico shader -sea */ picoShader = PicoNewShader( picoModel ); - if( picoShader == NULL ) - { + if ( picoShader == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* detox and set shader name */ - shader = (md3Shader_t*) ((picoByte_t*) surface + surface->ofsShaders); + shader = (md3Shader_t*) ( (picoByte_t*) surface + surface->ofsShaders ); _pico_setfext( shader->name, "" ); _pico_unixify( shader->name ); PicoSetShaderName( picoShader, shader->name ); - + /* associate current surface with newly created shader */ PicoSetSurfaceShader( picoSurface, picoShader ); - + /* copy indexes */ - triangle = (md3Triangle_t *) ((picoByte_t*) surface + surface->ofsTriangles); - - for( j = 0; j < surface->numTriangles; j++, triangle++ ) + triangle = (md3Triangle_t *) ( (picoByte_t*) surface + surface->ofsTriangles ); + + for ( j = 0; j < surface->numTriangles; j++, triangle++ ) { - PicoSetSurfaceIndex( picoSurface, (j * 3 + 0), (picoIndex_t) triangle->indexes[ 0 ] ); - PicoSetSurfaceIndex( picoSurface, (j * 3 + 1), (picoIndex_t) triangle->indexes[ 1 ] ); - PicoSetSurfaceIndex( picoSurface, (j * 3 + 2), (picoIndex_t) triangle->indexes[ 2 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 0 ), (picoIndex_t) triangle->indexes[ 0 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 1 ), (picoIndex_t) triangle->indexes[ 1 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 2 ), (picoIndex_t) triangle->indexes[ 2 ] ); } - + /* copy vertexes */ - texCoord = (md3TexCoord_t*) ((picoByte_t *) surface + surface->ofsSt); - vertex = (md3Vertex_t*) ((picoByte_t*) surface + surface->ofsVertexes + surface->numVerts * frameNum * sizeof( md3Vertex_t ) ); + texCoord = (md3TexCoord_t*) ( (picoByte_t *) surface + surface->ofsSt ); + vertex = (md3Vertex_t*) ( (picoByte_t*) surface + surface->ofsVertexes + surface->numVerts * frameNum * sizeof( md3Vertex_t ) ); _pico_set_color( color, 255, 255, 255, 255 ); - - for( j = 0; j < surface->numVerts; j++, texCoord++, vertex++ ) + + for ( j = 0; j < surface->numVerts; j++, texCoord++, vertex++ ) { /* set vertex origin */ xyz[ 0 ] = MD3_SCALE * vertex->xyz[ 0 ]; xyz[ 1 ] = MD3_SCALE * vertex->xyz[ 1 ]; xyz[ 2 ] = MD3_SCALE * vertex->xyz[ 2 ]; PicoSetSurfaceXYZ( picoSurface, j, xyz ); - + /* decode lat/lng normal to 3 float normal */ - lat = (float) ((vertex->normal >> 8) & 0xff); - lng = (float) (vertex->normal & 0xff); + lat = (float) ( ( vertex->normal >> 8 ) & 0xff ); + lng = (float) ( vertex->normal & 0xff ); lat *= PICO_PI / 128; lng *= PICO_PI / 128; normal[ 0 ] = (picoVec_t) cos( lat ) * (picoVec_t) sin( lng ); normal[ 1 ] = (picoVec_t) sin( lat ) * (picoVec_t) sin( lng ); normal[ 2 ] = (picoVec_t) cos( lng ); PicoSetSurfaceNormal( picoSurface, j, normal ); - + /* set st coords */ st[ 0 ] = texCoord->st[ 0 ]; st[ 1 ] = texCoord->st[ 1 ]; @@ -401,13 +396,13 @@ static picoModel_t *_md3_load( PM_PARAMS_LOAD ) /* set color */ PicoSetSurfaceColor( picoSurface, 0, j, color ); } - + /* get next surface */ - surface = (md3Surface_t*) ((picoByte_t*) surface + surface->ofsEnd); + surface = (md3Surface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); } - + /* return the new pico model */ - _pico_free(bb0); + _pico_free( bb0 ); return picoModel; } @@ -416,15 +411,15 @@ static picoModel_t *_md3_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleMD3 = { - "1.3", /* module version string */ - "Quake 3 Arena", /* module display name */ - "Randy Reddig", /* author's name */ - "2002 Randy Reddig", /* module copyright */ + "1.3", /* module version string */ + "Quake 3 Arena", /* module display name */ + "Randy Reddig", /* author's name */ + "2002 Randy Reddig", /* module copyright */ { - "md3", NULL, NULL, NULL /* default extensions to use */ + "md3", NULL, NULL, NULL /* default extensions to use */ }, - _md3_canload, /* validation routine */ - _md3_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _md3_canload, /* validation routine */ + _md3_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_mdc.c b/libs/picomodel/pm_mdc.c index d1243b2c..7e898ff1 100644 --- a/libs/picomodel/pm_mdc.c +++ b/libs/picomodel/pm_mdc.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -43,13 +43,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "picointernal.h" /* mdc model format */ -#define MDC_MAGIC "IDPC" -#define MDC_VERSION 2 +#define MDC_MAGIC "IDPC" +#define MDC_VERSION 2 /* mdc vertex scale */ -#define MDC_SCALE (1.0f / 64.0f) -#define MDC_MAX_OFS 127.0f -#define MDC_DIST_SCALE 0.05f +#define MDC_SCALE ( 1.0f / 64.0f ) +#define MDC_MAX_OFS 127.0f +#define MDC_DIST_SCALE 0.05f /* mdc decoding normal table */ double mdcNormals[ 256 ][ 3 ] = @@ -315,73 +315,73 @@ double mdcNormals[ 256 ][ 3 ] = /* mdc model frame information */ typedef struct mdcFrame_s { - float bounds[ 2 ][ 3 ]; - float localOrigin[ 3 ]; - float radius; - char creator[ 16 ]; + float bounds[ 2 ][ 3 ]; + float localOrigin[ 3 ]; + float radius; + char creator[ 16 ]; } mdcFrame_t; /* mdc model tag information */ typedef struct mdcTag_s { - short xyz[3]; - short angles[3]; + short xyz[3]; + short angles[3]; } mdcTag_t; /* mdc surface mdc (one object mesh) */ typedef struct mdcSurface_s { - char magic[ 4 ]; - char name[ 64 ]; /* polyset name */ - int flags; - int numCompFrames; /* all surfaces in a model should have the same */ - int numBaseFrames; /* ditto */ - int numShaders; /* all model surfaces should have the same */ - int numVerts; - int numTriangles; - int ofsTriangles; - int ofsShaders; /* offset from start of mdcSurface_t */ - int ofsSt; /* texture coords are common for all frames */ - int ofsXyzNormals; /* numVerts * numBaseFrames */ - int ofsXyzCompressed; /* numVerts * numCompFrames */ - - int ofsFrameBaseFrames; /* numFrames */ - int ofsFrameCompFrames; /* numFrames */ - int ofsEnd; /* next surface follows */ + char magic[ 4 ]; + char name[ 64 ]; /* polyset name */ + int flags; + int numCompFrames; /* all surfaces in a model should have the same */ + int numBaseFrames; /* ditto */ + int numShaders; /* all model surfaces should have the same */ + int numVerts; + int numTriangles; + int ofsTriangles; + int ofsShaders; /* offset from start of mdcSurface_t */ + int ofsSt; /* texture coords are common for all frames */ + int ofsXyzNormals; /* numVerts * numBaseFrames */ + int ofsXyzCompressed; /* numVerts * numCompFrames */ + + int ofsFrameBaseFrames; /* numFrames */ + int ofsFrameCompFrames; /* numFrames */ + int ofsEnd; /* next surface follows */ } mdcSurface_t; typedef struct mdcShader_s { - char name[ 64 ]; - int shaderIndex; /* for ingame use */ + char name[ 64 ]; + int shaderIndex; /* for ingame use */ } mdcShader_t; typedef struct mdcTriangle_s { - int indexes[ 3 ]; + int indexes[ 3 ]; } mdcTriangle_t; typedef struct mdcTexCoord_s { - float st[ 2 ]; + float st[ 2 ]; } mdcTexCoord_t; typedef struct mdcVertex_s { - short xyz[ 3 ]; - short normal; + short xyz[ 3 ]; + short normal; } mdcVertex_t; typedef struct mdcXyzCompressed_s { - unsigned int ofsVec; /* offset direction from the last base frame */ + unsigned int ofsVec; /* offset direction from the last base frame */ } mdcXyzCompressed_t; @@ -389,19 +389,19 @@ mdcXyzCompressed_t; /* mdc model file mdc structure */ typedef struct mdc_s { - char magic[ 4 ]; /* MDC_MAGIC */ - int version; - char name[ 64 ]; /* model name */ - int flags; - int numFrames; - int numTags; - int numSurfaces; - int numSkins; /* number of skins for the mesh */ - int ofsFrames; /* offset for first frame */ - int ofsTagNames; /* numTags */ - int ofsTags; /* numFrames * numTags */ - int ofsSurfaces; /* first surface, others follow */ - int ofsEnd; /* end of file */ + char magic[ 4 ]; /* MDC_MAGIC */ + int version; + char name[ 64 ]; /* model name */ + int flags; + int numFrames; + int numTags; + int numSurfaces; + int numSkins; /* number of skins for the mesh */ + int ofsFrames; /* offset for first frame */ + int ofsTagNames; /* numTags */ + int ofsTags; /* numFrames * numTags */ + int ofsSurfaces; /* first surface, others follow */ + int ofsEnd; /* end of file */ } mdc_t; @@ -409,32 +409,34 @@ mdc_t; /* -_mdc_canload() -validates a Return to Castle Wolfenstein model file. btw, i use the -preceding underscore cause it's a static func referenced -by one structure only. -*/ + _mdc_canload() + validates a Return to Castle Wolfenstein model file. btw, i use the + preceding underscore cause it's a static func referenced + by one structure only. + */ + +static int _mdc_canload( PM_PARAMS_CANLOAD ){ + const mdc_t *mdc; + -static int _mdc_canload( PM_PARAMS_CANLOAD ) -{ - const mdc_t *mdc; - - /* sanity check */ - if( (size_t) bufSize < ( sizeof( *mdc ) * 2) ) + if ( (size_t) bufSize < ( sizeof( *mdc ) * 2 ) ) { return PICO_PMV_ERROR_SIZE; - + } + /* set as mdc */ - mdc = (const mdc_t*) buffer; - + mdc = (const mdc_t*) buffer; + /* check mdc magic */ - if( *((const int*) mdc->magic) != *((const int*) MDC_MAGIC) ) + if ( *( (const int*) mdc->magic ) != *( (const int*) MDC_MAGIC ) ) { return PICO_PMV_ERROR_IDENT; - + } + /* check mdc version */ - if( _pico_little_long( mdc->version ) != MDC_VERSION ) + if ( _pico_little_long( mdc->version ) != MDC_VERSION ) { return PICO_PMV_ERROR_VERSION; - + } + /* file seems to be a valid mdc */ return PICO_PMV_OK; } @@ -442,51 +444,49 @@ static int _mdc_canload( PM_PARAMS_CANLOAD ) /* -_mdc_load() -loads a Return to Castle Wolfenstein mdc model file. -*/ + _mdc_load() + loads a Return to Castle Wolfenstein mdc model file. + */ + +static picoModel_t *_mdc_load( PM_PARAMS_LOAD ){ + int i, j; + picoByte_t *bb, *bb0; + mdc_t *mdc; + mdcSurface_t *surface; + mdcShader_t *shader; + mdcTexCoord_t *texCoord; + mdcFrame_t *frame; + mdcTriangle_t *triangle; + mdcVertex_t *vertex; + mdcXyzCompressed_t *vertexComp = NULL; + short *mdcShort, *mdcCompVert = NULL; + double lat, lng; + + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + -static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) -{ - int i, j; - picoByte_t *bb, *bb0; - mdc_t *mdc; - mdcSurface_t *surface; - mdcShader_t *shader; - mdcTexCoord_t *texCoord; - mdcFrame_t *frame; - mdcTriangle_t *triangle; - mdcVertex_t *vertex; - mdcXyzCompressed_t *vertexComp = NULL; - short *mdcShort, *mdcCompVert = NULL; - double lat, lng; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - /* ------------------------------------------------- - mdc loading - ------------------------------------------------- */ + mdc loading + ------------------------------------------------- */ /* set as mdc */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - mdc = (mdc_t*) bb; - + bb0 = bb = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bb, buffer, bufSize ); + mdc = (mdc_t*) bb; + /* check ident and version */ - if( *((int*) mdc->magic) != *((int*) MDC_MAGIC) || _pico_little_long( mdc->version ) != MDC_VERSION ) - { + if ( *( (int*) mdc->magic ) != *( (int*) MDC_MAGIC ) || _pico_little_long( mdc->version ) != MDC_VERSION ) { /* not an mdc file (todo: set error) */ - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* swap mdc */ mdc->version = _pico_little_long( mdc->version ); mdc->numFrames = _pico_little_long( mdc->numFrames ); @@ -498,38 +498,36 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) mdc->ofsTagNames = _pico_little_long( mdc->ofsTagNames ); mdc->ofsSurfaces = _pico_little_long( mdc->ofsSurfaces ); mdc->ofsEnd = _pico_little_long( mdc->ofsEnd ); - + /* do frame check */ - if( mdc->numFrames < 1 ) - { + if ( mdc->numFrames < 1 ) { _pico_printf( PICO_ERROR, "MDC with 0 frames" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - - if( frameNum < 0 || frameNum >= mdc->numFrames ) - { + + if ( frameNum < 0 || frameNum >= mdc->numFrames ) { _pico_printf( PICO_ERROR, "Invalid or out-of-range MDC frame specified" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* swap frames */ - frame = (mdcFrame_t*) (bb + mdc->ofsFrames ); - for( i = 0; i < mdc->numFrames; i++, frame++ ) + frame = (mdcFrame_t*) ( bb + mdc->ofsFrames ); + for ( i = 0; i < mdc->numFrames; i++, frame++ ) { frame->radius = _pico_little_float( frame->radius ); - for( j = 0; j < 3; j++ ) + for ( j = 0; j < 3; j++ ) { frame->bounds[ 0 ][ j ] = _pico_little_float( frame->bounds[ 0 ][ j ] ); frame->bounds[ 1 ][ j ] = _pico_little_float( frame->bounds[ 1 ][ j ] ); frame->localOrigin[ j ] = _pico_little_float( frame->localOrigin[ j ] ); } } - + /* swap surfaces */ - surface = (mdcSurface_t*) (bb + mdc->ofsSurfaces); - for( i = 0; i < mdc->numSurfaces; i++ ) + surface = (mdcSurface_t*) ( bb + mdc->ofsSurfaces ); + for ( i = 0; i < mdc->numSurfaces; i++ ) { /* swap surface mdc */ surface->flags = _pico_little_long( surface->flags ); @@ -546,142 +544,139 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) surface->ofsFrameBaseFrames = _pico_little_long( surface->ofsFrameBaseFrames ); surface->ofsFrameCompFrames = _pico_little_long( surface->ofsFrameCompFrames ); surface->ofsEnd = _pico_little_long( surface->ofsEnd ); - + /* swap triangles */ - triangle = (mdcTriangle_t*) ((picoByte_t*) surface + surface->ofsTriangles); - for( j = 0; j < surface->numTriangles; j++, triangle++ ) + triangle = (mdcTriangle_t*) ( (picoByte_t*) surface + surface->ofsTriangles ); + for ( j = 0; j < surface->numTriangles; j++, triangle++ ) { /* sea: swaps fixed */ triangle->indexes[ 0 ] = _pico_little_long( triangle->indexes[ 0 ] ); triangle->indexes[ 1 ] = _pico_little_long( triangle->indexes[ 1 ] ); triangle->indexes[ 2 ] = _pico_little_long( triangle->indexes[ 2 ] ); } - + /* swap st coords */ - texCoord = (mdcTexCoord_t*) ((picoByte_t*) surface + surface->ofsSt); - for( j = 0; j < surface->numVerts; j++, texCoord++ ) + texCoord = (mdcTexCoord_t*) ( (picoByte_t*) surface + surface->ofsSt ); + for ( j = 0; j < surface->numVerts; j++, texCoord++ ) { texCoord->st[ 0 ] = _pico_little_float( texCoord->st[ 0 ] ); texCoord->st[ 1 ] = _pico_little_float( texCoord->st[ 1 ] ); } - + /* swap xyz/normals */ - vertex = (mdcVertex_t*) ((picoByte_t*) surface + surface->ofsXyzNormals); - for( j = 0; j < (surface->numVerts * surface->numBaseFrames); j++, vertex++) + vertex = (mdcVertex_t*) ( (picoByte_t*) surface + surface->ofsXyzNormals ); + for ( j = 0; j < ( surface->numVerts * surface->numBaseFrames ); j++, vertex++ ) { vertex->xyz[ 0 ] = _pico_little_short( vertex->xyz[ 0 ] ); vertex->xyz[ 1 ] = _pico_little_short( vertex->xyz[ 1 ] ); vertex->xyz[ 2 ] = _pico_little_short( vertex->xyz[ 2 ] ); - vertex->normal = _pico_little_short( vertex->normal ); + vertex->normal = _pico_little_short( vertex->normal ); } /* swap xyz/compressed */ - vertexComp = (mdcXyzCompressed_t*) ((picoByte_t*) surface + surface->ofsXyzCompressed); - for( j = 0; j < (surface->numVerts * surface->numCompFrames); j++, vertexComp++) + vertexComp = (mdcXyzCompressed_t*) ( (picoByte_t*) surface + surface->ofsXyzCompressed ); + for ( j = 0; j < ( surface->numVerts * surface->numCompFrames ); j++, vertexComp++ ) { - vertexComp->ofsVec = _pico_little_long( vertexComp->ofsVec ); + vertexComp->ofsVec = _pico_little_long( vertexComp->ofsVec ); } /* swap base frames */ - mdcShort = (short *) ((picoByte_t*) surface + surface->ofsFrameBaseFrames); - for( j = 0; j < mdc->numFrames; j++, mdcShort++) + mdcShort = (short *) ( (picoByte_t*) surface + surface->ofsFrameBaseFrames ); + for ( j = 0; j < mdc->numFrames; j++, mdcShort++ ) { - *mdcShort = _pico_little_short( *mdcShort ); + *mdcShort = _pico_little_short( *mdcShort ); } /* swap compressed frames */ - mdcShort = (short *) ((picoByte_t*) surface + surface->ofsFrameCompFrames); - for( j = 0; j < mdc->numFrames; j++, mdcShort++) + mdcShort = (short *) ( (picoByte_t*) surface + surface->ofsFrameCompFrames ); + for ( j = 0; j < mdc->numFrames; j++, mdcShort++ ) { - *mdcShort = _pico_little_short( *mdcShort ); + *mdcShort = _pico_little_short( *mdcShort ); } - + /* get next surface */ - surface = (mdcSurface_t*) ((picoByte_t*) surface + surface->ofsEnd); + surface = (mdcSurface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); } - + /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - + pico model creation + ------------------------------------------------- */ + /* create new pico model */ picoModel = PicoNewModel(); - if( picoModel == NULL ) - { + if ( picoModel == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* do model setup */ PicoSetModelFrameNum( picoModel, frameNum ); PicoSetModelNumFrames( picoModel, mdc->numFrames ); /* sea */ PicoSetModelName( picoModel, fileName ); PicoSetModelFileName( picoModel, fileName ); - + /* mdc surfaces become picomodel surfaces */ - surface = (mdcSurface_t*) (bb + mdc->ofsSurfaces); - + surface = (mdcSurface_t*) ( bb + mdc->ofsSurfaces ); + /* run through mdc surfaces */ - for( i = 0; i < mdc->numSurfaces; i++ ) + for ( i = 0; i < mdc->numSurfaces; i++ ) { /* allocate new pico surface */ picoSurface = PicoNewSurface( picoModel ); - if( picoSurface == NULL ) - { + if ( picoSurface == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); PicoFreeModel( picoModel ); /* sea */ - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* mdc model surfaces are all triangle meshes */ PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - + /* set surface name */ PicoSetSurfaceName( picoSurface, surface->name ); - + /* create new pico shader -sea */ picoShader = PicoNewShader( picoModel ); - if( picoShader == NULL ) - { + if ( picoShader == NULL ) { _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); PicoFreeModel( picoModel ); - _pico_free(bb0); + _pico_free( bb0 ); return NULL; } - + /* detox and set shader name */ - shader = (mdcShader_t*) ((picoByte_t*) surface + surface->ofsShaders); + shader = (mdcShader_t*) ( (picoByte_t*) surface + surface->ofsShaders ); _pico_setfext( shader->name, "" ); _pico_unixify( shader->name ); PicoSetShaderName( picoShader, shader->name ); - + /* associate current surface with newly created shader */ PicoSetSurfaceShader( picoSurface, picoShader ); - + /* copy indexes */ - triangle = (mdcTriangle_t *) ((picoByte_t*) surface + surface->ofsTriangles); - - for( j = 0; j < surface->numTriangles; j++, triangle++ ) + triangle = (mdcTriangle_t *) ( (picoByte_t*) surface + surface->ofsTriangles ); + + for ( j = 0; j < surface->numTriangles; j++, triangle++ ) { - PicoSetSurfaceIndex( picoSurface, (j * 3 + 0), (picoIndex_t) triangle->indexes[ 0 ] ); - PicoSetSurfaceIndex( picoSurface, (j * 3 + 1), (picoIndex_t) triangle->indexes[ 1 ] ); - PicoSetSurfaceIndex( picoSurface, (j * 3 + 2), (picoIndex_t) triangle->indexes[ 2 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 0 ), (picoIndex_t) triangle->indexes[ 0 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 1 ), (picoIndex_t) triangle->indexes[ 1 ] ); + PicoSetSurfaceIndex( picoSurface, ( j * 3 + 2 ), (picoIndex_t) triangle->indexes[ 2 ] ); } - + /* copy vertexes */ - texCoord = (mdcTexCoord_t*) ((picoByte_t *) surface + surface->ofsSt); - mdcShort = (short *) ((picoByte_t *) surface + surface->ofsXyzNormals) + ((int)*((short *) ((picoByte_t *) surface + surface->ofsFrameBaseFrames) + frameNum) * surface->numVerts * 4); - if( surface->numCompFrames > 0 ) - { - mdcCompVert = (short *) ((picoByte_t *) surface + surface->ofsFrameCompFrames) + frameNum; - if( *mdcCompVert >= 0 ) - vertexComp = (mdcXyzCompressed_t *) ((picoByte_t *) surface + surface->ofsXyzCompressed) + (*mdcCompVert * surface->numVerts); + texCoord = (mdcTexCoord_t*) ( (picoByte_t *) surface + surface->ofsSt ); + mdcShort = (short *) ( (picoByte_t *) surface + surface->ofsXyzNormals ) + ( (int)*( (short *) ( (picoByte_t *) surface + surface->ofsFrameBaseFrames ) + frameNum ) * surface->numVerts * 4 ); + if ( surface->numCompFrames > 0 ) { + mdcCompVert = (short *) ( (picoByte_t *) surface + surface->ofsFrameCompFrames ) + frameNum; + if ( *mdcCompVert >= 0 ) { + vertexComp = (mdcXyzCompressed_t *) ( (picoByte_t *) surface + surface->ofsXyzCompressed ) + ( *mdcCompVert * surface->numVerts ); + } } _pico_set_color( color, 255, 255, 255, 255 ); - - for( j = 0; j < surface->numVerts; j++, texCoord++, mdcShort+=4 ) + + for ( j = 0; j < surface->numVerts; j++, texCoord++, mdcShort += 4 ) { /* set vertex origin */ xyz[ 0 ] = MDC_SCALE * mdcShort[ 0 ]; @@ -689,27 +684,26 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) xyz[ 2 ] = MDC_SCALE * mdcShort[ 2 ]; /* add compressed ofsVec */ - if( surface->numCompFrames > 0 && *mdcCompVert >= 0 ) - { - xyz[ 0 ] += ((float) ((vertexComp->ofsVec) & 255) - MDC_MAX_OFS) * MDC_DIST_SCALE; - xyz[ 1 ] += ((float) ((vertexComp->ofsVec >> 8) & 255) - MDC_MAX_OFS) * MDC_DIST_SCALE; - xyz[ 2 ] += ((float) ((vertexComp->ofsVec >> 16) & 255) - MDC_MAX_OFS) * MDC_DIST_SCALE; + if ( surface->numCompFrames > 0 && *mdcCompVert >= 0 ) { + xyz[ 0 ] += ( (float) ( ( vertexComp->ofsVec ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; + xyz[ 1 ] += ( (float) ( ( vertexComp->ofsVec >> 8 ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; + xyz[ 2 ] += ( (float) ( ( vertexComp->ofsVec >> 16 ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; PicoSetSurfaceXYZ( picoSurface, j, xyz ); - normal[ 0 ] = (float) mdcNormals[ (vertexComp->ofsVec >> 24) ][ 0 ]; - normal[ 1 ] = (float) mdcNormals[ (vertexComp->ofsVec >> 24) ][ 1 ]; - normal[ 2 ] = (float) mdcNormals[ (vertexComp->ofsVec >> 24) ][ 2 ]; + normal[ 0 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 0 ]; + normal[ 1 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 1 ]; + normal[ 2 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 2 ]; PicoSetSurfaceNormal( picoSurface, j, normal ); vertexComp++; } else - { + { PicoSetSurfaceXYZ( picoSurface, j, xyz ); /* decode lat/lng normal to 3 float normal */ - lat = (float) ((*(mdcShort + 3) >> 8) & 0xff); - lng = (float) (*(mdcShort + 3) & 0xff); + lat = (float) ( ( *( mdcShort + 3 ) >> 8 ) & 0xff ); + lng = (float) ( *( mdcShort + 3 ) & 0xff ); lat *= PICO_PI / 128; lng *= PICO_PI / 128; normal[ 0 ] = (picoVec_t) cos( lat ) * (picoVec_t) sin( lng ); @@ -717,7 +711,7 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) normal[ 2 ] = (picoVec_t) cos( lng ); PicoSetSurfaceNormal( picoSurface, j, normal ); } - + /* set st coords */ st[ 0 ] = texCoord->st[ 0 ]; st[ 1 ] = texCoord->st[ 1 ]; @@ -726,13 +720,13 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) /* set color */ PicoSetSurfaceColor( picoSurface, 0, j, color ); } - + /* get next surface */ - surface = (mdcSurface_t*) ((picoByte_t*) surface + surface->ofsEnd); + surface = (mdcSurface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); } - + /* return the new pico model */ - _pico_free(bb0); + _pico_free( bb0 ); return picoModel; } @@ -741,15 +735,15 @@ static picoModel_t *_mdc_load( PM_PARAMS_LOAD ) /* pico file format module definition */ const picoModule_t picoModuleMDC = { - "1.3", /* module version string */ - "RtCW MDC", /* module display name */ - "Arnout van Meer", /* author's name */ - "2002 Arnout van Meer", /* module copyright */ + "1.3", /* module version string */ + "RtCW MDC", /* module display name */ + "Arnout van Meer", /* author's name */ + "2002 Arnout van Meer", /* module copyright */ { - "mdc", NULL, NULL, NULL /* default extensions to use */ + "mdc", NULL, NULL, NULL /* default extensions to use */ }, - _mdc_canload, /* validation routine */ - _mdc_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ + _mdc_canload, /* validation routine */ + _mdc_load, /* load routine */ + NULL, /* save validation routine */ + NULL /* save routine */ }; diff --git a/libs/picomodel/pm_ms3d.c b/libs/picomodel/pm_ms3d.c index 8626beed..535b7e22 100644 --- a/libs/picomodel/pm_ms3d.c +++ b/libs/picomodel/pm_ms3d.c @@ -1,36 +1,36 @@ /* ----------------------------------------------------------------------------- -PicoModel Library + PicoModel Library -Copyright (c) 2002, Randy Reddig & seaw0lf -All rights reserved. + Copyright (c) 2002, Randy Reddig & seaw0lf + All rights reserved. -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. -Neither the names of the copyright holders nor the names of its contributors may -be used to endorse or promote products derived from this software without -specific prior written permission. + Neither the names of the copyright holders nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ */ + ----------------------------------------------------------------------------- */ @@ -59,18 +59,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. static picoColor_t white = { 255,255,255,255 }; /* ms3d limits */ -#define MS3D_MAX_VERTS 8192 -#define MS3D_MAX_TRIS 16384 -#define MS3D_MAX_GROUPS 128 -#define MS3D_MAX_MATERIALS 128 -#define MS3D_MAX_JOINTS 128 -#define MS3D_MAX_KEYFRAMES 216 +#define MS3D_MAX_VERTS 8192 +#define MS3D_MAX_TRIS 16384 +#define MS3D_MAX_GROUPS 128 +#define MS3D_MAX_MATERIALS 128 +#define MS3D_MAX_JOINTS 128 +#define MS3D_MAX_KEYFRAMES 216 /* ms3d flags */ -#define MS3D_SELECTED 1 -#define MS3D_HIDDEN 2 -#define MS3D_SELECTED2 4 -#define MS3D_DIRTY 8 +#define MS3D_SELECTED 1 +#define MS3D_HIDDEN 2 +#define MS3D_SELECTED2 4 +#define MS3D_DIRTY 8 /* this freaky loader needs byte alignment */ #pragma pack(push, 1) @@ -78,47 +78,47 @@ static picoColor_t white = { 255,255,255,255 }; /* ms3d header */ typedef struct SMsHeader { - char magic[10]; - int version; + char magic[10]; + int version; } TMsHeader; /* ms3d vertex */ typedef struct SMsVertex { - unsigned char flags; /* sel, sel2, or hidden */ - float xyz[3]; - char boneID; /* -1 means 'no bone' */ - unsigned char refCount; + unsigned char flags; /* sel, sel2, or hidden */ + float xyz[3]; + char boneID; /* -1 means 'no bone' */ + unsigned char refCount; } TMsVertex; /* ms3d triangle */ typedef struct SMsTriangle { - unsigned short flags; /* sel, sel2, or hidden */ - unsigned short vertexIndices[3]; - float vertexNormals[3][3]; - float s[3]; - float t[3]; - unsigned char smoothingGroup; /* 1 - 32 */ - unsigned char groupIndex; + unsigned short flags; /* sel, sel2, or hidden */ + unsigned short vertexIndices[3]; + float vertexNormals[3][3]; + float s[3]; + float t[3]; + unsigned char smoothingGroup; /* 1 - 32 */ + unsigned char groupIndex; } TMsTriangle; /* ms3d material */ typedef struct SMsMaterial { - char name[32]; - float ambient[4]; - float diffuse[4]; - float specular[4]; - float emissive[4]; - float shininess; /* range 0..128 */ - float transparency; /* range 0..1 */ - unsigned char mode; - char texture [128]; /* texture.bmp */ - char alphamap[128]; /* alpha.bmp */ + char name[32]; + float ambient[4]; + float diffuse[4]; + float specular[4]; + float emissive[4]; + float shininess; /* range 0..128 */ + float transparency; /* range 0..1 */ + unsigned char mode; + char texture [128]; /* texture.bmp */ + char alphamap[128]; /* alpha.bmp */ } TMsMaterial; @@ -126,34 +126,34 @@ TMsMaterial; // followed by a variable size block (see below) typedef struct SMsGroup { - unsigned char flags; // sel, hidden - char name[32]; - unsigned short numTriangles; + unsigned char flags; // sel, hidden + char name[32]; + unsigned short numTriangles; /* - unsigned short triangleIndices[ numTriangles ]; - char materialIndex; // -1 means 'no material' -*/ + unsigned short triangleIndices[ numTriangles ]; + char materialIndex; // -1 means 'no material' + */ } TMsGroup; // ms3d joint typedef struct SMsJoint { - unsigned char flags; - char name[32]; - char parentName[32]; - float rotation[3]; - float translation[3]; - unsigned short numRotationKeyframes; - unsigned short numTranslationKeyframes; + unsigned char flags; + char name[32]; + char parentName[32]; + float rotation[3]; + float translation[3]; + unsigned short numRotationKeyframes; + unsigned short numTranslationKeyframes; } TMsJoint; // ms3d keyframe typedef struct SMsKeyframe { - float time; - float parameter[3]; + float time; + float parameter[3]; } TMsKeyframe; @@ -163,26 +163,26 @@ TMsKeyframe; /* _ms3d_canload: * validates a milkshape3d model file. */ -static int _ms3d_canload( PM_PARAMS_CANLOAD ) -{ +static int _ms3d_canload( PM_PARAMS_CANLOAD ){ const TMsHeader *hdr; - - + + /* sanity check */ - if ((size_t) bufSize < sizeof(TMsHeader)) + if ( (size_t) bufSize < sizeof( TMsHeader ) ) { return PICO_PMV_ERROR_SIZE; + } /* get ms3d header */ hdr = (const TMsHeader *)buffer; /* check ms3d magic */ - if (strncmp(hdr->magic,"MS3D000000",10) != 0) + if ( strncmp( hdr->magic,"MS3D000000",10 ) != 0 ) { return PICO_PMV_ERROR_IDENT; + } /* check ms3d version */ - if (_pico_little_long(hdr->version) < 3 || - _pico_little_long(hdr->version) > 4) - { + if ( _pico_little_long( hdr->version ) < 3 || + _pico_little_long( hdr->version ) > 4 ) { _pico_printf( PICO_ERROR,"MS3D file ignored. Only MS3D 1.3 and 1.4 is supported." ); return PICO_PMV_ERROR_VERSION; } @@ -190,53 +190,55 @@ static int _ms3d_canload( PM_PARAMS_CANLOAD ) return PICO_PMV_OK; } -static unsigned char *GetWord( unsigned char *bufptr, int *out ) -{ - if (bufptr == NULL) return NULL; +static unsigned char *GetWord( unsigned char *bufptr, int *out ){ + if ( bufptr == NULL ) { + return NULL; + } *out = _pico_little_short( *(unsigned short *)bufptr ); return( bufptr + 2 ); } /* _ms3d_load: * loads a milkshape3d model file. -*/ -static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ) -{ - picoModel_t *model; + */ +static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ){ + picoModel_t *model; unsigned char *bufptr, *bufptr0; - int shaderRefs[ MS3D_MAX_GROUPS ]; - int numGroups; - int numMaterials; + int shaderRefs[ MS3D_MAX_GROUPS ]; + int numGroups; + int numMaterials; // unsigned char *ptrToGroups; - int numVerts; + int numVerts; unsigned char *ptrToVerts; - int numTris; + int numTris; unsigned char *ptrToTris; - int i,k,m; + int i,k,m; /* create new pico model */ model = PicoNewModel(); - if (model == NULL) return NULL; + if ( model == NULL ) { + return NULL; + } /* do model setup */ PicoSetModelFrameNum( model, frameNum ); PicoSetModelName( model, fileName ); PicoSetModelFileName( model, fileName ); - bufptr0 = bufptr = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bufptr, buffer, bufSize); + bufptr0 = bufptr = (picoByte_t*) _pico_alloc( bufSize ); + memcpy( bufptr, buffer, bufSize ); /* skip header */ - bufptr += sizeof(TMsHeader); + bufptr += sizeof( TMsHeader ); /* get number of vertices */ bufptr = GetWord( bufptr,&numVerts ); ptrToVerts = bufptr; #ifdef DEBUG_PM_MS3D - printf("NumVertices: %d\n",numVerts); + printf( "NumVertices: %d\n",numVerts ); #endif /* swap verts */ - for (i=0; ixyz[ 2 ] = _pico_little_float( vertex->xyz[ 2 ] ); #ifdef DEBUG_PM_MS3D_EX_ - printf("Vertex: x: %f y: %f z: %f\n", - msvd[i]->vertex[0], - msvd[i]->vertex[1], - msvd[i]->vertex[2]); + printf( "Vertex: x: %f y: %f z: %f\n", + msvd[i]->vertex[0], + msvd[i]->vertex[1], + msvd[i]->vertex[2] ); #endif } /* get number of triangles */ @@ -258,10 +260,10 @@ static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ) ptrToTris = bufptr; #ifdef DEBUG_PM_MS3D - printf("NumTriangles: %d\n",numTris); + printf( "NumTriangles: %d\n",numTris ); #endif /* swap tris */ - for (i=0; iflags = _pico_little_short( triangle->flags ); /* run through all tri verts */ - for (k=0; k<3; k++) + for ( k = 0; k < 3; k++ ) { /* swap tex coords */ triangle->s[ k ] = _pico_little_float( triangle->s[ k ] ); @@ -283,11 +285,10 @@ static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ) triangle->vertexNormals[ 2 ][ k ] = _pico_little_float( triangle->vertexNormals[ 2 ][ k ] ); /* check for out of range indices */ - if (triangle->vertexIndices[ k ] >= numVerts) - { - _pico_printf( PICO_ERROR,"Vertex %d index %d out of range (%d, max %d)",i,k,triangle->vertexIndices[k],numVerts-1); + if ( triangle->vertexIndices[ k ] >= numVerts ) { + _pico_printf( PICO_ERROR,"Vertex %d index %d out of range (%d, max %d)",i,k,triangle->vertexIndices[k],numVerts - 1 ); PicoFreeModel( model ); - _pico_free(bufptr0); + _pico_free( bufptr0 ); return NULL; /* yuck */ } } @@ -297,21 +298,20 @@ static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ) // ptrToGroups = bufptr; #ifdef DEBUG_PM_MS3D - printf("NumGroups: %d\n",numGroups); + printf( "NumGroups: %d\n",numGroups ); #endif /* run through all groups in model */ - for (i=0; i */ - else if( !Q_stricmp( token, "q3map_floodLight" ) ) - { + else if ( !Q_stricmp( token, "q3map_floodLight" ) ) { /* get color */ GetTokenAppend( shaderText, qfalse ); si->floodlightRGB[ 0 ] = atof( token ); @@ -1535,173 +1517,154 @@ static void ParseShaderFile( const char *filename ) GetTokenAppend( shaderText, qfalse ); si->floodlightRGB[ 2 ] = atof( token ); GetTokenAppend( shaderText, qfalse ); - si->floodlightDistance = atof( token ); + si->floodlightDistance = atof( token ); GetTokenAppend( shaderText, qfalse ); - si->floodlightIntensity = atof( token ); + si->floodlightIntensity = atof( token ); GetTokenAppend( shaderText, qfalse ); - si->floodlightDirectionScale = atof( token ); - if(colorsRGB) - { - si->floodlightRGB[0] = Image_LinearFloatFromsRGBFloat(si->floodlightRGB[0]); - si->floodlightRGB[1] = Image_LinearFloatFromsRGBFloat(si->floodlightRGB[1]); - si->floodlightRGB[2] = Image_LinearFloatFromsRGBFloat(si->floodlightRGB[2]); + si->floodlightDirectionScale = atof( token ); + if ( colorsRGB ) { + si->floodlightRGB[0] = Image_LinearFloatFromsRGBFloat( si->floodlightRGB[0] ); + si->floodlightRGB[1] = Image_LinearFloatFromsRGBFloat( si->floodlightRGB[1] ); + si->floodlightRGB[2] = Image_LinearFloatFromsRGBFloat( si->floodlightRGB[2] ); } - ColorNormalize(si->floodlightRGB, si->floodlightRGB); + ColorNormalize( si->floodlightRGB, si->floodlightRGB ); } /* jal: q3map_nodirty : skip dirty */ - else if( !Q_stricmp( token, "q3map_nodirty" ) ) - { + else if ( !Q_stricmp( token, "q3map_nodirty" ) ) { si->noDirty = qtrue; } - + /* q3map_lightmapSampleSize */ - else if( !Q_stricmp( token, "q3map_lightmapSampleSize" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapSampleSize" ) ) { GetTokenAppend( shaderText, qfalse ); si->lightmapSampleSize = atoi( token ); } - + /* q3map_lightmapSampleOffset */ - else if( !Q_stricmp( token, "q3map_lightmapSampleOffset" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapSampleOffset" ) ) { GetTokenAppend( shaderText, qfalse ); si->lightmapSampleOffset = atof( token ); } - + /* ydnar: q3map_lightmapFilterRadius */ - else if( !Q_stricmp( token, "q3map_lightmapFilterRadius" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapFilterRadius" ) ) { GetTokenAppend( shaderText, qfalse ); si->lmFilterRadius = atof( token ); GetTokenAppend( shaderText, qfalse ); si->lightFilterRadius = atof( token ); } - + /* ydnar: q3map_lightmapAxis [xyz] */ - else if( !Q_stricmp( token, "q3map_lightmapAxis" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapAxis" ) ) { GetTokenAppend( shaderText, qfalse ); - if( !Q_stricmp( token, "x" ) ) + if ( !Q_stricmp( token, "x" ) ) { VectorSet( si->lightmapAxis, 1, 0, 0 ); - else if( !Q_stricmp( token, "y" ) ) + } + else if ( !Q_stricmp( token, "y" ) ) { VectorSet( si->lightmapAxis, 0, 1, 0 ); - else if( !Q_stricmp( token, "z" ) ) + } + else if ( !Q_stricmp( token, "z" ) ) { VectorSet( si->lightmapAxis, 0, 0, 1 ); + } else { Sys_Printf( "WARNING: Unknown value for lightmap axis: %s\n", token ); VectorClear( si->lightmapAxis ); } } - + /* ydnar: q3map_lightmapSize (for autogenerated shaders + external tga lightmaps) */ - else if( !Q_stricmp( token, "q3map_lightmapSize" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapSize" ) ) { GetTokenAppend( shaderText, qfalse ); si->lmCustomWidth = atoi( token ); GetTokenAppend( shaderText, qfalse ); si->lmCustomHeight = atoi( token ); - + /* must be a power of 2 */ - if( ((si->lmCustomWidth - 1) & si->lmCustomWidth) || - ((si->lmCustomHeight - 1) & si->lmCustomHeight) ) - { + if ( ( ( si->lmCustomWidth - 1 ) & si->lmCustomWidth ) || + ( ( si->lmCustomHeight - 1 ) & si->lmCustomHeight ) ) { Sys_Printf( "WARNING: Non power-of-two lightmap size specified (%d, %d)\n", - si->lmCustomWidth, si->lmCustomHeight ); + si->lmCustomWidth, si->lmCustomHeight ); si->lmCustomWidth = lmCustomSize; si->lmCustomHeight = lmCustomSize; } } /* ydnar: q3map_lightmapBrightness N (for autogenerated shaders + external tga lightmaps) */ - else if( !Q_stricmp( token, "q3map_lightmapBrightness" ) || !Q_stricmp( token, "q3map_lightmapGamma" ) ) - { + else if ( !Q_stricmp( token, "q3map_lightmapBrightness" ) || !Q_stricmp( token, "q3map_lightmapGamma" ) ) { GetTokenAppend( shaderText, qfalse ); si->lmBrightness = atof( token ); - if( si->lmBrightness < 0 ) + if ( si->lmBrightness < 0 ) { si->lmBrightness = 1.0; + } } - + /* q3map_vertexScale (scale vertex lighting by this fraction) */ - else if( !Q_stricmp( token, "q3map_vertexScale" ) ) - { + else if ( !Q_stricmp( token, "q3map_vertexScale" ) ) { GetTokenAppend( shaderText, qfalse ); si->vertexScale = atof( token ); } - + /* q3map_noVertexLight */ - else if( !Q_stricmp( token, "q3map_noVertexLight" ) ) - { + else if ( !Q_stricmp( token, "q3map_noVertexLight" ) ) { si->noVertexLight = qtrue; } - + /* q3map_flare[Shader] */ - else if( !Q_stricmp( token, "q3map_flare" ) || !Q_stricmp( token, "q3map_flareShader" ) ) - { + else if ( !Q_stricmp( token, "q3map_flare" ) || !Q_stricmp( token, "q3map_flareShader" ) ) { GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { + if ( token[ 0 ] != '\0' ) { si->flareShader = safe_malloc( strlen( token ) + 1 ); strcpy( si->flareShader, token ); } } - + /* q3map_backShader */ - else if( !Q_stricmp( token, "q3map_backShader" ) ) - { + else if ( !Q_stricmp( token, "q3map_backShader" ) ) { GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { + if ( token[ 0 ] != '\0' ) { si->backShader = safe_malloc( strlen( token ) + 1 ); strcpy( si->backShader, token ); } } - + /* ydnar: q3map_cloneShader */ - else if ( !Q_stricmp( token, "q3map_cloneShader" ) ) - { + else if ( !Q_stricmp( token, "q3map_cloneShader" ) ) { GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { + if ( token[ 0 ] != '\0' ) { si->cloneShader = safe_malloc( strlen( token ) + 1 ); strcpy( si->cloneShader, token ); } } - + /* q3map_remapShader */ - else if( !Q_stricmp( token, "q3map_remapShader" ) ) - { + else if ( !Q_stricmp( token, "q3map_remapShader" ) ) { GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { + if ( token[ 0 ] != '\0' ) { si->remapShader = safe_malloc( strlen( token ) + 1 ); strcpy( si->remapShader, token ); } } /* q3map_deprecateShader */ - else if( !Q_stricmp( token, "q3map_deprecateShader" ) ) - { + else if ( !Q_stricmp( token, "q3map_deprecateShader" ) ) { GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { + if ( token[ 0 ] != '\0' ) { si->deprecateShader = safe_malloc( strlen( token ) + 1 ); strcpy( si->deprecateShader, token ); } } - + /* ydnar: q3map_offset */ - else if( !Q_stricmp( token, "q3map_offset" ) ) - { + else if ( !Q_stricmp( token, "q3map_offset" ) ) { GetTokenAppend( shaderText, qfalse ); si->offset = atof( token ); } - + /* ydnar: q3map_fur */ - else if( !Q_stricmp( token, "q3map_fur" ) ) - { + else if ( !Q_stricmp( token, "q3map_fur" ) ) { GetTokenAppend( shaderText, qfalse ); si->furNumLayers = atoi( token ); GetTokenAppend( shaderText, qfalse ); @@ -1709,10 +1672,9 @@ static void ParseShaderFile( const char *filename ) GetTokenAppend( shaderText, qfalse ); si->furFade = atof( token ); } - + /* ydnar: gs mods: legacy support for terrain/terrain2 shaders */ - else if( !Q_stricmp( token, "q3map_terrain" ) ) - { + else if ( !Q_stricmp( token, "q3map_terrain" ) ) { /* team arena terrain is assumed to be nonplanar, with full normal averaging, passed through the metatriangle surface pipeline, with a lightmap axis on z */ si->legacyTerrain = qtrue; @@ -1724,48 +1686,42 @@ static void ParseShaderFile( const char *filename ) si->shadeAngleDegrees = 179.0f; //% VectorSet( si->lightmapAxis, 0, 0, 1 ); /* ydnar 2002-09-21: turning this off for better lightmapping of cliff faces */ } - + /* ydnar: picomodel: q3map_forceMeta (forces brush faces and/or triangle models to go through the metasurface pipeline) */ - else if( !Q_stricmp( token, "q3map_forceMeta" ) ) - { + else if ( !Q_stricmp( token, "q3map_forceMeta" ) ) { si->forceMeta = qtrue; } - + /* ydnar: gs mods: q3map_shadeAngle */ - else if( !Q_stricmp( token, "q3map_shadeAngle" ) ) - { + else if ( !Q_stricmp( token, "q3map_shadeAngle" ) ) { GetTokenAppend( shaderText, qfalse ); si->shadeAngleDegrees = atof( token ); } - + /* ydnar: q3map_textureSize (substitute for q3map_lightimage derivation for terrain) */ - else if( !Q_stricmp( token, "q3map_textureSize" ) ) - { + else if ( !Q_stricmp( token, "q3map_textureSize" ) ) { GetTokenAppend( shaderText, qfalse ); si->shaderWidth = atoi( token ); GetTokenAppend( shaderText, qfalse ); si->shaderHeight = atoi( token ); } - + /* ydnar: gs mods: q3map_tcGen