SWMM6 & SWMM5 Enablement

Stormwater modeling notes, decoded.

SWMM5, SWMM6, XPSWMM, InfoSWMM, InfoSewer, OpenSWMM, and ICM — engine internals, error messages, calibration, and hard-won field wisdom from Robert Dickinson.

SWMM5 Delphi GUI Umap.pas Summary

 Extended and Expanded Summary of the Umap.pas Unit

This unit, Umap.pas, forms a central part of EPA SWMM’s map-drawing architecture. It manages drawing the Study Area Map on a memory bitmap and handles details like re-scaling, positioning, labeling, and optionally rendering a backdrop image.

Below is a thorough guide to:

  1. Purpose and Scope
  2. Core Data Structures
  3. Key Constants & Defaults
  4. Principal Routines
  5. Workflow
  6. Integration With Other Units

1. Purpose and Scope

The Umap.pas unit covers:

  • Rendering (drawing) the SWMM project’s elements onto an in-memory bitmap, then onto the main display canvas.
  • Backdrops, including reading an image from a file, placing it behind the foreground objects, and optionally modifying it (watermark, grayscale).
  • Re-scaling and zooming the map, ensuring that the coordinate transformations (World ↔ Screen) are correct.
  • Legendary map operations:
    • Identifying bounding rectangles for objects.
    • Drawing objects (subcatchments, nodes, links, and labels) at the correct size and color.
    • Handling shape-specific symbols (outfalls, dividers, inlets, etc.).
  • Coordinate conversion methods, allowing SWMM’s internal world coordinates to map onto device (pixel) coordinates.

2. Core Data Structures

2.1 TMap Class

TMap = class(TObject)
  Canvas    : TCanvas;      
  Bitmap    : TBitmap;      
  BackBM    : TBitmap;      
  GageBM    : TBitmap;      
  InletBM   : TBitmap;      
  Window    : TMapWindow;   
  Dimensions: TMapDimensions;
  Options   : TMapOptions;  
  Backdrop  : TMapBackdrop; 
  Sfactor   : Extended;     
  ZoomState : array [0..10] of TMapZoomState;
  ZoomIndex : Integer;      
  ZoomRatio : Integer;
  ...
end;

The TMap class encapsulates all map-centric data:

  • Canvas: The main TCanvas used for drawing.
  • Bitmap, BackBM: TBitmap objects for the overall map and the backdrop.
  • GageBM, InletBM: Bitmaps for specialized symbols (raingages, inlets).
  • Window: A TMapWindow record describing the mapping from world to pixel coordinates.
  • Dimensions: A TMapDimensions record with physical extents, unit conversions, etc.
  • Options: A TMapOptions record (e.g., whether to show node IDs, subcatchment fill style, arrow sizes, etc.).
  • Backdrop: A TMapBackdrop record with backdrop image info (filename, source, corners, etc.).
  • Sfactor: A factor for adjusting scale at zero-zoom.
  • ZoomState[]: Up to 10 zoom states can be stored, each with a center and zoom factor.

2.2 Supporting Records

  • TMapDimensions: Contains the real-world bounding box, length/area conversion factors, map units, etc.
  • TMapWindow: Captures the pixel-based map rectangle, world→pixel offset, and scaling ratio.
  • TMapBackdrop: For controlling the source/visibility of the backdrop image.
  • TMapOptions: For toggling visibility of subcatchments, nodes, etc., plus annotation styles and coloring.

3. Key Constants & Defaults

  1. MAX_INT_COORD = 32767 (the maximum pixel coordinate for safe GDI operations).
  2. MAX_POINTS = 1000 (the max vertices in a polygon array).
  3. Default TMapDimensions (DefMapDimensions) with 0..10000 bounding box, 3 decimal digits, conversion factors, etc.
  4. Default TMapBackdrop (DefMapBackdrop) with none source, empty file, etc.
  5. Default TMapOptions (DefMapOptions) with things like show subcatchments, node IDs off, link IDs off, etc.

4. Principal Routines

4.1 Map Construction and Lifecycle

  • constructor TMap.Create

    • Allocates memory bitmaps (Bitmap, BackBM, GageBM, InletBM) and sets them to 24-bit color.
    • Applies default map/backdrop options and zero-level zoom state.
  • destructor TMap.Destroy

    • Frees the TBitmap objects.

4.2 Drawing Methods

  1. DrawMap

    • Clears map background, optionally draws the backdrop, then calls DrawForeground.
  2. DrawForeground

    • Sets pen & brush colors, draws subcatchments, links, nodes, gages, and labels.
  3. Object-Specific:

    • DrawSubcatchments, DrawSubcatch(Index):
      • Retrieves vertex points, sets a color from the subcatch’s color index, draws the polygon, subcatch centroid marker, etc.
    • DrawNodes, plus subroutines for each node type (DrawOutfall, DrawDivider, DrawStorage, etc.).
    • DrawLinks, DrawLink(...):
      • Draws polylines for each link, possibly with an arrow or pump/valve symbol.
    • DrawLabels:
      • Draws map labels (TMapLabel) with user-defined fonts.
  4. Symbol Drawing:

    • DrawArrowHead(...): for link flow direction.
    • DrawPumpSymbol(...): for pumps.
    • DrawInletSymbol(...): for inlets.

4.3 Backdrop Handling

  • DrawBackdrop(...)

    • Loads a TPicture from file, calculates a rectangle, then stretches the image onto the BackBM canvas.
    • Handles grayscale or watermark transformations if set.
  • RedrawBackdrop

    • Convenience method that calls DrawBackdrop if backdrop is visible.

4.4 Rescaling, Zooming, Coordinate Conversions

  • Rescale

    • Recomputes the current window scale (WperP) based on the main bounding rectangle and the current ZoomIndex.
  • Pixel ↔ World:

    • GetXpix, GetYpix convert from world to pixel.
    • GetX, GetY convert from pixel back to world.
  • ZoomState[] array keeps track of center coordinates and scale factors at different zoom levels.

4.5 Utility Methods

  • GetBoundingRect(...)

    • Returns the bounding rectangle in pixel space for a given SWMM object (subcatch, node, link, or label).
  • GetNodeRect(...), GetLinkRect(...), GetSubcatchRect(...)

    • Specialized bounding rectangle logic for each category.
  • SnapSubcatch(...)

    • Example of snapping subcatchment vertices if user drags them close to another polygon.
  • GetSubcatchAreaStr(...), GetLinkLengthStr(...)

    • For computing lengths in consistent project units.

5. Workflow

  1. Initialization

    • A TMap instance is created, bitmaps are allocated, default dimension and options are assigned.
    • The “full extents” of the map are determined from the project bounding box (see Rescale logic).
  2. Backdrop

    • If the user sets a backdrop file, RedrawBackdrop is called.
    • DrawBackdrop loads the file into a TPicture, positions it, and draws it onto BackBM.
  3. Drawing the Foreground

    • DrawMap is invoked, which erases the background, then copies the backdrop image (if visible) onto the main Bitmap.
    • Then DrawForeground systematically draws subcatchments, links, nodes, rain gages, labels, etc.
    • SWMM color-coded styling is determined via calls to SetNodeColor, SetSubcatchColor, etc.
  4. Zooming

    • The user might choose Zoom In/Out in the UI.
    • SWMM updates ZoomIndex or modifies ZoomState[ZoomIndex].
    • Rescale is called, then DrawMap re-renders at the new scale.
  5. Coordinate Tools

    • Clicking on the map or retrieving an object’s bounding rectangle uses the coordinate transformations in GetXpix, GetYpix, etc.

6. Integration With Other Units

  • Uglobals.pas

    • Defines CurrentNodeVar, CurrentLinkVar, etc., plus color arrays like MapSubcatchColor, MapNodeColor, MapLinkColor.
  • Uproject.pas

    • Houses the main Project object with subcatchments, nodes, links, etc.
    • Umap frequently queries Project to get coordinates, color indexes, etc.
  • Uoutput.pas

    • Provides Uoutput.GetNodeValStr, Uoutput.GetSubcatchValStr, etc. used for labeling.
  • Uinlet.pas

    • Some specialized logic for drawing inlets on conduits (DrawInletSymbol).
  • Jpeg

    • The code references loading TJPegImage if the user’s backdrop is a JPEG.
  • System.UITypes

    • For color and coordinate definitions in newer Delphi versions.

Concluding Remarks

In summary:

  • Umap.pas orchestrates the entire graphic representation of SWMM objects.
  • It does so by layering a backdrop image behind user-defined and computed shapes.
  • It manages the correlation between real-world coordinates (including lat-long if the user chooses) and the screen’s pixel coordinates.
  • It uses custom coloring, line widths, symbol drawing, text labels, and handling of user options to produce a clear, zoomable map representation.

SWMM5 Delphi GUI Ulid.pas Summary

 Extended and Expanded Summary of the Ulid.pas Unit

The Ulid.pas unit in EPA SWMM provides functionality for managing Low Impact Development (LID) controls and their assignment to subcatchments. LID controls represent various best management practices such as bio-retention cells, infiltration trenches, permeable pavement, and so on.

Below is a thorough overview of:

  1. Purpose and Scope
  2. Core Data Structures
  3. Key Constants
  4. Important Routines
  5. Workflow (How LIDs are read, stored, and used)
  6. Integration With Other Units

1. Purpose and Scope

Ulid.pas handles:

  • The creation, editing, and storage of LID process data (e.g., infiltration trench geometry, green roof layers, or underdrain parameters).
  • The definition of LID usage in specific subcatchments (e.g., how many units of permeable pavement in a subcatchment, or the fraction of impervious runoff directed to a bio-retention cell).
  • Reading LID controls from project input files and writing them back out to text.
  • Integrating LIDs into the subcatchment object model used by SWMM.

2. Core Data Structures

2.1 LID Process Class: TLid

TLid = class(TObject)
  ProcessType  : Integer;
  SurfaceLayer : array [0..4] of String;
  PavementLayer: array [0..6] of String;
  SoilLayer    : array [0..6] of String;
  StorageLayer : array [0..4] of String;
  DrainLayer   : array [0..6] of String;
  DrainMatLayer: array [0..2] of String;
  DrainRemovals: TStringlist;
  constructor Create;
  destructor Destroy; override;
end;

Each TLid instance holds parameters for a specific LID control design:

  • ProcessType: Identifies which type of LID (bio-cell, green roof, infiltration trench, etc.).
  • SurfaceLayer: An array of strings defining surface layer properties.
  • PavementLayer: For permeable pavement.
  • SoilLayer: Soil layer parameters.
  • StorageLayer: Storage layer parameters (e.g., thickness, void ratio).
  • DrainLayer: Underdrain (e.g., orifice or weir) parameters.
  • DrainMatLayer: Drainage mat properties (used in green roofs).
  • DrainRemovals: Pollutant-specific removal efficiencies for the underdrain outflow.

A TLid object is stored in Project.Lists[LID].

2.2 LID Unit Class: TLidUnit

TLidUnit = class(TObject)
  Data: array[0..9] of String;
end;

Each TLidUnit object represents the application of a specific LID process within a subcatchment:

  • The array Data[0..9] holds usage parameters, e.g., number of units, area, initial moisture, drainage outlet, etc.

LID units (one or more) are stored in a subcatchment’s LIDs string list (with the LID name as the string, and a TLidUnit object as the Objects[] element).


3. Key Constants

  1. LID Process Types

    BIO_CELL, RAIN_GARDEN, GREEN_ROOF, INFIL_TRENCH,
    PERM_PAVE, RAIN_BARREL, ROOF_DISCON, VEG_SWALE
    
  2. LID Process Layers

    SURFACE_LAYER, PAVEMENT_LAYER, SOIL_LAYER, STORAGE_LAYER,
    DRAIN_LAYER, DRAINMAT_LAYER, DRAIN_REMOVALS
    
  3. LID Unit Parameters (indices for TLidUnit.Data[])

    UNIT_COUNT, UNIT_AREA, UNIT_WIDTH, INIT_MOISTURE,
    FROM_IMPERV, ROUTE_TO, RPT_FILE_NAME, DRAIN_TO, FROM_PERV, ...
    

    These define how many units are installed, how big they are, how they’re connected, etc.

  4. Default layer property arrays (e.g., DefSurfaceLayer, DefPavementLayer, etc.)
    Provide fallback or initial parameter values.


4. Important Routines

4.1 LID Creation and Editing

  1. EditLID(const I: Integer): String;

    • Launches a form (TLidControlDlg) to create or edit a TLid object.
    • If I < 0, a new TLid is created. If I >= 0, an existing LID is edited.
    • On success, returns the final name of the LID.
  2. UpdateLIDName(const OldName, NewName: String);

    • Replaces all references to LID OldName with NewName in the subcatchment usage lists.

4.2 LID Group Editing

  • EditLIDGroup(...)
    • Allows the user to manage multiple LID units (instances of TLidUnit) assigned to a single subcatchment.
    • E.g., a subcatchment might have some area in permeable pavement, some area in infiltration trenches, etc.

4.3 LID Input/Output

  1. ReadLidData(...)

    • Parses [LID_CONTROLS] input lines from an INP file.
    • Supports reading each layer’s parameters for a given LID (Surface, Pavement, Soil, etc.).
  2. ReadLidUsageData(...)

    • Parses [LID_USAGE] input lines from an INP file, assigning an LID to a specific subcatchment.
  3. ExportLIDs(...)

    • Writes [LID_CONTROLS] section lines to an output file.
    • Calls ExportLIDRemovals(...) if there are pollutant removal lines.
  4. ExportLIDGroups(...)

    • Writes [LID_USAGE] section lines to an output file.
    • Summarizes all TLidUnit usage from each subcatchment.

4.4 Utility Methods

  • GetPcntLidArea(I: Integer): Extended;

    • Computes total % area of subcatchment I covered by LIDs.
  • GetPcntArea(Nunits: Integer; AreaStr: String): String;

    • Returns a user-friendly string with percent area that an LID usage occupies.
  • HasLIDType(SC: TSubcatch; const LIDType: Integer): Boolean;

    • Checks if subcatchment SC uses a particular LID process.
  • FreeLIDUnits(LidUnits: TStringlist);

    • Frees all the TLidUnit objects from a subcatchment’s LID usage list.

5. Workflow

  1. Defining an LID

    • The user creates a new LID control via EditLID(I=-1).
    • This defines the LID’s layers: surface, pavement, soil, storage, etc.
  2. Assigning LIDs to Subcatchments

    • The user calls EditLIDGroup(indexOfSubcatch, ...) to select from existing LIDs and apply them in the chosen subcatchment.
    • Each usage is stored as a TLidUnit object in that subcatchment’s LIDs list.
  3. Reading from an INP File

    • ReadLidData() reads the [LID_CONTROLS] section to create TLid objects.
    • ReadLidUsageData() reads the [LID_USAGE] section, creating TLidUnit objects that get added to each subcatchment.
  4. Writing to an INP File

    • ExportLIDs() writes out each LID’s definition in the [LID_CONTROLS] section.
    • ExportLIDGroups() writes the usage of each LID in [LID_USAGE].
  5. Deleting/Updating LIDs

    • If an LID is renamed, UpdateLIDName() updates references.
    • If an LID is deleted, references in subcatchments are removed (via EditLID() or manual name blanking).

6. Integration With Other Units

  • Uproject.pas

    • Houses the global Project object containing lists for LIDs and subcatchments.
  • Uglobals.pas

    • Defines the indexes for LID object lists and subcatchment categories.
    • Manages unit systems (US/SI) used in area conversions.
  • Dlid.pas (the LID Control Editor Form)

    • Allows a single LID’s layers to be edited.
    • Called from EditLID().
  • Dlidgroup.pas (the LID Group Editor Form)

    • Allows multiple LID units to be assigned to a subcatchment.
    • Called from EditLIDGroup().
  • Uimport.pas

    • Provides routines for reading lines from an INP file, calling ReadLidData() or ReadLidUsageData().
  • Uexport.pas

    • Provides path manipulations, used for writing file references in ExportLIDs() or ExportLIDGroups().

Concluding Remarks

  • Ulid.pas is the primary repository for LID “control” definitions and their usage in subcatchments.
  • The code uses short arrays (e.g., [0..4], [0..6]) for each LID layer to store numeric text parameters.
  • LID usage is a separate concept from LID definition: the TLid class describes the process/layer specs, while TLidUnit describes how a subcatchment uses it.

This modular approach simplifies reading/writing LID data, editing them in specialized dialog forms, and referencing them from the rest of SWMM’s data structures.

SWMM5 Delphi GUI Ulegend.pas Summary

 Extended and Expanded Summary of the Ulegend.pas Unit

The Ulegend.pas unit in EPA SWMM manages the creation, display, and editing of color legends for various variables shown on the study area map. It also includes functionality to draw a legend for elapsed or actual simulation time (the “time legend”). Below is a thorough overview of the unit’s functionality, data parameters, and key routines.


1. Purpose and Scope

The Ulegend.pas unit is responsible for:

  1. Drawing the legend that shows how colors map to ranges (intervals) of subcatchment, node, or link variables (e.g., pollutant concentration, water depth, velocity, etc.).
  2. Displaying and editing legend intervals and colors through a user interface (the Legend Editor dialog).
  3. Drawing a separate time legend on the map that displays the current simulation time period being viewed.

2. Key Data Types and Fields

2.1 TMapLegend Record

A TMapLegend is defined globally in Uglobals.pas and referenced here. It holds:

  • Intervals: an array of floating-point breakpoints for the color intervals.
  • Nintervals: the number of these intervals actually used (1 to MAXINTERVALS).
  • Ltype: the object type for this legend (e.g., SUBCATCHMENTS, NODES, or LINKS).
  • ViewVar: the index of the particular variable (e.g., flow, depth, pollutant concentration) being displayed.

2.2 Supporting Variables

  • MapColor[] or Colors[]: arrays of TColor used to assign colors to each legend interval.
  • Digits: integer specifying how many decimal places to display for legend intervals.
  • Framed: boolean that determines if the legend is drawn with a bounding rectangle.

3. Main Functions and Procedures

3.1 DrawLegend(...)

procedure DrawLegend(
  const R: TRect;
  const C: TCanvas;
  const BackColor: TColor;
  const Framed: Boolean;
  const Legend: TMapLegend;
  const VarIndex: Integer;
  const Digits: Integer;
  const MapColor: array of TColor);
  • Purpose
    Draws a color-coded legend for a specified variable on a map canvas.

  • Parameters

    1. R: The rectangle on which the legend is drawn.
    2. C: The TCanvas where the legend is rendered.
    3. BackColor: Background color for the legend area.
    4. Framed: Whether or not to draw a rectangle frame around the legend.
    5. Legend: The TMapLegend record containing intervals and the number of intervals.
    6. VarIndex: Identifies which variable’s legend is drawn (e.g., flow, depth).
    7. Digits: Number of decimal digits to display on interval labels.
    8. MapColor: Array of colors associated with each legend interval.
  • Logic

    • Retrieves the name and units of the variable from GetObjVarNames (in Uglobals.pas).
    • Clears the rectangle R with the background color.
    • Draws optional framing if Framed is True.
    • Renders a title with object type (“Node”, “Link”, or “Subcatch”) and the variable name (e.g., “Depth”, “Concentration”).
    • For each interval in the legend, draws a small color box and a textual label with the numeric breakpoint (formatted with Digits decimals).
    • Optionally shows the variable’s measurement units (e.g., MGD, CFS, etc.).

3.2 DrawTimeLegend(...)

procedure DrawTimeLegend(
  R: TRect;
  C: TCanvas;
  const BackColor: TColor;
  const S: String);
  • Purpose
    Draws the textual “time legend” (the current date/time or elapsed time of the simulation) in a specified rectangle.

  • Parameters

    1. R: The rectangle bounding the legend.
    2. C: The map canvas on which to draw.
    3. BackColor: Background color.
    4. S: The time string to display (e.g., “4/25/2024 12:00:00 AM”).
  • Logic

    • Fills the background with BackColor.
    • Chooses a font (Arial, Bold, size=8).
    • Writes the string S centered in the rectangle R.
    • The text and pen color is set to contrast with the background (e.g., if the background is black, the text is white).

3.3 EditLegend(...)

function EditLegend(
  var Legend: TMapLegend;
  const VarIndex: Integer;
  const Digits: Integer;
  const TimePeriod: Integer;
  var Colors: array of TColor;
  var Framed: Boolean): Boolean;
  • Purpose
    Opens a Legend Editor dialog box (TLegendForm) to let the user modify legend intervals, colors, or whether the legend is framed.

  • Parameters

    1. Legend: Reference to the current legend’s intervals, number of intervals, etc.
    2. VarIndex: The variable being depicted.
    3. Digits: Decimal places for numeric intervals.
    4. TimePeriod: The current simulation time period (for possibly adjusting scale).
    5. Colors: The color array for each legend break.
    6. Framed: Whether the user wants a framed bounding rectangle around the legend.
  • Logic

    1. Retrieves the object class and variable name/units via GetObjVarNames.
    2. Instantiates TLegendForm (declared in Dlegend.pas), passing in legend data.
    3. If the user clicks OK, the updated intervals, colors, and Framed flag are retrieved.
    4. If user cancels, returns False (no changes applied).

4. Integration with Other Units

  1. Dlegend.pas: The actual Legend Editor form used by EditLegend.
  2. Uglobals.pas:
    • Contains the TMapLegend record, constants like SUBCATCHMENTS, NODES, etc.
    • Provides GetObjVarNames(...) which returns object category name, variable name, and units.
  3. Uutils.pas:
    • Offers string formatting and numeric conversion utilities (FloatToStrF, etc.).
  4. Fmain.pas or Fmap.pas**:
    • The location where these legends are drawn or updated on the map.
  5. System.UITypes:
    • Provides definitions for color, coordinate rectangles, and possibly other UI-related types.

5. Typical Usage Flow

  1. Drawing the Legend

    • The SWMM main map display calls DrawLegend(...) whenever it needs to refresh or redraw the color-coded legend.
    • The legend’s intervals and colors come from the SubcatchLegend[], NodeLegend[], or LinkLegend[] arrays in Uglobals.
  2. User Editing

    • The user right-clicks or otherwise chooses to “Edit Legend.”
    • EditLegend(...) is invoked, which displays TLegendForm.
    • The user adjusts the color scale, intervals, number of intervals, etc.
    • On closing with OK, the updated properties store back into the Legend and Colors arrays.
  3. Time Legend

    • In an animation loop or when stepping through simulation time periods, DrawTimeLegend(...) is called to update the displayed date/time in a small region of the map.

6. Conclusions

The Ulegend.pas unit provides the fundamental drawing routines and an editing hook for legends in SWMM’s map display. Key highlights include:

  • It can display both variable legends (with multiple color intervals) and a time legend.
  • Legend intervals are typically read from or saved to Uglobals data structures, ensuring consistency across SWMM.
  • A separate form (Dlegend.pas) is used for interactive editing of the color intervals, numeric ranges, and legend styles.

This approach separates the concerns of:

  1. Storing legend data (TMapLegend in Uglobals),
  2. Drawing it on the map (Ulegend.pas), and
  3. Letting the user edit intervals (Dlegend.pas).

SWMM5 Delphi GUI Uinlet.pas Summary

 Extended and Expanded Summary of the Uinlet.pas Unit

The Uinlet.pas unit in EPA SWMM manages the logic, data storage, and I/O routines for modeling street and channel inlets within a SWMM project. Inlet definitions determine how flow enters a conduit link through different inlet geometries (e.g., grates, curb openings, etc.). The unit also covers the usage details of those inlets, including how many inlets are placed, how clogged they might be, or where captured flow is directed.

Below is a comprehensive summary of the unit’s structures, functionality, and main procedures.


1. Data Structures

1.1 TInlet Class

  • Purpose
    Represents a type of inlet design, specifying geometry and relevant characteristics such as length, width, fraction of open area, etc.

  • Key Fields

    1. InletType: An integer representing the type of inlet (grate, curb, combo, slotted, drop grate, drop curb, or custom).
    2. Data[0..MAX_INLET_PROPS]: An array of strings storing property values for the selected inlet type. The properties are indexed constants such as GRATE_INLET_TYPE, GRATE_INLET_LENGTH, etc.
  • Important Methods

    • constructor Create;
      Initializes the new TInlet object with default properties (DefInlet array).
    • function GetID: String;
      Returns the ID name of the inlet design from the global Project.Lists[INLET] array.

1.2 TInletUsage Class

  • Purpose
    Describes how a particular inlet design (TInlet) is used on a specific conduit link (TLink) in the network.

  • Key Fields

    1. InletLink: The link where the inlet is placed.
    2. InletNode: The node that receives flow from the inlet (i.e., the “capture” node).
    3. Inlet: A reference to a TInlet object describing the inlet design.
    4. Data[0..USAGE_MAX_INDEX]: An array of strings holding usage properties (e.g., number of inlets, percent clogged, maximum flow limit, local depression geometry, etc.).

2. Constants & Index Definitions

  1. Inlet Placement

    • AUTOMATIC = 0
    • ON_GRADE = 1
    • ON_SAG = 2
  2. Inlet Types

    • GRATE_INLET = 0
    • CURB_INLET = 1
    • COMBO_INLET = 2
    • SLOTTED_INLET = 3
    • DROP_GRATE = 4
    • DROP_CURB = 5
    • CUSTOM_INLET = 6
  3. TInlet.Data[] Field Indexes (0..MAX_INLET_PROPS)

    • Grate-specific fields, e.g., GRATE_INLET_TYPE, GRATE_INLET_LENGTH, etc.
    • Curb-specific fields, e.g., CURB_INLET_LENGTH, CURB_INLET_HEIGHT, etc.
    • Slotted or custom inlet fields.
  4. Usage Indexes (0..USAGE_MAX_INDEX)

    • USAGE_NUM_INLETS, USAGE_PCNT_CLOGGED, USAGE_FLOW_RESTRICT, USAGE_DEPRESS_HEIGHT, USAGE_DEPRESS_WIDTH, USAGE_PLACEMENT.

3. Main Routines

3.1 Reading / Writing “Inlet Design” Data

These handle the [INLETS] section in an SWMM input file.

  1. ReadInletDesignData

    • Called when parsing a line from [INLETS] in a SWMM input file.
    • Determines which inlet “type” is being read (e.g., GRATE, CURB, COMBO, SLOTTED, CUSTOM, etc.) based on keywords.
    • Creates or updates a TInlet object in Project.Lists[INLET], filling in property fields.
  2. Helper Functions

    • ReadGrateInletData(...)
      Reads data tokens for a grate or combination inlet.
    • ReadCurbInletData(...)
      Reads data tokens for a curb or combo inlet.
    • ReadSlottedInletData(...)
      Reads data tokens for a slotted drain inlet.
    • ReadCustomInletData(...)
      Reads data tokens for a custom inlet, referencing rating curves, etc.
  3. EditInletDesign(I: Integer): String

    • Launches a UI form (TInletEditorForm) allowing editing of an inlet design in the Project.Lists[INLET].
    • If I < 0, creates a new inlet design; if I >= 0, edits the existing one.
    • Updates name changes, sets the Modified flag.
  4. ExportInletDesigns(S: TStringList)

    • Writes out all inlet definitions in [INLETS] format to a string list S.
    • Breaks out logic for GRATE, CURB, COMBO, SLOTTED, DROP inlets or custom inlets.

3.2 Reading / Writing “Inlet Usage” Data

These handle the [INLET_USAGE] section in an SWMM input file.

  1. ReadInletUsageData

    • Reads tokens from [INLET_USAGE] lines: link ID, inlet ID, node ID, # of inlets, clogging, flow restriction, local depression geometry, etc.
    • Locates the associated TLink, TNode, and TInlet; creates a TInletUsage object stored in theLink.Inlet.
  2. EditInletUsage(Index: Integer; var S: String; var Modified: Boolean): String

    • Invokes the user interface (InletUsageForm) to let the user configure inlet usage for a link Index in the CONDUIT list.
    • Filters out which inlet designs are valid for the link’s cross-section shape (e.g., street cross-section might only allow drop inlet types, or channel shapes might not allow standard curb inlets).
  3. ExportInletUsage(S: TStringList)

    • Writes out data lines in [INLET_USAGE] format for each link that has an associated TInletUsage object.

3.3 Utility Functions

  1. GetInletNode(aLink: TLink): TNode

    • Returns the node that is assigned as the capture node in InletUsage for that link (may differ from link’s Node1 or Node2 depending on local geometry).
  2. GetCaptureNode(aLink: TLink): TNode

    • Looks at the invert elevations of Node1 and Node2 to see which is physically lower or if a user-specified capture node is set.
  3. DeleteInletsByNode(aNode: TNode): Boolean

    • When a node is deleted from the project, any references to that node in an inlet usage must also be freed.
  4. DeleteInletsByType(aInletType: TInlet): Boolean

    • If a user removes an inlet design from the project, all usage references to it must be destroyed.
  5. CheckForValidInlet(aLink: TLink): Boolean

    • Verifies that a link’s cross-section shape is actually compatible with the assigned inlet type.
    • If incompatible, the code frees the TInletUsage object.

4. Typical Workflow

  1. Reading from INP

    • While parsing [INLETS], the parser calls ReadInletDesignData, producing one or more TInlet objects.
    • While parsing [INLET_USAGE], the parser calls ReadInletUsageData, creating or updating TInletUsage references on relevant CONDUIT links.
  2. During Editing

    • The user might open an Inlet Design Editor (EditInletDesign) to add or modify a TInlet.
    • The user might open an Inlet Usage Editor (EditInletUsage) for a given link to specify the # of inlets, clogging fraction, etc.
  3. Writing to INP

    • When saving the model, ExportInletDesigns writes the [INLETS] section, and ExportInletUsage writes [INLET_USAGE].
  4. When Deleting

    • If a node or a specific inlet design is removed, any associated inlets (TInletUsage) get cleaned up in the link database.

5. Conclusion

The Uinlet.pas unit centralizes all inlet design and inlet usage logic within SWMM. It keeps track of:

  • Which inlets are defined (their geometry, type, etc.).
  • How they are used on each conduit link (the capture node, number of inlets, local depressions, or flow restrictions).

Through a set of well-defined read/write methods and user-interface hooks, it ensures consistent modeling of inlet flow capacity within the broader SWMM network.

SWMM5 Delphi GUI Uinifile.pas Summary

 Extended Summary of the Uinifile.pas Unit

The Uinifile.pas unit provides functionality for reading and writing initialization data for the SWMM application. This data includes various preferences, default property values, layout settings, and map/legend configurations. The module handles two main categories of INI files:

  1. The global EPASWMM5.INI file (located in a folder typically called epaswmm5.ini).
  2. A project-specific INI file (which can store or retrieve settings relevant to a particular SWMM project).

Below is a detailed summary of the principal components and routines within the unit.


1. Main Responsibilities

  1. Reading and writing user-interface style and program preferences to the global epaswmm5.ini.
  2. Reading and saving default property values (e.g., default conduit roughness, subcatchment infiltration options, ID label prefixes, etc.).
  3. Remembering the size and position of the Main Form and the Property Editor form.
  4. Managing the map legend defaults (colors, intervals).
  5. Managing MRU (Most Recently Used) project file lists.
  6. Handling calibration data file references, print page setup details, and date/time format preferences.

2. Key Data & Structures

  1. TIniFile objects:

    • Created for reading/writing from/to epaswmm5.ini (the main SWMM INI file).
    • Also used for project-specific .ini files that store per-project settings.
  2. Project Default Properties:

    • The global Project object (in Uglobals) has arrays DefProp[ ] for default properties of each SWMM object type (e.g., SUBCATCH, JUNCTION, CONDUIT, etc.).
    • The unit reads these from [Defaults] sections in an INI file or writes them back.
  3. Window Layout:

    • The top, left, width, and height of the Main Form (MainForm) and the Property Editor (PropEditForm) are read and stored in the INI file.
  4. Graph and Profile Plot Options:

    • The module writes/reads GraphOptions and ProfileOptions to/from the INI file to remember user customizations regarding line styles, colors, grid lines, legend properties, etc.
  5. Map Legends:

    • For subcatchment, node, and link view variables, the user can have color intervals that get loaded/saved.
    • Color arrays, like MapSubcatchColor[], MapNodeColor[], MapLinkColor[], get stored in [Legends] sections.
  6. Calibration:

    • The array CalibData[] (defined in Uglobals) references up to 12 calibration data file paths. These can be saved or retrieved from [Calibration] in the INI file.

3. Major Procedures & Functions

3.1 Reading and Writing the Main SWMM INI File

  1. ReadStyleName

    • Reads the currently used VCL UI style from [Preferences]StyleName.
    • Ensures the style name matches a recognized style in TStyleManager.StyleNames.
  2. ReadIniFile

    • Creates a TIniFile object for epaswmm5.ini.
    • Reads:
      1. Graph options: 3D display, color settings, axis grids, line/point styles, etc.
      2. Profile plot options.
      3. Directories: e.g., DataDir and TempDir.
      4. Preferences: fonts, blinking highlight, confirm delete, auto-backup, etc.
      5. MRU file list.
      6. Property Editor form placement.
      7. Display precision for subcatch/node/link output variables.
  3. SaveIniFile

    • Writes back to epaswmm5.ini:
      1. Graph & ProfilePlot options.
      2. Directories & preferences.
      3. MRU list.
      4. Property Editor coordinates & size.
      5. Display precision for model variables.
  4. ReadMainFormSize / SaveMainFormSize

    • Manage the position, size, and window state of the main SWMM form.

3.2 Handling Program Defaults

  1. ReadDefaults

    • Initializes default property data for objects like subcatchments, junctions, etc. from factory definitions in Uproject (like DefSubcatch, DefJunction, etc.).
    • Then loads any overrides from epaswmm5.ini using the function LoadDefaultsFromFile.
  2. SaveDefaults

    • Uses SaveDefaultsToFile to store the default properties (prefixes, infiltration default, etc.) to epaswmm5.ini.
  3. LoadDefaultsFromFile(theIniFile: TIniFile)

    • A local procedure reading Labels (ID prefixes & increments) and [Defaults] from the TIniFile.
    • Also sets infiltration parameter arrays (Horton, Green-Ampt, etc.) if user changed infiltration in [Defaults].
  4. SaveDefaultsToFile(theIniFile: TIniFile)

    • Writes these default properties back to the given INI file.

3.3 Project-Specific INI Handling

  1. ReadProjIniFile(const Fname: String)

    • If a user has a separate project INI (e.g., myproject.ini), this routine reads map display options (like whether subcatch IDs appear or subcatch polygons are visible), legend color intervals, default infiltration parameters, page layout info (for printing), calibration file references, and more from that file.
  2. SaveProjIniFile(const Fname: String)

    • Saves the same sets of information above into a .ini file next to the project file. This includes:
      • [Map] display settings, [Backdrop] flags, [Legends], [Labels], [Page] layout, [Calibration], [Graph] date/time format, [Results] saved status, etc.

4. Additional Implementation Details

  • InitMapLegends: Called upon reading defaults, assigns factory defaults to color intervals and color arrays for subcatch/node/link legend displays.
  • CheckGraphSeriesOptions: Ensures user-specified line styles or point sizes stay in valid ranges.
  • ExtractValues: Helper that tokenizes a string of numbers (with commas) into floats, storing them in an array. Used for reading the [Legends] intervals.

5. Summary of the Workflow

  1. On startup or closing, the main SWMM form calls ReadIniFile and SaveIniFile to handle global preferences.
  2. When opening a new SWMM project, the user’s project .ini file might be read with ReadProjIniFile.
  3. When saving or closing the project, SaveProjIniFile writes out all current settings for map views, defaults, page layout, etc.
  4. When the user modifies defaults or style in the main UI, the updated settings get stored to the correct place (either the global or project .ini file) so that changes persist between sessions.

Therefore, Uinifile.pas is essentially the preference manager for both the general SWMM environment (the main INI) and for the current project’s specialized settings (the project-level INI).

SWMM5 Delphi GUI Uimport.pas Summary

 Extended Summary of the Uimport.pas Unit

This unit, Uimport.pas, is responsible for importing SWMM project data from a formatted text file (usually the .inp file). It handles lines and tokens read from the file and populates SWMM's internal data structures with subcatchments, nodes, links, pollutants, land uses, pump curves, raingages, etc. It also supports reading older and newer formats for various sections (like older or updated raingage format), and reading optional or legacy sections (like [EVENTS] or [BACKDROP]).

Below is a detailed overview of how the unit works and the responsibilities of its types, variables, and procedures.


1. Overall Purpose

Uimport.pas manages:

  1. Opening a SWMM project file (.inp typically).
  2. Reading each line, splitting into tokens, removing comments, and determining which input section it belongs to (via [RAINGAGES], [JUNCTIONS], [CONDUITS], etc.).
  3. Parsing tokens into SWMM data objects, such as nodes, links, subcatchments, etc. For each recognized section, there is a parser routine (e.g., ReadConduitData, ReadSubcatchmentData) that populates the relevant fields.
  4. Error handling and message reporting if lines have invalid data or references to undefined items.
  5. Post-processing after the entire file is read, such as re-assigning pointers to ID strings, re-calculating subcatchment centroids, adjusting map dimensions, etc.

2. Key Variables and Data Structures

  1. SectionWords: array[0..57]

    • Contains all recognized section keywords in SWMM’s input file (e.g. [RAINGAGES], [JUNCTIONS], [CONTROLS], etc.).
    • The integer index into this array (when a match is found) determines which parser function handles the subsequent lines.
  2. Section: Integer

    • Holds the current input-section index. Initially -1 (no section). Once a line with [ is found, Section is updated.
  3. FileType: TFileType

    • Either ftInput or ftImport. Typically ftInput is used for reading .inp data.
  4. Objects:

    • SubcatchList, NodeList, LinkList: transient string lists used only during the import process if FileType = ftInput. They help quickly look up existing Subcatch/Node/Link objects by name before final pointers are set.
  5. Error Handling:

    • ErrCount, ErrList: counters and list for storing error messages. Up to MAX_ERRORS (50) lines are recorded.
  6. Various:

    • TokList: the token list for the current line being processed.
    • PrevID, PrevIndex: used for lines that continue the same object across multiple lines (e.g., multiple lines describing a single [HYDROGRAPH] or [TIMESERIES] block).

3. Reading the File

3.1 ReadInpFile(const Fname: String): Boolean

  • Attempts to open the file as text, then calls ReadFile (a local procedure) that line-by-line parses:
    1. Removes comment portion.
    2. Checks if line defines a new [SECTION]. If yes, updates Section.
    3. Otherwise, tokenizes the line (TokList, Ntoks) and calls ParseInpLine to handle it, depending on Section.
  • If any references to undefined objects or numeric parse failures occur, an error is appended to ErrList.
  • After reading is done:
    • Calls SetIDPtrs to link each object’s .ID property to the ID string table.
    • Calls SetSubcatchCentroids, SetStorageCentroids to compute polygons' centroids.
    • Calls SetMapDimensions to detect the bounding coordinates for the map.

3.2 ParseInpLine(S: String): Integer

  • Switch statement on Section. Example:
    • If Section = 14, calls ReadConduitData.
    • If Section = 23, calls ReadPollutantData.
    • etc.

3.3 Routines for Each Section

  • For instance, ReadConduitData expects at least 7 tokens:

    1. Conduit ID
    2. From Node ID
    3. To Node ID
    4. Length
    5. Roughness
    6. Inlet Offset
    7. Outlet Offset
    • If references are invalid (can't find node by name), it reports an error.
  • ReadSubcatchmentData similarly expects [SUBCATCHMENT] lines, etc.

  • Many of these are fairly self-contained, returning an error code if not enough tokens appear or if numeric parse fails.


4. Post-Processing

  1. SetMapDimensions: If user-supplied [MAP] or [BACKDROP] sections didn't provide bounding dimensions, the module scans all objects (nodes, subcatch polygons, etc.) to find min/max X & Y for the map.
  2. SetIDPtrs: ensures each subcatch/node/link object’s ID pointer references the actual ID name in the TList object strings.
  3. SetSubcatchCentroids and SetStorageCentroids: compute polygon centroid X/Y if polygon has vertices.

5. Notable Edge Cases / Details

  • Old vs. new format: Some sections (e.g. [RAINGAGES], [HYDROGRAPHS]) have older 4.4/4.5 era formats; ReadOldRaingageData or ReadNewRaingageData handle this.
  • [FILE] section: references external interface files.
  • Deprecated [Import] logic**: not actually used, but placeholders remain.
  • Backdrop: [BACKDROP] lines can define a background image file and coordinate extents. If loaded, SetMapDimensions merges it with the bounding extents of all other objects.
  • Many unrecognized keywords or not enough items produce an error line in ErrList.

6. Startup & Time Setup

  • SetDefaultDates: ensures Start/End/Report date/time entries are valid. If not found in the file or invalid, it uses default or tries to fix them.

7. Summary of Use

When opening a SWMM .inp project file:

  1. The main form calls OpenProject(Fname).
  2. This sets up default map dimension, calls ReadInpFile(...).
  3. ReadInpFile uses ReadFile to parse all lines. Each line leads to a specialized reader routine, storing data in the global Project object.
  4. Errors encountered along the way are accumulated in ErrList. If any exist, a status form displays them.
  5. SetDefaultDates, SetMapDimensions, SetIDPtrs finalize the newly imported data.

Hence, Uimport.pas is central to making user’s textual project files into an in-memory model representation that the SWMM GUI can manipulate.

SWMM5 Delphi GUI Ugraph.pas Summary

 Extended Summary of the Ugraph.pas Unit

This unit, Ugraph.pas, provides general-purpose charting routines for use within EPA SWMM’s Delphi application. It supports creating, configuring, copying, and printing TChart objects and their data series, utilizing the TeeChart library components (TChart, TSeries, etc.). Below is a detailed overview of how each part of this unit fits together.


1. Overall Purpose

Ugraph.pas encapsulates:

  1. Procedures that help configure and initialize various chart properties (axes, legend, colors, etc.) using the global GraphOptions from Uglobals.pas.
  2. Functions that create new data series (e.g. area, line, bar, point) within a TChart.
  3. Routines to copy chart images/data to the clipboard or a file (bitmap, metafile, textual data).
  4. Procedures to print the chart to either a physical printer or a preview form.

2. Key Exposed Procedures and Functions

  1. CopyTo(Chart: TChart)

    • Opens a dialog (TCopyToForm) allowing the user to copy a chart to either a file or the Clipboard in one of three formats:
      • Bitmap (raster)
      • Enhanced Metafile (vector)
      • Text (raw numeric data)
    • Internally calls helper routines (CopyToBitmap, CopyToMetafile, or CopyToString) depending on the user’s choice.
  2. Data Series Creation
    A set of functions that create specific TeeChart series within a given TChart:

    • CreateBarSeries(Chart, Title): creates and configures a TBarSeries.
    • CreateAreaSeries(Chart, Title): creates a TAreaSeries (used for rainfall, typically in a “staired” mode).
    • CreateFastLineSeries(Chart, Title): creates a TFastLineSeries, which is faster for large data sets.
    • CreateLineSeries(Chart, Title): creates a standard TLineSeries.
    • CreatePointSeries(Chart, Title): creates a TPointSeries that draws discrete points.

    Each of these sets up the series with basic properties (e.g. color, visible in legend, pointer style, etc.) and references GraphOptions to stay consistent with the user’s global preferences.

  3. InitGraphOptions(Chart: TChart)

    • Applies the global GraphOptions to the chart. This includes whether it’s 3D, background color, legend style, axis styles, fonts, and so on.
    • Also calls an internal helper InitAxisOptions for each axis (bottom, left, right) to set up grid style, font properties, etc.
  4. Print(Chart, thePrinter, Destination)

    • Renders the chart to a TPrintControl object, which can go to the system printer or to a preview form.
    • Creates an internal Metafile of the chart, fits it to the page, and sends it through thePrinter.
  5. SetGraphOptions(theChart, var startPage, theForm)

    • Opens a Chart Options dialog (from Dchart.pas) where the user can adjust line styles, point styles, axis settings, etc.
    • On success, merges the user’s changes back into GraphOptions and optionally saves them as new defaults if the user requests it.

3. Internal Helper Procedures

  1. CopyToBitmap(Fname, Chart) and CopyToMetafile(Fname, Chart)
    • If Fname is non-empty, the chart is saved to a file. Otherwise, it’s copied to the Windows Clipboard in the respective format.
  2. CopyToString(Fname, Chart)
    • Extracts X-Y data from the chart’s series into a tab- or space-delimited text.
    • If Fname is empty, it places the text on the Clipboard; otherwise, it writes to disk.
    • Handles single series vs. multiple time series, calibration data sets, etc.
  3. InitLineSeriesOptions, InitAreaSeriesOptions, InitFastLineSeriesOptions
    • Apply color, pen styles, pointer visibility, etc., to each series, referencing arrays from GraphOptions.
  4. SaveDefaultOptions(Chart, UseDefaultPanelColor)
    • Called if the user wants to make the updated chart settings the new “application defaults.”
    • Updates the global GraphOptions so future new charts adopt those styles automatically.

4. Data Structures

4.1 Data Series Classes

  • TBarSeries: draws columns for data. Typically for histograms.
  • TAreaSeries: area under a line, used in SWMM for e.g. rainfall bars.
  • TFastLineSeries: optimized line series for large data.
  • TLineSeries: standard line graph.
  • TPointSeries: for discrete scatter plots or calibration data sets.

4.2 Global GraphOptions (from Uglobals)

  • The InitGraphOptions, InitLineSeriesOptions, etc. all read from the global GraphOptions. The user can update GraphOptions via a chart options dialog, or revert to previously saved defaults.

5. Summary of Use

  1. Creation: Another unit can call CreateLineSeries(...) or CreateBarSeries(...) to add a data series to a TChart.
  2. Initialization: Once the series are created, InitGraphOptions(Chart) configures the chart’s background, legend, axes, etc.
  3. User Adjustments: The user can open a Chart Options dialog by calling SetGraphOptions(...), and the new settings are loaded into GraphOptions.
  4. Output: The chart can be:
    • Copied to a file or clipboard (CopyTo(Chart)).
    • Printed or previewed (Print(Chart, thePrinter, Destination)).

Hence, Ugraph.pas is a utility for standard charting operations, bridging user preferences (GraphOptions) and the various TeeChart components used throughout SWMM’s GUI.

SWMM5 Delphi GUI Uglobals.pas Summary

 Extended Summary of Uglobals.pas

This unit, Uglobals.pas, serves as a central module for the SWMM application, defining global (i.e., application-wide) constants, types, and variables. Many other units rely on these definitions. Below is an in-depth explanation of the unit’s contents and how they are used.


1. Purpose and Scope

Uglobals.pas defines:

  1. Object categories and ID ranges used in SWMM (e.g., SUBCATCHMENTS, NODES, LINKS, etc.).
  2. Map and graphical display constants (e.g., for colors, cursors, legend indexes).
  3. Basic data structures:
    • TMapLegend**TMapLegend**: for storing the intervals and type of the color legend on the map.
    • TGraphOptions**TGraphOptions**: user preferences for plot displays (e.g., line colors, axis fonts, 3D layout).
    • TProfileOptions**TProfileOptions**: user preferences for profile plots.
    • TReportSelection**TReportSelection**: structure describing a table or plot selection.
    • And others for storing user preferences (e.g., PageLayout, TCalibData, TRunStatus, etc.).
  4. Global variables used throughout SWMM**:**
    • Program-level preferences (e.g., StyleName, Blinking, AutoLength, ShowStartPage).
    • Paths / directories in use (ProjectDir, TempDir, etc.).
    • The main SWMM Project instance (with references to all objects).
    • Simulation results summary info (Nperiods, RunFlag, etc.).

2. Key Sections

2.1 Object Category and SWMM Version Ranges

  • The integer constants VERSIONID1 = 51000 and VERSIONID2 = 52004 define the earliest and latest SWMM 5 version formats the program can parse without error.
  • TXT_SUBCATCH, TXT_NODE, TXT_LINK, TXT_SYS are textual labels for certain object categories.

2.2 Global Constants

  1. File names: INIFILE, HLPFILE, etc.
  2. Map appearance: typical color sets, symbol sizes, arrow style enumerations, etc.
  3. Measurement units: arrays for flow units (US vs. SI), mass units, temperature units, etc.
  4. Default geometry or numeric tolerances: e.g. FLOWTOL = 0.005 for zero-flow tolerance, MISSING = -1.0e10 as a missing-value sentinel, etc.

2.3 Data Structures

2.3.1 TMapLegend

  • Keeps track of color intervals for subcatchment, node, or link color displays on the map.
  • Has an array Intervals[0..MAXINTERVALS] for color intervals and the number of intervals used, plus references to “ViewVar” (the SWMM variable being visualized) and “Ltype” (subcatch, node, link).

2.3.2 TGraphOptions

  • A record capturing user preferences for generating time-series plots (line colors, thickness, styles, background color, 3D display, legend styles, etc.).

2.3.3 TProfileOptions

  • Used for profile plots.
  • Holds colors for water fill, conduit line, labels, etc.

2.3.4 TReportSelection

  • Describes how data will be reported in tables/plots, which variables are selected, date range, list of items, etc.

2.3.5 TPageLayout

  • Tracks printed page layout: margins, orientation, page size, etc.

2.4 Global Variables

  1. GUI Preferences

    • Blinking: Are map hilighters blinking?
    • FlyOvers: Show map “flyover” tips.
    • AutoLength: Whether pipe lengths are auto-computed from node coordinates.
    • BoldFonts, LargeFonts, StyleName: affect the UI theme.
  2. Project Database

    • Project (type TProject): the main container for all SWMM objects.
    • CurrentObject: the category currently selected in the UI.
    • UnitSystem (e.g., usUS or usSI).
    • FlowUnits: the textual representation of flow (CFS, CMS, etc.).
  3. File Paths

    • HomeDir, ProjectDir, TempDir, IniFileDir, etc.
    • InputFileName, TempInputFile, TempReportFile, TempOutputFile.
  4. Analysis Results

    • RunFlag: indicates if a successful run is loaded.
    • Nperiods: total number of time steps in output.
    • Zsubcatch, Znode, Zlink: arrays storing the current color-coded variable values for subcatchments, nodes, and links.
    • FlowDir: array for flow directions.
  5. Calibration Data

    • CalibData[1..12]: Holds info about any calibration data files, referencing the 12 possible measurement types (rainfall, flow, depth, etc.).
  6. Program Startup

    • StartupFile, StartupAction, MRUList: the “most recently used” file list, the file to open on startup, etc.

2.5 Key Procedures/Functions

  1. GetStartupAction

    • Shows a “Welcome” form so the user can select an action (e.g., “New Project,” “Open Project,” etc.).
    • The form sets StartupAction and StartupFile.
  2. ReadCmdLine

    • Checks for command-line switches like /f, meaning “open the specified file at startup,” or /s to override the directory for storing the .ini settings.
  3. GetObject(ObjType, S)

    • From an object category (SUBCATCHMENTS, NODES, LINKS, etc.) and an ID string, returns the matching SWMM object instance in the Project.
  4. GetObjVarNames(ObjType, VarIndex, ObjName, VarName, VarUnits)

    • Given an object type and variable index (like “FLOW” for a link), it sets out parameters describing object type name, variable name, and measurement units.
  5. RegisterCalibData

    • Reads each calibration data file path from CalibData[] and attempts to parse the known “location” IDs inside it.
  6. SetDirectories, SetFormatSettings

    • Initialize various directory paths (where the .ini or .exe is located) and numeric/time format properties so that SWMM uses consistent date/time/decimal formats.
  7. SetMapBackColors

    • Provides a series of default background color choices for the study area map.
  8. GetPeriod

    • Given a “date index” (days from start), returns the reporting period integer for that date.

3. Typical Usage by Other Units

  1. Fmain.pas references Uglobals extensively for checking/updating the global Project, and to read/write to the same global variables controlling program settings.
  2. Fmap.pas and others rely on Zsubcatch, Znode, Zlink, FlowDir to color and animate the map.
  3. Uinlet.pas, Uclipbrd.pas, etc. also rely on Project, UnitSystem, MapLegend, or TempDir.

4. Conclusion

Uglobals.pas is the foundation of SWMM’s data orchestration, holding:

  • All constants describing categories, measurement units, maximum sizes, etc.
  • Data structures for user options, plotting, legends, and more.
  • Global variables that other modules rely on for status, file paths, or references to the main TProject.

Because these variables and types are used across almost all modules, Uglobals is typically included in every major SWMM unit.

SWMM5 Delphi GUI Uexport.pas Summary

 Extended Summary for Uexport.pas

The Uexport.pas unit plays a central role in exporting the current SWMM project’s data into a formatted text file (or equivalently, into a TStringList). The data it exports includes:

  1. Main project data (subcatchments, nodes, links, infiltration parameters, pollutants, land uses, etc.).
  2. User options and simulation parameters (simulation dates, time steps, infiltration model, etc.).
  3. Additional items such as control rules, time series, curves, map coordinates, and even user-defined events.

It also handles special “save” tasks such as writing out a hotstart file or partial sets of results.


1. Responsibilities of the Unit

The Uexport unit provides a series of helper methods to write:

  • Project Setup: [TITLE], [OPTIONS], [FILES], [EVAPORATION], [TEMPERATURE]
  • Rain Gages: [RAINGAGES]
  • Subcatchment-Related Data: [SUBCATCHMENTS], [SUBAREAS], [INFILTRATION], [SNOWPACKS], [GROUNDWATER], etc.
  • Node & Link Data: [JUNCTIONS], [OUTFALLS], [DIVIDERS], [STORAGE], [CONDUITS], [PUMPS], [ORIFICES], [WEIRS], [OUTLETS], [XSECTIONS], [STREETS], [INLETS], [LOSSES], etc.
  • Pollutant & Land Use: [POLLUTANTS], [LANDUSES], [BUILDUP], [WASHOFF], etc.
  • Water Quality: [TREATMENT] for node-level pollutant treatment equations.
  • Inflows: [INFLOWS], [DWF], [RDII], etc.
  • Hydrographs & Time Series: [HYDROGRAPHS], [TIMESERIES], [PATTERNS], [CURVES]
  • Controls & Reporting: [CONTROLS], [REPORT]
  • Map Data: [MAP], [COORDINATES], [VERTICES], [Polygons], [SYMBOLS], [LABELS], [BACKDROP]
  • Adjustment factors: [ADJUSTMENTS] for monthly climate adjustments.
  • Optional: [EVENTS] if the user is using the event analysis feature.
  • Additional: [TAGS] for object tags, and [PROFILES] for user-created profile plots.

The unit also defines:

  • SaveProject(Fname): Writes the entire SWMM input file for the current project to a file Fname.
  • SaveResults(Fname): Renames and saves a run's [REPORT] & [OUTFILE].
  • SaveHotstartFile(Fname): Writes hotstart data (current flow and depths, etc.) to a binary file.
  • RelativePathName(Fname): Converts an absolute file path to a path relative to the directory of the saved project file.

2. Key Data and Helper Routines

2.1 Internal Variables

  • Tab: A string that holds either a tab character or a single space, depending on whether the user wants a tab-delimited or spaced-delimited format.
  • SaveToPath: The directory path to which the project file is being saved. Used to produce “relative” paths for external files.
  • DXFCount, DWFCount, RDIICount, TreatCount: Counters used to track how many nodes have external inflows, dry-weather flows, RDII flows, or treatment definitions. This guides whether to export [INFLOWS], [DWF], [RDII], [TREATMENT] sections.

2.2 Modularity

Each major SWMM input section ([JUNCTIONS], [CONDUITS], [STORAGE], etc.) has its own procedure:

  • ExportTitle -> [TITLE]
  • ExportOptions -> [OPTIONS]
  • ExportRaingages -> [RAINGAGES]
  • ExportSubcatchments, ExportSubAreas, ExportInfiltration, …
  • ExportJunctions, ExportOutfalls, …, etc.

The pattern is consistent: build a header line with S.Add(...), then loop through the relevant items in Project.Lists[...], generating lines of data. Comments are also exported for each object using ExportComment(...).

2.3 Project-Wide Exports

  1. ExportProject(S, P): The main aggregator that calls each individual export subroutine in a specific order, building a complete SWMM input file in the stringlist S.

  2. ExportMap(S): Exports map geometry data such as [COORDINATES] for each node, [VERTICES] for each link, [Polygons] for subcatchments, [LABELS] for map labels, etc.

  3. SaveProject(Fname):

    • Creates a TStringList.
    • Calls ExportProject to add all text lines.
    • Appends [TAGS], [MAP], [PROFILES].
    • Saves the final text to Fname.
    • If Fname has a .ini extension, also writes certain layout data with Uinifile.SaveProjIniFile.

2.4 Output & Intermediate Files

  • Temporary: The code references TempReportFile and TempOutputFile—where the engine run results might have been stored. SaveResults(Fname) tries to rename these to permanent names (like *.rpt, *.out) if possible.

  • Hotstart: The SaveHotstartFile(Fname) function writes out flow depths, water levels, etc., to a binary file in a special format for a subsequent run to be initialized with.

    • It writes the # of subcatchments, nodes, links, & pollutants, plus unit info, plus current state for each subcatchment, node, & link.

3. Typical Flow

  1. User selects “File -> Save As” for a SWMM project.
  2. SaveProject(Fname) is called.
  3. Internally, a new TStringList is created and passed to ExportProject.
  4. ExportProject calls each subordinate ExportXxx procedure in the recommended SWMM input order, building up a final text representation.
  5. The final text is saved to disk as an *.inp file, and possibly an .ini file is created with some UI-specific details.

Additionally, “File -> Save Results” might call SaveResults(Fname), which manipulates the previously generated “temporary” output and report files.


4. Notable Implementation Details

  • The code is mindful of whether a user has set output objects to “No” results, so many references to Uoutput or counters like DXFCount detect if a section is actually needed.
  • The routine RelativePathName(Fname) ensures that external references (like a time series file, or a rain data file) are given relative to the project file’s folder if possible, to make the project file more portable.
  • Many small labeling procedures ensure the formatting is consistent with SWMM’s expected column widths, like Format('%-16s', [...]), Tab + Format('%-10s', [...]), etc.

5. Conclusion

Uexport.pas collects all project data and organizes it into the standard SWMM text input format. Each object category has its own dedicated procedure that reads from the project database, writes to an output TStringList, and can optionally handle advanced features like infiltration models, external inflows, or special shapes. This design provides a straightforward, structured approach to exporting a complete SWMM model file.

SWMM5 Delphi GUI Uedit.pas Summary

 Extended Summary for Uedit.pas

This Delphi Pascal unit, Uedit.pas, provides a set of procedures and functions to create and edit objects in an EPA SWMM project. These objects include rain gages, subcatchments, nodes (junctions, outfalls, dividers, storage units), links (conduits, pumps, weirs, outlets, orifices), labels, and non-visual entities (pollutants, land uses, infiltration parameters, etc.). The code orchestrates calls to specialized dialog forms for editing or adding new data, and it updates the project database as well as the visual map and data browser.


1. Purpose & Scope

  • Manage object creation within the SWMM project database:

    • Subcatchments, nodes, links, labels, and some specialized node/link types.
  • Provide editor entry points to modify existing objects, typically by showing specialized dialog forms or the general property editor.

  • Integration Points:

    1. Map: If an object is visual (like a subcatchment or node), it gets drawn on the map or erased/redrawn when edited.
    2. Browser: Data items in the project’s list of objects also appear in the Browser panel; adding a new item calls BrowserAddItem, removing calls BrowserDeleteObject, etc.
    3. Dialogs: For certain object types, specialized forms or the property editor (e.g., PropEditForm) are invoked.

2. Major Functional Blocks

2.1 Adding Objects

  1. AddGage(X, Y)
    Creates a rain gage with coordinates X,Y`X, Y`. Chooses a default ID, uses default properties, and adds it to the project list Project.Lists[RAINGAGE]. Then draws it on the map.

  2. AddSubcatch(PointList, N)
    Creates a subcatchment polygon from an array of screen points (TPoint), converts to map coordinates, and stores them in the subcatchment's vertex list. The bounding center is computed, and an ID is assigned. Then draws on the map and updates the Browser.

  3. AddStorage(PointList, N)
    Creates a storage node with a polygon outline. The node's actual X,Y is set to the polygon centroid. A simpler version of AddNode(...).

  4. AddLink(Ltype, Node1, Node2, PointList, N)
    Creates a link (conduit, pump, orifice, etc.) connecting two known node objects. Intermediate points in PointList become the link’s vertex list. The object is drawn on the map and added to the Browser.

  5. AddNode(Ntype, X, Y)
    Creates a node of type (junction, outfall, divider, storage). Assigns default properties, sets X, Y, and draws it.

  6. AddLabel(X, Y, S)
    Creates a map label at (X, Y) with text S. Draws the label on the map.

  7. AddNonVisualObject(ObjType)
    If the user wants to add something like a pollutant, pattern, or curve, this calls the corresponding specialized editor. If the user completes that dialog, the new object is inserted in the relevant list.


2.2 Editing Objects

Most objects can be edited through either the property editor or specialized forms.

  1. EditRaingage(Index)

    • Loads the raingage data into PropList.
    • Presents them in PropEditForm with RaingageProps.
  2. EditSubcatch(Index)

    • Loads subcatchment data (area, width, outlet, infiltration, etc.) into PropList.
    • Uses SubcatchProps in PropEditForm.
  3. EditNode(Ntype, Index)

    • For a junction, outfall, divider, or storage node, populates PropList with the relevant data, sets up the property editor with JunctionProps, OutfallProps, etc.
  4. EditLink(Ltype, Index)

    • For a conduit, pump, orifice, weir, or outlet link, populates PropList.
    • Some fields (like max. depth or roughness) may be disabled (esReadOnly) depending on shape or cross-section type.
  5. EditLabel(Index)

    • Shows label’s text, position, anchor node, etc., in PropList.
  6. EditNodalInflows(ObjType, Index, S, Modified)

    • Creates a specialized TInflowsForm to handle dry-weather, direct, and RDII inflows to a node.
  7. EditTreatment(ObjType, Index, S, Modified)

    • Creates a specialized TTreatmentForm to define pollutant removal equations at a node.
  8. EditXsection(ObjType, Index, S, Modified)

    • For a link’s cross section geometry. If the shape is “Street” or “Irregular,” the user must switch to a different form. Typically calls TXsectionForm.
  9. EditStorageInfil(Index, S, Modified)

    • A storage node’s infiltration parameters. Uses TInfilForm with fewer fields.
  10. EditLoadings(Index, S, Modified)

    • Edits initial pollutant loads on a subcatchment. Uses TInitLoadingsForm.
  11. EditSubLanduses(Index, S, Modified)

    • Subcatchment land uses & percentages. If no land uses exist, an info message is shown.
  12. EditGroundwater(Index, S, Modified)

    • Subsurface flow parameters for a subcatchment. Calls TGroundWaterForm.
  13. EditComment(Title, S, Modified)

    • General comment field editor.
  14. EditRainFileName(Index, S, Modified)

    • Opens a file open dialog for selecting a rain data file. Replaces the path in the raingage’s property.
  15. EditCurve(ObjType, Index)

    • Edits a curve object (pump curve, rating curve, etc.). If Index<0, it’s a new curve.
  16. EditTimeseries(Index)

    • Edits a time series object. If Index<0, creates a new one.
  17. EditHydrograph(Index)

    • Edits an RDII unit hydrograph. If new, Index<0.
  18. EditStreet(Index)

    • Edits a street cross section shape definition.
  19. EditInletDesign(Index)

    • Edits a street inlet definition.
  20. EditInletUsage(Index, S, Modified)

    • Edits how a link’s inlet is used (in the code, it references DinletUsage).
  21. EditTransect(Index)

    • Channel cross-section shapes. If new, Index<0.
  22. EditPattern(Index)

    • Time patterns (daily, monthly, hourly, etc.).
  23. EditOptions

    • Edits global simulation options with TAnalysisOptionsForm.
  24. EditNotes

    • Edits the global “Title/Notes” with TNotesEditorForm.
  25. EditControls(Index)

    • Rule-based control statements (open the “ControlsForm”).

2.3 Updating Editor & Map

  • UpdateEditor(ObjType, Index):
    Re-loads the property editor contents for a specific object. If the property editor is visible, calls the relevant “EditXxxx(...)” routine.
  • SetConduitDepthField & SetConduitRoughnessField:
    For a conduit link, sometimes the geometry is from a Street or Irregular shape. Those fields become read-only. The geometry’s depth or roughness is derived from the street or transect object.

3. Key Data Structures

  1. TNode: For junctions, outfalls, etc.

    • Has Data[...] array for properties, X, Y coordinates, infiltration, etc.
  2. TLink: For conduit/pump/weir/outlet.

    • Has Data[...] array, references to Node1 & Node2, a vertex list, etc.
  3. TSubcatch:

    • Has Data[...] array, infiltration properties, polygons in Vlist.
  4. TRaingage:

    • Data[...] for gauge definition, plus X, Y.
  5. Project.Lists[...]:

    • The database for each object category. E.g., Project.Lists[RAINGAGE], Project.Lists[CONDUIT].
  6. PropList:

    • A shared string list that the property editor uses.

4. Workflow Examples

Adding a Subcatchment

  1. User draws polygon.
  2. Code calls AddSubcatch(PointList, N).
  3. A TSubcatch object is created, given a new ID, polygon vertex coords, then added to Project.Lists[SUBCATCH].
  4. MapForm.DrawObject(SUBCATCH, I) draws it, and Ubrowser.BrowserAddItem(SUBCATCH, I) updates the Browser.

Editing a Conduit

  1. User selects a conduit in the Browser or on the map, calls EditLink(CONDUIT, Index).
  2. PropEditForm is loaded with conduit properties, including its shape, max depth, length, etc.
  3. If the user changes shape to “Street,” the code sets certain fields read-only and updates geometry from the street object.
  4. If user hits OK, changes are validated & saved, the map is redrawn if necessary, and HasChanged is set.

5. Conclusion

Uedit.pas is central to enabling both the addition and modification of all objects in an EPA SWMM project. It either opens a specialized dialog (if one is required) or uses the universal property editor for simpler objects. After changes, it ensures that the map and Browser remain in sync, and that the underlying SWMM data structure is updated properly.