Программа TMCGROUT — API-документация
Пакет TMC Suite. Вьювер графиков частотных характеристик матрицы рассеяния (S-параметров): КСВН, потери (dB), модуль и фаза элементов S-матрицы. Язык документации: русский. Все сигнатуры приведены по исходникам из
src/viewers/Tmcgrout/и общим заголовкам изsrc/Include/.
1. Назначение программы
TMCGROUT (выходной EXE — TMCGROUT.exe) — графический просмотрщик результатов электродинамического расчёта: строит 2D-графики частотных характеристик многополюсника по данным из S-файлов (матриц рассеяния, читаются библиотекой SFILE95).
Программа построена по классической схеме MFC Document/View (приложение типа MDI — многодокументный интерфейс). Каждый документ — это текстовый файл с расширением .soc (формат TMCGROUT), который описывает набор графиков: для каждого графика указывается имя S-файла, номера входов/мод элемента S-матрицы и подпись. Программа умеет:
- открывать
.soc-документы или напрямую.s/.s2p/.s4p/… файлы матриц рассеяния (для них автоматически создаётся.soc-документ); - строить до 20 графиков в одном документе, каждый своим цветом/типом/толщиной линии;
- для каждого графика выбирать тип Y (КСВН, потери в дБ, модуль |S|, фаза в градусах/радианах) и тип X (частота в Гц/кГц/МГц/ГГц или пользовательская единица);
- вычислять графики по выражениям над несколькими S-файлами (синтаксис
{...[файл]...}, разбор — классCTMCGrExpression, вычисление — библиотека exprint); - масштабировать (zoom мышью и через меню), автоподбор пределов по X/Y, прокрутку Home/End;
- настраивать цвета (фон, сетка, оси, точки, графики), шрифт подписей;
- сохранять параметры окна и оформления в реестре (HKCU\…\TMCGROUT) и в самом
.soc-файле; - запускать внешний редактор (по умолчанию
winword.exe) для документа; - следить за временем изменения файлов и перечитывать данные при изменении (таймер).
2. Состав проекта
В сборку TMCGROUT.vcxproj входят следующие файлы .cpp/.h:
| Файл | Класс / содержимое | Назначение (кратко) |
|---|---|---|
TMCGROUT.cpp/.h |
CTMCGROUTApp |
Класс приложения, InitInstance, шаблон документа, диалог «О программе» |
MainFrm.cpp/.h |
CMainFrame |
Главное MDI-окно: тулбар, статусбар, сохранение позиции окна |
ChildFrm.cpp/.h |
CChildFrame |
Дочернее MDI-окно документа |
TMCGROUTDoc.cpp/.h |
CTMCGROUTDoc |
Документ: чтение/запись .soc, загрузка S-данных, параметры графиков |
TMCGROUTView.cpp/.h |
CTMCGROUTView |
Вид: вся отрисовка графиков, осей, сетки, обработка мыши и меню |
TMCGROUTDIALOGView.cpp/.h |
CTMCGROUTDIALOGView |
Диалог параметров графика (пределы, единицы, формат, точки) |
DialogDoc.cpp/.h |
CDialogDoc |
Диалог-таблица содержимого документа (до 20 графиков) |
TmcGroutColorGraphDialog.cpp/.h |
CTmcGroutColorGraphDialog |
Диалог настройки цвета/типа/толщины линий 16 графиков |
TmcGrParColTypWid.cpp/.h |
CTmcGrParColTypWid |
Диалог выбора цвета/стиля/толщины одной линии |
TMCGrExpression.cpp |
CTMCGrExpression |
Разбор и вычисление выражений-графиков (заголовок — общий, в src/Include) |
StdAfx.cpp/.h |
— | Прекомпилированный заголовок MFC |
resource.h, TMCGROUT.rc |
— | Ресурсы (меню, диалоги, иконки, тулбар) |
Зависимости: MFC (UseOfMfc — общая/статическая), общие заголовки src/Include/ (Tmcgrviw.h, TMCGrExpression.h, Proc_s.h, complex1.h, inter.h, typedef.h), а также библиотеки пакета: SFILE95 (чтение S-матриц — read_S_matrix_element), complex (cabsv, cphase), exprint (i1nte_atof_1 из inter.h — вычисление выражений).
3. Общие структуры данных (заголовок Tmcgrviw.h)
Программа хранит данные графиков в структурах, объявленных в общем заголовке src/Include/Tmcgrviw.h. Эти структуры — основа модели данных TMCGROUT.
3.1. TMC_GR_DOC1 — один график (в документе)
typedef struct {
int nPoint; // число точек графика
double dFreq; // частота (для временного массива)
double *pFreq; // массив частот
_complex *pSmatr; // массив комплексных значений элемента S-матрицы
CTMCGrExpression *pcExpr;// указатель на класс-выражение (если график задан выражением)
int nInp1; // номер входа 1
int nMod1; // номер моды входа 1
int nInp2; // номер входа 2
int nMod2; // номер моды входа 2
char *szFileName; // полное имя S-файла (с путём)
char *szGrapName; // имя графика (имя S-файла или текст выражения)
char *szGrapPodp; // подпись графика в легенде
int LineColor; // цвет линии (COLORREF)
int LineType; // стиль линии (PS_SOLID/PS_DASH/…)
int LineWidth; // толщина линии
TMC_INT_POINT piPoint[TMC_GROUT_POINT_TYPE]; // 10 точек формы маркера
int PointColor; // цвет маркера
int PointType; // стиль маркера
int PointWidth; // толщина маркера
int OutFlag; // флаг вывода графика на экран (TRUE/FALSE)
FILETIME LastWriteTime;// время последней записи S-файла
} TMC_GR_DOC1;
| Поле | Тип | Назначение |
|---|---|---|
nPoint |
int |
Число частотных точек графика |
pFreq |
double* |
Массив частот (Гц), длина nPoint |
pSmatr |
_complex* |
Массив комплексных S-значений, длина nPoint |
pcExpr |
CTMCGrExpression* |
Если ≠ NULL — график вычисляется по выражению, а не из одного файла |
nInp1/nMod1/nInp2/nMod2 |
int |
Адрес элемента S-матрицы (вход/мода вход/мода) |
szFileName |
char* |
Полный путь к S-файлу |
szGrapName |
char* |
Имя графика (имя файла или текст {...}-выражения) |
szGrapPodp |
char* |
Подпись (легенда); при ошибке чтения сюда пишется Error_... |
LineColor/LineType/LineWidth |
int |
Параметры линии |
piPoint[10] |
TMC_INT_POINT[] |
Координаты вершин маркера точки (форма символа) |
OutFlag |
int |
Рисовать график или нет |
LastWriteTime |
FILETIME |
Контроль изменений файла |
3.2. TMC_GR_DOC — документ целиком
typedef struct {
int nGraph; // число графиков в документе
TMC_GR_DOC1 *psGraph; // массив графиков
BOOL nAFlagX; // авто-масштаб по X (TRUE — автоподбор)
BOOL nAFlagY; // авто-масштаб по Y
BOOL PointDrawFlag;// рисовать ли маркеры точек
int nYType; // тип Y-координаты (см. константы)
int nXType; // тип X-координаты
double Xmin, Xmax; // пределы по X
double Ymin, Ymax; // пределы по Y
FILETIME LastWriteTime;// время записи файла документа
} TMC_GR_DOC;
3.3. TMC_GR_VIEW, TMC_GR_WINDOW — данные вида
TMC_GR_VIEW хранит точки одного графика в двух системах координат — вещественной (pPoint, тип TMC_POINT{double x,y}) и логической экранной (piPoint, тип TMC_INT_POINT{int nX,nY}).
typedef struct {
int nPoint; // число точек
int nPointDraw; // число реально рисуемых точек (в пределах окна)
TMC_POINT *pPoint; // вещественные координаты
TMC_INT_POINT *piPoint; // логические (экранные) координаты
} TMC_GR_VIEW;
TMC_GR_WINDOW — состояние области рисования вида: вещественное окно sGrWin (TMC_GR_WINDOW_D — Xmin/Xmax/Ymin/Ymax, флаги nAFlagX/nAFlagY), целочисленный вьюпорт sGrView (TMC_GR_VIEWPORT — nXmin/nXmax/nYmin/nYmax), типы осей nXType/nYType, число графиков nGraph, флаг точек PointDrawFlag, массив psGraph.
3.4. TMC_GR_TYPE_X, TMC_GR_TYPE_Y — описание типа оси
typedef struct { int nType; char pszXname[100]; } TMC_GR_TYPE_X;
typedef struct { int nType; char pszYname[100]; } TMC_GR_TYPE_Y;
Пара «код типа + текст подписи оси».
3.5. Константы типов графика (Tmcgrviw.h)
| Константа | Значение | Смысл (ось Y) |
|---|---|---|
TMC_GR_TYPE_WSVR |
0 | КСВН (VSWR) |
TMC_GR_TYPE_L |
1 | Потери, дБ (-20·lg|S|) |
TMC_GR_TYPE_SM |
2 | Модуль |S| |
TMC_GR_TYPE_SFR |
3 | Фаза S, радианы |
TMC_GR_TYPE_SFD |
4 | Фаза S, градусы |
| Константа | Значение | Смысл (ось X) |
|---|---|---|
TMC_GR_TYPE_FGHz |
0 | Частота, ГГц |
TMC_GR_TYPE_FMHz |
1 | Частота, МГц |
TMC_GR_TYPE_FKHz |
2 | Частота, кГц |
TMC_GR_TYPE_FHz |
3 | Частота, Гц |
TMC_GR_TYPE_F_USER |
4 | Пользовательская единица (имя и множитель задаёт пользователь) |
| Константа | Значение | Смысл |
|---|---|---|
TMC_GROUT_DOCFILE_ID |
"#TMCGROUT" |
Метка-сигнатура файла документа .soc |
TMC_GROUT_MAXSTRING_BUF |
10000 | Размер строкового буфера |
TMC_GROUT_POINT_TYPE |
10 | Число вершин в форме маркера точки |
TMC_GROUT_POINT_TYPE_X/Y |
400 | Базовый размер маркера по X/Y |
TMC_VIEW_XSIZE/YSIZE |
18000 | Логический размер области рисования |
TMC_VIEW_SIZEMODE |
MM_HIMETRIC |
Режим отображения (метрический) |
Кроме того, заголовок содержит набор #define-идентификаторов секций файла документа (TMC_GROUT_DOCFILE_ID_Xmin, …_nXType, …_sDrawTextFont и т.п.) — это текстовые префиксы строк .soc-файла, по которым CTMCGROUTDoc::SetOneReadGraphParameters распознаёт параметры.
4. Класс CTMCGROUTApp
Назначение: класс приложения MFC. Инициализирует программу, регистрирует шаблон документа, открывает последний файл, восстанавливает положение главного окна.
Заголовок: TMCGROUT.h
Базовый класс: CWinApp.
Методы
CTMCGROUTApp()
Конструктор. Значимая инициализация вынесена в InitInstance.
BOOL InitInstance()
Что делает: точка входа приложения.
Как работает:
1. AfxOleInit() — инициализация OLE/COM (нужна для Shell-вызовов в CRecentFileList на Windows 7+; часть исправления бага краша при открытии файла);
2. SetRegistryKey("TMCGROUT") — хранить настройки и список последних файлов (MRU) в реестре HKCU, а не в WINDIR\TMCGROUT.INI;
3. Enable3dControls(), LoadStdProfileSettings(9) — стандартная инициализация MFC, загрузка MRU (9 файлов);
4. регистрирует CMultiDocTemplate (документ CTMCGROUTDoc + дочернее окно CChildFrame + вид CTMCGROUTView, ресурс IDR_TMCGROTYPE);
5. создаёт главное окно CMainFrame;
6. если командная строка пуста — перебирает список MRU и открывает первый существующий файл;
7. восстанавливает положение главного окна из профиля (ключ #INIWND);
8. показывает окно (SW_RESTORE).
Возвращает: TRUE при успехе, FALSE при ошибке создания окна.
afx_msg void OnAppAbout()
Показывает модальный диалог «О программе» (CAboutDlg, ресурс IDD_ABOUTBOX).
Глобальный объект: CTMCGROUTApp theApp; — единственный экземпляр приложения.
Вложенный класс CAboutDlg (объявлен в TMCGROUT.cpp) — простой диалог «О программе» без обработчиков.
5. Класс CMainFrame
Назначение: главное MDI-окно приложения. Содержит панель инструментов и строку состояния.
Заголовок: MainFrm.h
Базовый класс: CMDIFrameWnd.
Поля
| Поле | Тип | Назначение |
|---|---|---|
m_wndStatusBar |
CStatusBar |
Строка состояния (2 панели: координаты мыши и текущий тип графика) |
m_wndToolBar |
CToolBar |
Панель инструментов |
Методы
int OnCreate(LPCREATESTRUCT)
Создаёт тулбар (IDR_MAINFRAME) и статусбар (2 индикатора-разделителя), включает докинг и подсказки. Возвращает 0 при успехе, -1 при ошибке.
BOOL PreCreateWindow(CREATESTRUCT& cs)
Задаёт стиль окна (разворачивается на весь экран — WS_MAXIMIZE).
void OnDestroy()
При закрытии сохраняет положение главного окна (если SW_SHOWNORMAL) в профиль реестра под ключом #INIWND (формат «left right top bottom»).
Строка состояния заполняется глобальными функциями
PutTrace/PutStatistics(см. раздел 11).
6. Класс CChildFrame
Назначение: дочернее MDI-окно, в котором живёт вид документа.
Заголовок: ChildFrm.h
Базовый класс: CMDIChildWnd.
BOOL PreCreateWindow(CREATESTRUCT& cs)
Задаёт стиль дочернего окна (по умолчанию развёрнуто — WS_MAXIMIZE). Других обработчиков класс не содержит.
7. Класс CTMCGROUTDoc — документ
Назначение: модель данных одного документа: читает/пишет .soc-файл, загружает данные S-матриц, хранит параметры графиков и оформления.
Заголовок: TMCGROUTDoc.h
Базовый класс: CDocument.
Зависит от: Tmcgrviw.h, Proc_s.h, SFILE95 (read_S_matrix_element).
Поля (public)
| Поле | Тип | Назначение |
|---|---|---|
grdoc |
TMC_GR_DOC |
Главная структура документа: массив графиков и параметры |
sGrDoc[16] |
TMC_GR_DOC1[16] |
Шаблоны оформления для 16 «цветов» графиков (циклически применяются) |
bLossPoint |
BOOL |
Флаг отображения «точки потерь» |
dXAxiesUserUnit |
double |
Множитель пользовательской единицы оси X |
csXAxiesUserName |
CString |
Имя пользовательской единицы оси X |
scBackgoundColor |
COLORREF |
Цвет фона |
scGridColor |
COLORREF |
Цвет сетки |
scAxiesColor |
COLORREF |
Цвет осей |
scTextColor |
COLORREF |
Цвет текста |
scPointColor |
COLORREF |
Цвет точек |
lfInitial |
LOGFONT |
Шрифт подписей (по умолчанию Times New Roman) |
csEditorName |
CString |
Имя внешнего редактора (по умолчанию winword.exe) |
error[300] |
char[] |
Текст последней ошибки (выводится в виде); пусто = нет ошибки |
piProcInfo |
PROCESS_INFORMATION |
Дескриптор запущенного внешнего процесса |
Конструктор / деструктор
CTMCGROUTDoc()
Инициализирует grdoc значениями по умолчанию (0 графиков, тип X = ГГц, тип Y = КСВН, пределы 1..10 / 1..1.2, авто-масштаб включён), цвета (фон белый, остальное чёрное, точки красные), шрифт Times New Roman, редактор winword.exe; вызывает SetDefaultLineColorWidthType().
~CTMCGROUTDoc()
Освобождает данные через DocFileDelData().
Публичные методы
void ReadDocFile(void)
Что делает: перечитывает документ целиком.
Как работает: формирует имя .soc (MakeDocFileName), освобождает старые данные (DocFileDelData), считает число графиков (ReadNGraph), выделяет память (DocFileNewData), читает каждый график (ReadGraph), обновляет метки времени (IsDataModific).
void ReadGraphParameters(void)
Читает из .soc-файла строки параметров (по одной) через SetOneReadGraphParameters, затем применяет цвет точек (SetGraphColor).
void ReadGraphParametersDefault(void)
Читает параметры графиков по умолчанию из профиля реестра (ключ #TMCGROTS); строки разделены символом ¦ (0xA6 в Windows-1251).
BOOL WriteDocFile()
Что делает: записывает текущий документ в .soc-файл и дублирует параметры оформления в реестр.
Возвращает: FALSE при успехе, TRUE при ошибке (нетипичная инверсия — учитывать!).
Особенности: пишет сигнатуру #TMCGROUT, блок параметров (единицы, типы осей, пределы, флаги, шрифт, цвета, параметры 16 линий), затем по строке на каждый график (имя подпись OutFlag inp1 mod1 inp2 mod2).
void AddGraphicsInDoc(char *szSFileName)
Дописывает в конец .soc-файла новую строку-график для указанного S-файла (путь делается относительным через MakeRelatPathSFile). Параметры элемента по умолчанию — 1 1 1 1 1.
BOOL IsDataModific(void)
Сравнивает сохранённые LastWriteTime документа и всех выводимых S-файлов с актуальными. Если что-то изменилось — обновляет метки и возвращает TRUE, иначе FALSE.
void SetGraphColor(void)
Присваивает всем графикам цвет точек scPointColor.
void RunExeFile(char *lpszNameExe)
Запускает внешнюю программу lpszNameExe, передавая ей путь к документу в качестве аргумента (через CreatProc).
BOOL DocFileNewData(int n)
Выделяет массив grdoc.psGraph на n графиков и инициализирует каждый шаблоном из sGrDoc[i % 16] (цвет, тип/толщина линии, форма маркера); выделяет буферы имён (по 300 байт). Возвращает TRUE/FALSE (нехватка памяти).
void DocFileDelData()
Освобождает все динамические поля графиков (pFreq, pSmatr, имена, pcExpr) и сам массив; обнуляет счётчик и error.
Приватные методы (вспомогательные)
| Метод | Назначение |
|---|---|
int ReadNGraph(void) |
Подсчитывает число строк-графиков в .soc (непустые строки, не начинающиеся с #) |
void ReadGraph(int nGr) |
Читает nGr-ю строку графика, разбирает поля (имя [подпись] [OutFlag] inp1 mod1 inp2 mod2); если имя в фигурных скобках {…} → выражение (ReadGraph1Expession), иначе обычный файл (ReadGraph1) |
void ReadGraph1(int nGr, char *szFileName, int *nPoint, double **pFreq, _complex **pSmatr) |
Загружает данные одного S-файла через read_S_matrix_element (SFILE95); при ошибке пишет Error_when_read_* в подпись |
void ReadGraph1Expession(int nGr, char *szExpression) |
Строит график-выражение: создаёт CTMCGrExpression, загружает все файлы-переменные, проверяет совпадение частотных сеток (IsFreqCorrect), копирует частоты |
int CalcNGraphExpession(char *szExpression) |
(объявлен) подсчёт числа графиков в выражении |
void ReadInputModeFromFileName(CString&, char*, int&, int&, int&, int&) |
Извлекает inp1/mod1/inp2/mod2 из имени вида *inp1;mod1;inp2;mod2*реальное_имя; если нет — возвращает −1 |
void SetOneReadGraphParameters(char *ch) |
Разбирает одну строку параметров .soc (по префиксу #…): пределы, типы осей, флаги, цвета, шрифт, параметры 16 линий |
void SetDefaultLineColorWidthType(void) |
Заполняет sGrDoc[0..15] цветами и формами маркеров по умолчанию (16 заранее заданных вариантов), LineType=PS_SOLID, LineWidth=50 |
void MakeDocFileName(void) |
Если путь пуст — берёт заголовок; если открыт .s/.soc — формирует имя .soc-документа и создаёт заготовку файла |
BOOL IsDocFileName(char *ch) |
Проверяет, что первая строка файла = сигнатура #TMCGROUT |
void SFileNameToDatFileName(char *ch) |
Преобразует имя .s-файла в .soc (или .$OC, если .soc уже есть) |
void MakeRelatPathSFile(char *szSFileName) |
Делает путь S-файла относительным к каталогу документа (через ..\) |
int CalcNDirInPathName(char *ch) |
Считает число каталогов в пути |
int SelectDirName(char *ch) |
Возвращает длину первого сегмента пути (до \) |
FILETIME LastWriteTime(char *szFileName) |
Возвращает время последней записи файла (через CreateFile/GetFileTime) |
void del_bl2(char *ch) |
«Сжимает» строку: убирает лишние пробелы, учитывает скобки [], обрезает по ! (комментарий) |
void del_bl3(char *ch) |
Удаляет из строки все пробелы/табы/переводы строк |
void put_error_messege(char *error) |
Копирует текст ошибки в поле error (выводится в виде) |
void CreatProc(char *lpszNameExe) |
Запускает дочерний процесс CreateProcess в каталоге документа |
Примечание: при добавлении файла во MRU намеренно передаётся
FALSE(не добавлять рабочий путь), чтобы избежать исключенияCInvalidArgExceptionвCRecentFileList::Add(см. комментарии в коде — исправление бага краша).
8. Класс CTMCGROUTView — вид
Назначение: отрисовка графиков и вся интерактивная работа (мышь, меню, масштабирование, печать). Самый большой класс программы.
Заголовок: TMCGROUTView.h
Базовый класс: CScrollView.
Зависит от: Tmcgrviw.h, complex1.h, SFILE95, complex, exprint.
Поля (private, основные)
| Поле | Тип | Назначение |
|---|---|---|
tmcgrwin |
TMC_GR_WINDOW |
Состояние области рисования (окно, вьюпорт, типы осей, массив точек графиков) |
gr_typX |
TMC_GR_TYPE_X* |
Массив из 6 описаний типов оси X (ГГц/МГц/кГц/Гц/пользоват./терминатор) |
gr_typY |
TMC_GR_TYPE_Y* |
Массив из 6 описаний типов оси Y (КСВН/L dB/|S|/фаза°/фаза rad/терминатор) |
bLossPoint |
BOOL |
Флаг «точки потерь» |
dPointSize |
double |
Размер маркера точки |
csXAxiesFormat, csYAxiesFormat |
CString |
printf-формат подписей осей (по умолчанию %4.3lg) |
dXAxiesUserUnit |
double |
Множитель пользовательской единицы X |
MouseResize |
CRect |
Прямоугольник выделения мышью (zoom) |
MouseXCoord, MouseYCoord |
double |
Координаты под курсором (для статусбара) |
FlagDrawMouseCoord(Move), FlagResizeInit |
BOOL |
Флаги состояния мыши/инициализации |
rectOutXY |
CRect |
Область вывода координат |
Переопределения MFC
| Метод | Назначение |
|---|---|
void OnDraw(CDC* pDC) |
Главная отрисовка: фон → (если есть ошибка — текст ошибки и выход) → рамка zoom → сетка → оси → графики |
void OnInitialUpdate() |
Установка размеров прокрутки (SetScrollSizes, MM_HIMETRIC), чтение параметров (ReadGraphParametersDefault/ReadGraphParameters), загрузка данных (ReadDocFileW), копирование настроек из документа во вьюпорт, пересчёт графиков (PrepareDoubleGraph/PrepareLogGraph), запуск таймера (10 с) |
BOOL PreCreateWindow(CREATESTRUCT&) |
По умолчанию |
void OnPrepareDC(CDC*, CPrintInfo*) |
Подготовка контекста (масштаб/начало координат) |
BOOL OnPreparePrinting/OnBeginPrinting/OnEndPrinting |
Печать (стандартная) |
BOOL OnEraseBkgnd(CDC*) |
Заливка фона цветом scBackgoundColor |
CTMCGROUTDoc* GetDocument() |
Доступ к документу (с проверкой типа в Debug) |
Преобразования координат
Окно (вещественные Xmin..Xmax, Ymin..Ymax) вьюпорт (логические пиксели nXmin..nXmax, nYmin..nYmax). Все четыре функции делают линейное преобразование с зажимом результата в границы.
double LXCordToDoublX(int x) / double LYCordToDoublY(int y)
Логическая координата → вещественная X/Y (для определения, что под курсором).
int DoublXCordToLX(double x) / int DoublYCordToLY(double y)
Вещественная координата → логическая (экранная) X/Y (для рисования).
double GetXAxiesUnit(void)
Возвращает множитель текущей единицы X: ГГц→1e-9, МГц→1e-6, кГц→1e-3, Гц→1, пользоват.→dXAxiesUserUnit.
Подготовка данных к рисованию
void ReadDocFileW(void)
Перечитывает документ (pDoc->ReadDocFile), пересоздаёт массив tmcgrwin.psGraph под число графиков и точек.
void PrepareDoubleGraph(void)
Что делает: заполняет вещественные точки pPoint[j] для каждого видимого графика.
Как работает: для каждого графика и точки вычисляет X по типу оси (делит частоту на 1e9/1e6/…), а Y — по типу (КСВН =(1+r)/(1−r), потери =−20·lg|S|, модуль |S|, фаза в рад/град; для выражений — через методы CTMCGrExpression). Параллельно ищет минимумы/максимумы и, если включён авто-масштаб (nAFlagX/nAFlagY), задаёт пределы окна. Вызывает PutStatistics1().
void PrepareLogGraph(void)
Переводит все вещественные точки в логические (DoublXCordToLX/Y), считает nPointDraw — число точек в пределах окна; точки вне [Xmin,Xmax] «прижимаются» к предыдущей.
void RedrawViewGr(void)
PrepareDoubleGraph → PrepareLogGraph → RedrawWindow.
Отрисовка (private)
| Метод | Назначение |
|---|---|
void onDrowAxies(CDC*) |
Рисует оси X/Y со стрелками и подпись типа оси X |
void onDrawGrid(CDC*) |
Рисует координатную сетку с числовыми метками (формат csXAxiesFormat/csYAxiesFormat) |
void OnDrawGraph(CDC*) |
Рисует все графики: проход 1 — линии (OnDrawGraph1), проход 2 — маркеры (OnDrawGraph2), проход 3 — доп. элементы (OnDrawGraph3) |
void OnDrawGraph1/2/3(CDC*, int i) |
Линия / маркеры / прочее для графика i |
void OnDrawLine(CDC*, int i, int nX, int nY) |
Отрезок линии графика |
void OnDrawPoint(CDC*, int i, int nX, int nY) |
Маркер точки (по форме piPoint) |
void OnDrawBackground(CDC*) |
Заливка фона |
void OnDrawMouseResize(CDC*) |
Пунктирный прямоугольник выделения zoom |
void OnDrawMouseScrol(CDC*) |
(вызов закомментирован в OnDraw) |
void VTextOut(CDC*, int nX, int nY, CString) |
Вывод текста выбранным шрифтом lfInitial |
void SetRectOutXY() |
Пересчёт области вывода координат |
void IvalidateRectView(CRect r1) |
Инвалидация прямоугольника вида |
Обработчики мыши
| Метод | Действие |
|---|---|
OnLButtonDown |
Начало выделения области (zoom) |
OnMouseMove |
Обновляет рамку выделения и координаты в статусбаре (PutTrace1) |
OnLButtonUp |
Завершает zoom: новые пределы по выделению (если область достаточно велика) |
OnLButtonDblClk |
Двойной щелчок: внутри графика — OnViewResizewindow, вне — OnViewResizectrlr + сохранение в реестр; перед этим перечитывает данные при изменении файлов |
OnRButtonDown |
Контекстное действие (правая кнопка) |
OnTimer |
По таймеру (10 с): при изменении файлов перечитывает и перерисовывает |
Команды меню (обработчики afx_msg)
| Метод | Команда меню | Действие |
|---|---|---|
OnEditEdit |
Edit/Edit | Запуск внешнего редактора для документа |
OnEditGraphicsparameters |
параметры графика | Открывает диалог CTMCGROUTDIALOGView; применяет пределы, единицы, формат, флаги, при необходимости вызывает диалоги цветов/шрифта; сохраняет в документ и реестр |
OnEditDocument |
редактор документа | Открывает диалог-таблицу CDialogDoc со списком до 20 графиков (имена, входы/моды, флаги) |
OnEditAddcharacteristics |
добавить характеристику | Диалог выбора .s-файла → AddGraphicsInDoc → перечитать → OnEditDocument |
OnViewGraphics |
обновить | Перечитать документ и перерисовать |
OnViewResizectrlr |
подгон под окно | Пересчитывает вьюпорт по размеру клиентской области |
OnViewResizewindow |
— | Изменение вещественного окна |
OnViewAutoxsize/OnViewAutoysize |
авто-масштаб X/Y | Включает авто-подбор пределов (+ OnUpdate… — галочки в меню) |
OnViewChangexmaxxmin Increment/Decriment |
сдвиг по X | Сдвиг окна по X на ±10 % |
OnViewChangeymaxymin Increment/Decrement |
сдвиг по Y | Сдвиг окна по Y на ±10 % |
OnViewZoomZoom/Zoomp |
zoom −/+ | Масштаб по обеим осям |
OnViewZoomZoomx/Zoomxp |
zoom X −/+ | Масштаб по X |
OnViewZoomZoomy/Zoomyp |
zoom Y −/+ | Масштаб по Y |
OnViewTranslateHome/End |
в начало/конец | Прокрутка/сдвиг диапазона |
OnConfigEditor |
выбор редактора | Задаёт csEditorName |
OnConfigFont |
шрифт | Диалог CFontDialog, сохраняет lfInitial |
OnConfigColorpoint |
цвет точек | CColorDialog → scPointColor |
OnConfigColorAxis |
цвет осей | → scAxiesColor |
OnConfigColorGrid |
цвет сетки | → scGridColor |
OnConfigColorBackground |
цвет фона | → scBackgoundColor |
OnConfigColorGraphics |
цвета графиков | Диалог CTmcGroutColorGraphDialog (16 линий) |
OnFileSave/OnFileSaveAs |
сохранить | Запись документа |
Прочие private
| Метод | Назначение |
|---|---|
void PutTrace1() |
Формирует и выводит в статусбар координаты под курсором (X=…; Y=…) |
void PutStatistics1() |
Выводит во вторую панель статусбара имя текущего типа Y |
void WriteIniWndPar() |
Сохраняет в реестр размеры вьюпорта, форматы осей, размер точки |
9. Диалоги
9.1. Класс CTMCGROUTDIALOGView — параметры графика
Заголовок: TMCGROUTDIALOGView.h · Базовый класс: CDialog · Ресурс: IDD_DIALOG1.
Назначение: настройка отображения: пределы X/Y, авто-масштаб, единица оси X (радиокнопки Гц/кГц/МГц/ГГц/пользоват.), тип Y, флаг и размер точек, форматы подписей, имя файла документа.
Ключевые поля (DDX): m_XMin/m_XMax/m_YMin/m_YMax (double — пределы), m_aXSFlag/m_aYSFlag (BOOL — авто-масштаб), m_XUnit/m_YUnit (int — индекс радиогруппы типа X/Y), m_dXUnit (множитель пользоват. единицы), m_csXUserName (имя единицы), m_csXFormat/m_csYFormat (формат осей), m_DrawPoinFlag (рисовать точки), m_dPointSize (0..100), m_LossPoint, m_szDatFileName. Флаги m_Font/m_Color/m_ColorGrid/m_ColorAxies/m_ColorBackground/m_ColorGraphics сигнализируют, какую доп. настройку открыть после закрытия.
Методы:
- BOOL OnInitDialog() — включает/выключает поля в зависимости от флагов (например, поля Xmin/Xmax недоступны при авто-масштабе);
- OnGrparXinghz/Xinhz/Xinkhz/Xinmhz/Xinhz2 — переключение единицы X, активируют поля пользовательской единицы при m_XUnit==4;
- OnGrparAxsflag/Aysflag — блокируют пределы при авто-масштабе;
- OnGrparPointflag — блокирует параметры точки;
- OnDefaultGridFormat — ставит формат осей %4.3lg;
- OnOk2..OnOk7 — закрывают диалог, выставляя соответствующий флаг (m_Font, m_Color, m_ColorGrid, m_ColorAxies, m_ColorBackground, m_ColorGraphics).
9.2. Класс CDialogDoc — таблица графиков документа
Заголовок: DialogDoc.h · Базовый класс: CDialog · Ресурс: IDD_DIALOG2.
Назначение: редактирование содержимого документа в виде таблицы на 20 строк. Для каждой строки: имя графика (m_GraphName1..20), имя S-файла (m_SFileName_1..20), входы/моды (m_np1_*, m_np2_*, m_mod1_*, m_mod2_* — по 20), флаг вывода (m_OutGrFlag_1..20).
Поля: m_DocFileName (CString) — имя файла документа; m_AddCharacteristicsFlag (BOOL) — установлен, если пользователь нажал «добавить».
Методы: OnAddCharacteristics() — выставляет m_AddCharacteristicsFlag=TRUE и закрывает диалог по OK.
Большое число одинаковых полей (
*_1..*_20) — следствие фиксированной разметки диалога на 20 строк; семантика всех полей идентична соответствующим полямTMC_GR_DOC1.
9.3. Класс CTmcGroutColorGraphDialog — цвета 16 графиков
Заголовок: TmcGroutColorGraphDialog.h · Базовый класс: CDialog · Ресурс: IDD_DIALOGBARCOLORH.
Назначение: настройка цвета/типа/толщины линий сразу для 16 графиков; рисует образцы линий.
Поле: sGrDoc[16] (TMC_GR_DOC1) — рабочая копия параметров 16 линий.
Методы:
- void SetGraphParam(TMC_GR_DOC1 *sGrDoc1) — копирует параметры 16 линий в диалог (вызывается перед показом);
- void GetGraphParam(TMC_GR_DOC1 *sGrDoc1) — копирует обратно (после OK);
- void OnPaint() — рисует образец каждой из 16 линий в статических полях IDC_STATICLEVEL1..16;
- OnColorLevelAutoSet…OnColorLevelAutoSet16() — обработчики 16 кнопок, каждый вызывает ChangeGraphicsPar(n) для линии n=0..15;
- void ChangeGraphicsPar(int n) — открывает диалог CTmcGrParColTypWid для линии n, применяет выбранные цвет/тип/толщину;
- void OnGrapparcordefault() — сброс к умолчанию (SetDefault);
- void SetDefault(void) — заполняет sGrDoc[0..15] цветами/формами по умолчанию (аналогично CTMCGROUTDoc::SetDefaultLineColorWidthType).
9.4. Класс CTmcGrParColTypWid — параметры одной линии
Заголовок: TmcGrParColTypWid.h · Базовый класс: CDialog · Ресурс: IDD_DIALOGGRPARALL.
Назначение: выбор цвета, стиля и толщины одной линии графика.
Поля: LineType (int — PS_SOLID/PS_DASH/PS_DOT/…), LineWidth (int), LineColor (COLORREF); DDX-поля m_Style (радиогруппа стиля), m_Width (радиогруппа толщины).
Методы:
- BOOL OnInitDialog() — устанавливает радиокнопки из LineType/LineWidth;
- void OnPaint() — рисует образец линии в IDC_STATICLEVEL2;
- void OnGrParamColor() — CColorDialog для выбора цвета линии;
- OnRadio1..OnRadio5() — выбор стиля; при не-сплошном стиле толщина принудительно ставится 1 (поля толщины блокируются);
- void OnOK() — преобразует m_Style в LineType (0→PS_SOLID, 1→PS_DASH, 2→PS_DOT, …) и m_Width в LineWidth, закрывает диалог.
10. Класс CTMCGrExpression — графики-выражения
Назначение: разбор и вычисление графика, заданного выражением над несколькими S-файлами (например, разность характеристик). Синтаксис: текст с подвыражениями в квадратных скобках [имя_файла], между которыми — операторы/функции (вычисляются библиотекой exprint).
Заголовок: src/Include/TMCGrExpression.h (общий) · Реализация: TMCGrExpression.cpp.
Зависит от: complex1.h (complex), inter.h (exprint — i1nte_atof_1), Tmcgrviw.h.
Поля (private)
| Поле | Тип | Назначение |
|---|---|---|
csExpresion |
CString |
Исходный текст выражения |
nVar |
int |
Число переменных (файлов в […]) |
nMaska |
int |
Число «масок» (фрагментов вне скобок) = nVar+1 |
pszVar |
char** |
Имена файлов-переменных |
pszMaska |
char** |
Текстовые фрагменты между переменными |
pnPoint |
int* |
Число точек по каждой переменной |
ppdFreq |
double** |
Массивы частот по переменным |
ppcSmatrix |
_complex** |
Массивы S-значений по переменным |
IsError |
BOOL |
Флаг ошибки вычисления |
Конструктор / методы
CTMCGrExpression(char *szExpression)
Сохраняет текст выражения, обнуляет поля.
char* InitData(void)
Что делает: разбирает выражение и выделяет память.
Как работает: считает число переменных (CalcNGraphExpession), выделяет массивы, разбивает строку на маски и переменные (Init1Data).
Возвращает: NULL при успехе, иначе строку-описание ошибки ("Bad_Nvar_or_Bad_Bracket[]", "memory_allocation_error", "init_data_error").
int GetNVar(void) — число переменных.
char* GetFileName(int n) — имя n-го файла (или NULL при выходе за границы).
double** GetFreqArray(int n) / _complex** GetSMatrArray(int n) / int* GetNPoint(int n)
Возвращают адрес соответствующего элемента массива (для заполнения извне через CTMCGROUTDoc::ReadGraph1); NULL при некорректном n.
BOOL IsFreqCorrect(void)
Проверяет, что у всех переменных одинаковое число точек и совпадающие частоты (с относительной точностью 1e-15). Возврат TRUE/FALSE.
BOOL IsGraphDifferent(void)
TRUE, если второй символ выражения — { (особый режим «разностного» графика).
Вычисление значения в точке nPoint
Для каждого типа Y свой метод; все собирают строку «маска₀ (значение₁) маска₁ (значение₂) …» и вычисляют её через i1nte_atof_1 (exprint):
| Метод | Что подставляет |
|-------|-----------------|
| double GetExpressionValue(int n) | Подставляет частоту {f=(…)} (инициализация) |
| double GetExpressionValueSM(int n) | Модуль cabsv(S) |
| double GetExpressionValueL(int n) | Потери −20·lg|S| |
| double GetExpressionValueK(int n) | КСВН (1+|S|)/(1−|S|) (с защитой |S|≈1) |
| double GetExpressionValueSFR(int n) | Фаза, радианы (с «разворачиванием» через GetCPhase) |
| double GetExpressionValueSFD(int n) | Фаза, градусы |
| double GetExpressionValueSFR_User/SFD_User(int n) | Фаза без разворачивания (через GetCPhase_User) |
Возвращают: вещественное значение; при ошибке вычисления выставляют IsError=TRUE и возвращают 0.
double GetCPhase(int i, int nPoint) (private)
Возвращает «развёрнутую» (непрерывную) фазу переменной i в точке nPoint: суммирует переходы через 2π.
double GetCPhase_User(int i, int nPoint) (private)
Возвращает «сырую» фазу cphase(S) без разворачивания.
void DeleteData(void) / BOOL Init1Data(void) / int CalcNGraphExpession(void) (private)
Освобождение памяти / заполнение масок и переменных / подсчёт числа переменных по скобкам.
11. Глобальные функции (в TMCGROUTView.cpp)
Объявлены в TMCGROUTView.h, пишут текст в строку состояния главного окна.
| Функция | Назначение |
|---|---|
void PutTrace(CString csTrace) |
Выводит текст в панель 0 статусбара (координаты курсора) |
void PutTrace(char *szTrace) |
То же, перегрузка для C-строки |
void PutStatistics(CString csTrace) |
Выводит текст в панель 1 статусбара (тип графика) |
void PutStatistics(char *szTrace) |
То же для C-строки |
Также в Tmcgrviw.h объявлены вспомогательные глобальные функции работы с путями (MakeRelatPathFile, MakeFullPathFile, SelectDirName, CalcNDirInPathName, RunExeFileG, CreatProcG) — их реализация может находиться в других модулях пакета.
12. Формат файла документа .soc
Текстовый файл. Первая строка — сигнатура #TMCGROUT. Далее:
- строки параметров вида #Ключ значение (распознаются SetOneReadGraphParameters по префиксам из Tmcgrviw.h): единицы и имя оси X, флаги точек, типы осей, пределы Xmin/Xmax/Ymin/Ymax, флаги авто-масштаба, имя редактора, шрифт, цвета (текст/фон/оси/сетка/точки) и параметры 16 линий;
- комментарии — строки, начинающиеся с ! (или часть строки после !);
- строки-графики: имя_файла [подпись] [OutFlag] inp1 mod1 inp2 mod2. Имя в фигурных скобках {…} означает график-выражение.
Параметры оформления дублируются в реестр HKCU\…\#TMCGROTS (для использования как «значения по умолчанию» в новых документах), где строки разделены символом ¦ (0xA6).
The TMCGROUT program — API documentation
TMC Suite package. A viewer of scattering-matrix (S-parameter) frequency-response graphs: VSWR, losses (dB), the magnitude and phase of the S-matrix elements. All signatures are taken from the sources in
src/viewers/Tmcgrout/and the shared headers fromsrc/Include/.
1. Purpose of the program
TMCGROUT (the output EXE — TMCGROUT.exe) is a graphical viewer of
electrodynamic-computation results: it builds 2D frequency-response graphs of a
multiport from data in S-files (scattering matrices, read by the SFILE95 library).
The program is built on the classic MFC Document/View scheme (an MDI —
multiple-document-interface — application). Each document is a text file with the
.soc extension (the TMCGROUT format) that describes a set of graphs: for each graph
the S-file name, the input/mode numbers of the S-matrix element, and a caption are
given. The program can:
- open
.socdocuments or.s/.s2p/.s4p/… scattering-matrix files directly (a.socdocument is created automatically for them); - build up to 20 graphs in one document, each with its own line color/type/width;
- for each graph choose the Y type (VSWR, losses in dB, magnitude |S|, phase in degrees/radians) and the X type (frequency in Hz/kHz/MHz/GHz or a custom unit);
- compute graphs from expressions over several S-files (the syntax
{...[file]...}, parsing — theCTMCGrExpressionclass, evaluation — the exprint library); - scale (zoom with the mouse and via the menu), auto-fit the X/Y limits, scroll Home/End;
- configure the colors (background, grid, axes, points, graphs), the label font;
- save the window and appearance parameters in the registry (HKCU\…\TMCGROUT) and in
the
.socfile itself; - launch an external editor (by default
winword.exe) for the document; - watch the modification time of the files and re-read the data on change (a timer).
2. Project composition
The TMCGROUT.vcxproj build contains the following .cpp/.h files:
| File | Class / contents | Purpose (briefly) |
|---|---|---|
TMCGROUT.cpp/.h |
CTMCGROUTApp |
The application class, InitInstance, the document template, the "About" dialog |
MainFrm.cpp/.h |
CMainFrame |
The main MDI window: the toolbar, status bar, saving the window position |
ChildFrm.cpp/.h |
CChildFrame |
The child MDI document window |
TMCGROUTDoc.cpp/.h |
CTMCGROUTDoc |
The document: reading/writing .soc, loading S-data, the graph parameters |
TMCGROUTView.cpp/.h |
CTMCGROUTView |
The view: all drawing of the graphs, axes, grid, mouse and menu handling |
TMCGROUTDIALOGView.cpp/.h |
CTMCGROUTDIALOGView |
The graph-parameters dialog (limits, units, format, points) |
DialogDoc.cpp/.h |
CDialogDoc |
The document-contents table dialog (up to 20 graphs) |
TmcGroutColorGraphDialog.cpp/.h |
CTmcGroutColorGraphDialog |
The color/type/width dialog for 16 graph lines |
TmcGrParColTypWid.cpp/.h |
CTmcGrParColTypWid |
The color/style/width selection dialog for a single line |
TMCGrExpression.cpp |
CTMCGrExpression |
Parsing and evaluation of expression graphs (the header is shared, in src/Include) |
StdAfx.cpp/.h |
— | The MFC precompiled header |
resource.h, TMCGROUT.rc |
— | Resources (menus, dialogs, icons, toolbar) |
Dependencies: MFC (UseOfMfc — shared/static), the shared headers src/Include/
(Tmcgrviw.h, TMCGrExpression.h, Proc_s.h, complex1.h, inter.h, typedef.h),
and the package libraries: SFILE95 (reading S-matrices — read_S_matrix_element),
complex (cabsv, cphase), exprint (i1nte_atof_1 from inter.h — expression
evaluation).
3. Common data structures (the Tmcgrviw.h header)
The program stores the graph data in structures declared in the shared header
src/Include/Tmcgrviw.h. These structures are the basis of the TMCGROUT data model.
3.1. TMC_GR_DOC1 — one graph (in a document)
typedef struct {
int nPoint; // the number of graph points
double dFreq; // the frequency (for the time array)
double *pFreq; // the array of frequencies
_complex *pSmatr; // the array of complex values of the S-matrix element
CTMCGrExpression *pcExpr;// a pointer to the expression class (if the graph is an expression)
int nInp1; // the number of input 1
int nMod1; // the mode number of input 1
int nInp2; // the number of input 2
int nMod2; // the mode number of input 2
char *szFileName; // the full S-file name (with path)
char *szGrapName; // the graph name (the S-file name or the expression text)
char *szGrapPodp; // the graph caption in the legend
int LineColor; // the line color (COLORREF)
int LineType; // the line style (PS_SOLID/PS_DASH/…)
int LineWidth; // the line width
TMC_INT_POINT piPoint[TMC_GROUT_POINT_TYPE]; // 10 points of the marker shape
int PointColor; // the marker color
int PointType; // the marker style
int PointWidth; // the marker width
int OutFlag; // the flag for outputting the graph on screen (TRUE/FALSE)
FILETIME LastWriteTime;// the last write time of the S-file
} TMC_GR_DOC1;
| Field | Type | Purpose |
|---|---|---|
nPoint |
int |
The number of frequency points of the graph |
pFreq |
double* |
The array of frequencies (Hz), length nPoint |
pSmatr |
_complex* |
The array of complex S-values, length nPoint |
pcExpr |
CTMCGrExpression* |
If ≠ NULL — the graph is computed from an expression rather than a single file |
nInp1/nMod1/nInp2/nMod2 |
int |
The address of the S-matrix element (input/mode input/mode) |
szFileName |
char* |
The full path to the S-file |
szGrapName |
char* |
The graph name (the file name or the text of a {...} expression) |
szGrapPodp |
char* |
The caption (legend); on a read error Error_... is written here |
LineColor/LineType/LineWidth |
int |
The line parameters |
piPoint[10] |
TMC_INT_POINT[] |
The coordinates of the marker vertices (the symbol shape) |
OutFlag |
int |
Whether to draw the graph |
LastWriteTime |
FILETIME |
File-change control |
3.2. TMC_GR_DOC — the whole document
typedef struct {
int nGraph; // the number of graphs in the document
TMC_GR_DOC1 *psGraph; // the array of graphs
BOOL nAFlagX; // auto-scale on X (TRUE — auto-fit)
BOOL nAFlagY; // auto-scale on Y
BOOL PointDrawFlag;// whether to draw the point markers
int nYType; // the Y-coordinate type (see the constants)
int nXType; // the X-coordinate type
double Xmin, Xmax; // the X limits
double Ymin, Ymax; // the Y limits
FILETIME LastWriteTime;// the write time of the document file
} TMC_GR_DOC;
3.3. TMC_GR_VIEW, TMC_GR_WINDOW — the view data
TMC_GR_VIEW stores the points of one graph in two coordinate systems — the real
one (pPoint, type TMC_POINT{double x,y}) and the logical screen one (piPoint,
type TMC_INT_POINT{int nX,nY}).
typedef struct {
int nPoint; // the number of points
int nPointDraw; // the number of actually drawn points (within the window)
TMC_POINT *pPoint; // the real coordinates
TMC_INT_POINT *piPoint; // the logical (screen) coordinates
} TMC_GR_VIEW;
TMC_GR_WINDOW — the state of the view's drawing area: the real window sGrWin
(TMC_GR_WINDOW_D — Xmin/Xmax/Ymin/Ymax, flags nAFlagX/nAFlagY), the integer
viewport sGrView (TMC_GR_VIEWPORT — nXmin/nXmax/nYmin/nYmax), the axis types
nXType/nYType, the number of graphs nGraph, the point flag PointDrawFlag, the
array psGraph.
3.4. TMC_GR_TYPE_X, TMC_GR_TYPE_Y — the axis-type description
typedef struct { int nType; char pszXname[100]; } TMC_GR_TYPE_X;
typedef struct { int nType; char pszYname[100]; } TMC_GR_TYPE_Y;
A pair of "type code + axis-label text".
3.5. Graph-type constants (Tmcgrviw.h)
| Constant | Value | Meaning (Y axis) |
|---|---|---|
TMC_GR_TYPE_WSVR |
0 | VSWR |
TMC_GR_TYPE_L |
1 | Losses, dB (-20·lg|S|) |
TMC_GR_TYPE_SM |
2 | Magnitude |S| |
TMC_GR_TYPE_SFR |
3 | S phase, radians |
TMC_GR_TYPE_SFD |
4 | S phase, degrees |
| Constant | Value | Meaning (X axis) |
|---|---|---|
TMC_GR_TYPE_FGHz |
0 | Frequency, GHz |
TMC_GR_TYPE_FMHz |
1 | Frequency, MHz |
TMC_GR_TYPE_FKHz |
2 | Frequency, kHz |
TMC_GR_TYPE_FHz |
3 | Frequency, Hz |
TMC_GR_TYPE_F_USER |
4 | A custom unit (the name and factor are set by the user) |
| Constant | Value | Meaning |
|---|---|---|
TMC_GROUT_DOCFILE_ID |
"#TMCGROUT" |
The signature label of the .soc document file |
TMC_GROUT_MAXSTRING_BUF |
10000 | The string-buffer size |
TMC_GROUT_POINT_TYPE |
10 | The number of vertices in the point-marker shape |
TMC_GROUT_POINT_TYPE_X/Y |
400 | The base marker size along X/Y |
TMC_VIEW_XSIZE/YSIZE |
18000 | The logical size of the drawing area |
TMC_VIEW_SIZEMODE |
MM_HIMETRIC |
The mapping mode (metric) |
In addition, the header contains a set of #define identifiers for the sections of the
document file (TMC_GROUT_DOCFILE_ID_Xmin, …_nXType, …_sDrawTextFont, etc.) — these
are the text prefixes of the .soc-file lines by which
CTMCGROUTDoc::SetOneReadGraphParameters recognizes the parameters.
4. The CTMCGROUTApp class
Purpose: the MFC application class. It initializes the program, registers the
document template, opens the last file, restores the position of the main window.
Header: TMCGROUT.h
Base class: CWinApp.
Methods
CTMCGROUTApp()
The constructor. The significant initialization is moved to InitInstance.
BOOL InitInstance()
What it does: the application entry point.
How it works:
1. AfxOleInit() — OLE/COM initialization (needed for Shell calls in
CRecentFileList on Windows 7+; part of the fix for the crash-on-open bug);
2. SetRegistryKey("TMCGROUT") — store the settings and the recent-files list (MRU) in
the registry HKCU, rather than in WINDIR\TMCGROUT.INI;
3. Enable3dControls(), LoadStdProfileSettings(9) — standard MFC initialization,
loading the MRU (9 files);
4. registers CMultiDocTemplate (the document CTMCGROUTDoc + the child window
CChildFrame + the view CTMCGROUTView, the resource IDR_TMCGROTYPE);
5. creates the main window CMainFrame;
6. if the command line is empty — iterates the MRU list and opens the first existing
file;
7. restores the main-window position from the profile (the #INIWND key);
8. shows the window (SW_RESTORE).
Returns: TRUE on success, FALSE on a window-creation error.
afx_msg void OnAppAbout()
Shows the modal "About" dialog (CAboutDlg, the resource IDD_ABOUTBOX).
Global object: CTMCGROUTApp theApp; — the single application instance.
The nested class CAboutDlg (declared in TMCGROUT.cpp) — a simple "About" dialog
without handlers.
5. The CMainFrame class
Purpose: the main MDI window of the application. Contains the toolbar and the status
bar.
Header: MainFrm.h
Base class: CMDIFrameWnd.
Fields
| Field | Type | Purpose |
|---|---|---|
m_wndStatusBar |
CStatusBar |
The status bar (2 panels: mouse coordinates and the current graph type) |
m_wndToolBar |
CToolBar |
The toolbar |
Methods
int OnCreate(LPCREATESTRUCT)
Creates the toolbar (IDR_MAINFRAME) and the status bar (2 separator indicators),
enables docking and tooltips. Returns 0 on success, -1 on error.
BOOL PreCreateWindow(CREATESTRUCT& cs)
Sets the window style (maximized — WS_MAXIMIZE).
void OnDestroy()
On closing saves the main-window position (if SW_SHOWNORMAL) into the registry
profile under the #INIWND key (the format "left right top bottom").
The status bar is filled by the global functions
PutTrace/PutStatistics(see section 11).
6. The CChildFrame class
Purpose: the child MDI window in which the document view lives.
Header: ChildFrm.h
Base class: CMDIChildWnd.
BOOL PreCreateWindow(CREATESTRUCT& cs)
Sets the style of the child window (maximized by default — WS_MAXIMIZE). The class
contains no other handlers.
7. The CTMCGROUTDoc class — the document
Purpose: the data model of one document: reads/writes the .soc file, loads the
S-matrix data, stores the graph and appearance parameters.
Header: TMCGROUTDoc.h
Base class: CDocument.
Depends on: Tmcgrviw.h, Proc_s.h, SFILE95 (read_S_matrix_element).
Fields (public)
| Field | Type | Purpose |
|---|---|---|
grdoc |
TMC_GR_DOC |
The main document structure: the array of graphs and the parameters |
sGrDoc[16] |
TMC_GR_DOC1[16] |
The appearance templates for 16 graph "colors" (applied cyclically) |
bLossPoint |
BOOL |
The "loss point" display flag |
dXAxiesUserUnit |
double |
The multiplier of the custom X-axis unit |
csXAxiesUserName |
CString |
The name of the custom X-axis unit |
scBackgoundColor |
COLORREF |
The background color |
scGridColor |
COLORREF |
The grid color |
scAxiesColor |
COLORREF |
The axis color |
scTextColor |
COLORREF |
The text color |
scPointColor |
COLORREF |
The point color |
lfInitial |
LOGFONT |
The label font (Times New Roman by default) |
csEditorName |
CString |
The external editor name (by default winword.exe) |
error[300] |
char[] |
The text of the last error (shown in the view); empty = no error |
piProcInfo |
PROCESS_INFORMATION |
The handle of the launched external process |
Constructor / destructor
CTMCGROUTDoc()
Initializes grdoc with default values (0 graphs, X type = GHz, Y type = VSWR, limits
1..10 / 1..1.2, auto-scale on), the colors (background white, the rest black, points
red), the font Times New Roman, the editor winword.exe; calls
SetDefaultLineColorWidthType().
~CTMCGROUTDoc()
Frees the data via DocFileDelData().
Public methods
void ReadDocFile(void)
What it does: re-reads the whole document.
How it works: forms the .soc name (MakeDocFileName), frees the old data
(DocFileDelData), counts the graphs (ReadNGraph), allocates memory
(DocFileNewData), reads each graph (ReadGraph), updates the timestamps
(IsDataModific).
void ReadGraphParameters(void)
Reads the parameter lines from the .soc file (one at a time) via
SetOneReadGraphParameters, then applies the point color (SetGraphColor).
void ReadGraphParametersDefault(void)
Reads the default graph parameters from the registry profile (the #TMCGROTS key); the
lines are separated by the ¦ character (0xA6 in Windows-1251).
BOOL WriteDocFile()
What it does: writes the current document into the .soc file and duplicates the
appearance parameters in the registry.
Returns: FALSE on success, TRUE on error (an atypical inversion — note it!).
Features: writes the signature #TMCGROUT, the parameters block (units, axis types,
limits, flags, font, colors, the 16-line parameters), then one line per graph (name
caption OutFlag inp1 mod1 inp2 mod2).
void AddGraphicsInDoc(char *szSFileName)
Appends a new graph line for the given S-file to the end of the .soc file (the path is
made relative via MakeRelatPathSFile). The default element parameters are 1 1 1 1 1.
BOOL IsDataModific(void)
Compares the saved LastWriteTime of the document and of all displayed S-files with the
current ones. If something changed — updates the timestamps and returns TRUE,
otherwise FALSE.
void SetGraphColor(void)
Assigns the point color scPointColor to all graphs.
void RunExeFile(char *lpszNameExe)
Launches the external program lpszNameExe, passing it the document path as an argument
(via CreatProc).
BOOL DocFileNewData(int n)
Allocates the array grdoc.psGraph for n graphs and initializes each with the
template from sGrDoc[i % 16] (color, line type/width, marker shape); allocates name
buffers (300 bytes each). Returns TRUE/FALSE (out of memory).
void DocFileDelData()
Frees all the dynamic fields of the graphs (pFreq, pSmatr, the names, pcExpr) and
the array itself; zeroes the counter and error.
Private methods (helpers)
| Method | Purpose |
|---|---|
int ReadNGraph(void) |
Counts the number of graph lines in the .soc (non-empty lines not starting with #) |
void ReadGraph(int nGr) |
Reads the nGr-th graph line, parses the fields (name [caption] [OutFlag] inp1 mod1 inp2 mod2); if the name is in curly braces {…} → an expression (ReadGraph1Expession), otherwise an ordinary file (ReadGraph1) |
void ReadGraph1(int nGr, char *szFileName, int *nPoint, double **pFreq, _complex **pSmatr) |
Loads the data of one S-file via read_S_matrix_element (SFILE95); on error writes Error_when_read_* into the caption |
void ReadGraph1Expession(int nGr, char *szExpression) |
Builds an expression graph: creates a CTMCGrExpression, loads all the variable files, checks that the frequency grids coincide (IsFreqCorrect), copies the frequencies |
int CalcNGraphExpession(char *szExpression) |
(declared) counting the number of graphs in an expression |
void ReadInputModeFromFileName(CString&, char*, int&, int&, int&, int&) |
Extracts inp1/mod1/inp2/mod2 from a name of the form *inp1;mod1;inp2;mod2*real_name; if absent — returns −1 |
void SetOneReadGraphParameters(char *ch) |
Parses one .soc parameter line (by the #… prefix): limits, axis types, flags, colors, font, the 16-line parameters |
void SetDefaultLineColorWidthType(void) |
Fills sGrDoc[0..15] with default colors and marker shapes (16 predefined variants), LineType=PS_SOLID, LineWidth=50 |
void MakeDocFileName(void) |
If the path is empty — takes the title; if a .s/.soc is open — forms the .soc document name and creates a file stub |
BOOL IsDocFileName(char *ch) |
Checks that the first line of the file = the signature #TMCGROUT |
void SFileNameToDatFileName(char *ch) |
Converts a .s-file name into .soc (or .$OC if .soc already exists) |
void MakeRelatPathSFile(char *szSFileName) |
Makes the S-file path relative to the document directory (via ..\) |
int CalcNDirInPathName(char *ch) |
Counts the number of directories in a path |
int SelectDirName(char *ch) |
Returns the length of the first path segment (up to \) |
FILETIME LastWriteTime(char *szFileName) |
Returns the last write time of a file (via CreateFile/GetFileTime) |
void del_bl2(char *ch) |
"Compresses" a line: removes extra spaces, accounts for [] brackets, truncates at ! (a comment) |
void del_bl3(char *ch) |
Removes all spaces/tabs/newlines from a line |
void put_error_messege(char *error) |
Copies the error text into the error field (shown in the view) |
void CreatProc(char *lpszNameExe) |
Launches a child process CreateProcess in the document directory |
Note: when adding a file to the MRU,
FALSEis deliberately passed (do not add the working path) to avoid aCInvalidArgExceptioninCRecentFileList::Add(see the code comments — the crash-bug fix).
8. The CTMCGROUTView class — the view
Purpose: drawing the graphs and all interactive work (mouse, menu, scaling,
printing). The largest class of the program.
Header: TMCGROUTView.h
Base class: CScrollView.
Depends on: Tmcgrviw.h, complex1.h, SFILE95, complex, exprint.
Fields (private, main)
| Field | Type | Purpose |
|---|---|---|
tmcgrwin |
TMC_GR_WINDOW |
The state of the drawing area (window, viewport, axis types, the graphs' point array) |
gr_typX |
TMC_GR_TYPE_X* |
An array of 6 X-axis type descriptions (GHz/MHz/kHz/Hz/custom/terminator) |
gr_typY |
TMC_GR_TYPE_Y* |
An array of 6 Y-axis type descriptions (VSWR/L dB/|S|/phase°/phase rad/terminator) |
bLossPoint |
BOOL |
The "loss point" flag |
dPointSize |
double |
The point-marker size |
csXAxiesFormat, csYAxiesFormat |
CString |
The printf format of the axis labels (by default %4.3lg) |
dXAxiesUserUnit |
double |
The multiplier of the custom X unit |
MouseResize |
CRect |
The mouse selection rectangle (zoom) |
MouseXCoord, MouseYCoord |
double |
The coordinates under the cursor (for the status bar) |
FlagDrawMouseCoord(Move), FlagResizeInit |
BOOL |
Mouse/initialization state flags |
rectOutXY |
CRect |
The coordinate-output area |
MFC overrides
| Method | Purpose |
|---|---|
void OnDraw(CDC* pDC) |
The main drawing: background → (if there is an error — the error text and exit) → zoom frame → grid → axes → graphs |
void OnInitialUpdate() |
Setting the scroll sizes (SetScrollSizes, MM_HIMETRIC), reading the parameters (ReadGraphParametersDefault/ReadGraphParameters), loading the data (ReadDocFileW), copying the settings from the document into the viewport, recomputing the graphs (PrepareDoubleGraph/PrepareLogGraph), starting the timer (10 s) |
BOOL PreCreateWindow(CREATESTRUCT&) |
Default |
void OnPrepareDC(CDC*, CPrintInfo*) |
Preparing the context (scale/origin) |
BOOL OnPreparePrinting/OnBeginPrinting/OnEndPrinting |
Printing (standard) |
BOOL OnEraseBkgnd(CDC*) |
Filling the background with the color scBackgoundColor |
CTMCGROUTDoc* GetDocument() |
Access to the document (with a type check in Debug) |
Coordinate transformations
The window (the real Xmin..Xmax, Ymin..Ymax) the viewport (the logical pixels
nXmin..nXmax, nYmin..nYmax). All four functions do a linear transformation with
clamping of the result to the boundaries.
double LXCordToDoublX(int x) / double LYCordToDoublY(int y)
Logical coordinate → real X/Y (to determine what is under the cursor).
int DoublXCordToLX(double x) / int DoublYCordToLY(double y)
Real coordinate → logical (screen) X/Y (for drawing).
double GetXAxiesUnit(void)
Returns the multiplier of the current X unit: GHz→1e-9, MHz→1e-6, kHz→1e-3, Hz→1,
custom→dXAxiesUserUnit.
Preparing the data for drawing
void ReadDocFileW(void)
Re-reads the document (pDoc->ReadDocFile), re-creates the array tmcgrwin.psGraph for
the number of graphs and points.
void PrepareDoubleGraph(void)
What it does: fills the real points pPoint[j] for each visible graph.
How it works: for each graph and point computes X by the axis type (dividing the
frequency by 1e9/1e6/…), and Y by the type (VSWR =(1+r)/(1−r), losses =−20·lg|S|,
magnitude |S|, phase in rad/deg; for expressions — via the CTMCGrExpression
methods). In parallel it finds the minima/maxima and, if auto-scale is on
(nAFlagX/nAFlagY), sets the window limits. Calls PutStatistics1().
void PrepareLogGraph(void)
Converts all the real points into logical ones (DoublXCordToLX/Y), counts
nPointDraw — the number of points within the window; points outside [Xmin,Xmax] are
"snapped" to the previous one.
void RedrawViewGr(void)
PrepareDoubleGraph → PrepareLogGraph → RedrawWindow.
Drawing (private)
| Method | Purpose |
|---|---|
void onDrowAxies(CDC*) |
Draws the X/Y axes with arrows and the X-axis type label |
void onDrawGrid(CDC*) |
Draws the coordinate grid with numeric labels (the format csXAxiesFormat/csYAxiesFormat) |
void OnDrawGraph(CDC*) |
Draws all the graphs: pass 1 — lines (OnDrawGraph1), pass 2 — markers (OnDrawGraph2), pass 3 — additional elements (OnDrawGraph3) |
void OnDrawGraph1/2/3(CDC*, int i) |
Line / markers / other for graph i |
void OnDrawLine(CDC*, int i, int nX, int nY) |
A line segment of the graph |
void OnDrawPoint(CDC*, int i, int nX, int nY) |
A point marker (by the piPoint shape) |
void OnDrawBackground(CDC*) |
Filling the background |
void OnDrawMouseResize(CDC*) |
The dashed zoom selection rectangle |
void OnDrawMouseScrol(CDC*) |
(the call is commented out in OnDraw) |
void VTextOut(CDC*, int nX, int nY, CString) |
Text output with the selected font lfInitial |
void SetRectOutXY() |
Recomputing the coordinate-output area |
void IvalidateRectView(CRect r1) |
Invalidating a view rectangle |
Mouse handlers
| Method | Action |
|---|---|
OnLButtonDown |
The start of area selection (zoom) |
OnMouseMove |
Updates the selection frame and the coordinates in the status bar (PutTrace1) |
OnLButtonUp |
Completes the zoom: new limits by the selection (if the area is large enough) |
OnLButtonDblClk |
Double click: inside the graph — OnViewResizewindow, outside — OnViewResizectrlr + saving to the registry; before that re-reads the data on file change |
OnRButtonDown |
A context action (right button) |
OnTimer |
By the timer (10 s): on file change re-reads and redraws |
Menu commands (afx_msg handlers)
| Method | Menu command | Action |
|---|---|---|
OnEditEdit |
Edit/Edit | Launch the external editor for the document |
OnEditGraphicsparameters |
graph parameters | Opens the CTMCGROUTDIALOGView dialog; applies the limits, units, format, flags, calls the color/font dialogs if needed; saves to the document and registry |
OnEditDocument |
document editor | Opens the CDialogDoc table dialog with a list of up to 20 graphs (names, inputs/modes, flags) |
OnEditAddcharacteristics |
add characteristic | A .s-file selection dialog → AddGraphicsInDoc → re-read → OnEditDocument |
OnViewGraphics |
refresh | Re-read the document and redraw |
OnViewResizectrlr |
fit to window | Recomputes the viewport by the client-area size |
OnViewResizewindow |
— | Changing the real window |
OnViewAutoxsize/OnViewAutoysize |
auto-scale X/Y | Enables auto-fit of the limits (+ OnUpdate… — check marks in the menu) |
OnViewChangexmaxxmin Increment/Decriment |
X shift | Shifts the window along X by ±10% |
OnViewChangeymaxymin Increment/Decrement |
Y shift | Shifts the window along Y by ±10% |
OnViewZoomZoom/Zoomp |
zoom −/+ | Scale on both axes |
OnViewZoomZoomx/Zoomxp |
zoom X −/+ | Scale on X |
OnViewZoomZoomy/Zoomyp |
zoom Y −/+ | Scale on Y |
OnViewTranslateHome/End |
to start/end | Scroll/shift of the range |
OnConfigEditor |
editor selection | Sets csEditorName |
OnConfigFont |
font | The CFontDialog, saves lfInitial |
OnConfigColorpoint |
point color | CColorDialog → scPointColor |
OnConfigColorAxis |
axis color | → scAxiesColor |
OnConfigColorGrid |
grid color | → scGridColor |
OnConfigColorBackground |
background color | → scBackgoundColor |
OnConfigColorGraphics |
graph colors | The CTmcGroutColorGraphDialog dialog (16 lines) |
OnFileSave/OnFileSaveAs |
save | Writing the document |
Other private
| Method | Purpose |
|---|---|
void PutTrace1() |
Forms and outputs the coordinates under the cursor to the status bar (X=…; Y=…) |
void PutStatistics1() |
Outputs the name of the current Y type to the second status-bar panel |
void WriteIniWndPar() |
Saves the viewport sizes, axis formats, point size to the registry |
9. Dialogs
9.1. The CTMCGROUTDIALOGView class — the graph parameters
Header: TMCGROUTDIALOGView.h · Base class: CDialog · Resource:
IDD_DIALOG1.
Purpose: display settings: X/Y limits, auto-scale, X-axis unit (radio buttons
Hz/kHz/MHz/GHz/custom), Y type, the point flag and size, the label formats, the document
file name.
Key fields (DDX): m_XMin/m_XMax/m_YMin/m_YMax (double — the limits),
m_aXSFlag/m_aYSFlag (BOOL — auto-scale), m_XUnit/m_YUnit (int — the index of the
X/Y type radio group), m_dXUnit (the custom-unit multiplier), m_csXUserName (the unit
name), m_csXFormat/m_csYFormat (the axis format), m_DrawPoinFlag (draw points),
m_dPointSize (0..100), m_LossPoint, m_szDatFileName. The flags
m_Font/m_Color/m_ColorGrid/m_ColorAxies/m_ColorBackground/m_ColorGraphics signal which
additional setting to open after closing.
Methods:
- BOOL OnInitDialog() — enables/disables the fields depending on the flags (for
example, the Xmin/Xmax fields are unavailable under auto-scale);
- OnGrparXinghz/Xinhz/Xinkhz/Xinmhz/Xinhz2 — switching the X unit, activating the
custom-unit fields when m_XUnit==4;
- OnGrparAxsflag/Aysflag — lock the limits under auto-scale;
- OnGrparPointflag — locks the point parameters;
- OnDefaultGridFormat — sets the axis format %4.3lg;
- OnOk2..OnOk7 — close the dialog, setting the corresponding flag (m_Font, m_Color,
m_ColorGrid, m_ColorAxies, m_ColorBackground, m_ColorGraphics).
9.2. The CDialogDoc class — the document graph table
Header: DialogDoc.h · Base class: CDialog · Resource: IDD_DIALOG2.
Purpose: editing the document contents as a table of 20 rows. For each row: the
graph name (m_GraphName1..20), the S-file name (m_SFileName_1..20), the inputs/modes
(m_np1_*, m_np2_*, m_mod1_*, m_mod2_* — 20 each), the output flag
(m_OutGrFlag_1..20).
Fields: m_DocFileName (CString) — the document file name;
m_AddCharacteristicsFlag (BOOL) — set if the user pressed "add".
Methods: OnAddCharacteristics() — sets m_AddCharacteristicsFlag=TRUE and closes
the dialog by OK.
The large number of identical fields (
*_1..*_20) is a consequence of the fixed dialog layout of 20 rows; the semantics of all the fields are identical to the corresponding fields ofTMC_GR_DOC1.
9.3. The CTmcGroutColorGraphDialog class — the colors of 16 graphs
Header: TmcGroutColorGraphDialog.h · Base class: CDialog · Resource:
IDD_DIALOGBARCOLORH.
Purpose: setting the color/type/width of the lines for 16 graphs at once; draws line
samples.
Field: sGrDoc[16] (TMC_GR_DOC1) — the working copy of the 16-line parameters.
Methods:
- void SetGraphParam(TMC_GR_DOC1 *sGrDoc1) — copies the 16-line parameters into the
dialog (called before showing);
- void GetGraphParam(TMC_GR_DOC1 *sGrDoc1) — copies them back (after OK);
- void OnPaint() — draws a sample of each of the 16 lines in the static fields
IDC_STATICLEVEL1..16;
- OnColorLevelAutoSet…OnColorLevelAutoSet16() — handlers of the 16 buttons, each
calling ChangeGraphicsPar(n) for line n=0..15;
- void ChangeGraphicsPar(int n) — opens the CTmcGrParColTypWid dialog for line n,
applies the chosen color/type/width;
- void OnGrapparcordefault() — reset to default (SetDefault);
- void SetDefault(void) — fills sGrDoc[0..15] with default colors/shapes (like
CTMCGROUTDoc::SetDefaultLineColorWidthType).
9.4. The CTmcGrParColTypWid class — the parameters of a single line
Header: TmcGrParColTypWid.h · Base class: CDialog · Resource:
IDD_DIALOGGRPARALL.
Purpose: choosing the color, style and width of a single graph line.
Fields: LineType (int — PS_SOLID/PS_DASH/PS_DOT/…), LineWidth (int),
LineColor (COLORREF); the DDX fields m_Style (the style radio group), m_Width
(the width radio group).
Methods:
- BOOL OnInitDialog() — sets the radio buttons from LineType/LineWidth;
- void OnPaint() — draws a line sample in IDC_STATICLEVEL2;
- void OnGrParamColor() — the CColorDialog for choosing the line color;
- OnRadio1..OnRadio5() — style selection; for a non-solid style the width is forced to
1 (the width fields are locked);
- void OnOK() — converts m_Style into LineType (0→PS_SOLID, 1→PS_DASH, 2→PS_DOT, …)
and m_Width into LineWidth, closes the dialog.
10. The CTMCGrExpression class — expression graphs
Purpose: parsing and evaluation of a graph given by an expression over several
S-files (for example, the difference of characteristics). Syntax: text with
subexpressions in square brackets [file_name], with operators/functions between them
(evaluated by the exprint library).
Header: src/Include/TMCGrExpression.h (shared) · Implementation:
TMCGrExpression.cpp.
Depends on: complex1.h (complex), inter.h (exprint — i1nte_atof_1),
Tmcgrviw.h.
Fields (private)
| Field | Type | Purpose |
|---|---|---|
csExpresion |
CString |
The source expression text |
nVar |
int |
The number of variables (files in […]) |
nMaska |
int |
The number of "masks" (fragments outside the brackets) = nVar+1 |
pszVar |
char** |
The variable file names |
pszMaska |
char** |
The text fragments between the variables |
pnPoint |
int* |
The number of points per variable |
ppdFreq |
double** |
The frequency arrays per variable |
ppcSmatrix |
_complex** |
The S-value arrays per variable |
IsError |
BOOL |
The evaluation-error flag |
Constructor / methods
CTMCGrExpression(char *szExpression)
Saves the expression text, zeroes the fields.
char* InitData(void)
What it does: parses the expression and allocates memory.
How it works: counts the number of variables (CalcNGraphExpession), allocates the
arrays, splits the string into masks and variables (Init1Data).
Returns: NULL on success, otherwise an error-description string
("Bad_Nvar_or_Bad_Bracket[]", "memory_allocation_error", "init_data_error").
int GetNVar(void) — the number of variables.
char* GetFileName(int n) — the name of the n-th file (or NULL out of bounds).
double** GetFreqArray(int n) / _complex** GetSMatrArray(int n) / int* GetNPoint(int n)
Return the address of the corresponding array element (to be filled externally via
CTMCGROUTDoc::ReadGraph1); NULL for an incorrect n.
BOOL IsFreqCorrect(void)
Checks that all the variables have the same number of points and matching frequencies
(with a relative accuracy of 1e-15). Returns TRUE/FALSE.
BOOL IsGraphDifferent(void)
TRUE if the second character of the expression is { (the special "difference" graph
mode).
Computing the value at point nPoint
Each Y type has its own method; they all assemble the string "mask₀ (value₁) mask₁
(value₂) …" and evaluate it via i1nte_atof_1 (exprint):
| Method | What it substitutes |
|--------|---------------------|
| double GetExpressionValue(int n) | Substitutes the frequency {f=(…)} (initialization) |
| double GetExpressionValueSM(int n) | The magnitude cabsv(S) |
| double GetExpressionValueL(int n) | The losses −20·lg|S| |
| double GetExpressionValueK(int n) | The VSWR (1+|S|)/(1−|S|) (with protection for |S|≈1) |
| double GetExpressionValueSFR(int n) | The phase, radians (with "unwrapping" via GetCPhase) |
| double GetExpressionValueSFD(int n) | The phase, degrees |
| double GetExpressionValueSFR_User/SFD_User(int n) | The phase without unwrapping (via GetCPhase_User) |
Return: a real value; on an evaluation error they set IsError=TRUE and return 0.
double GetCPhase(int i, int nPoint) (private)
Returns the "unwrapped" (continuous) phase of variable i at point nPoint: sums the
transitions through 2π.
double GetCPhase_User(int i, int nPoint) (private)
Returns the "raw" phase cphase(S) without unwrapping.
void DeleteData(void) / BOOL Init1Data(void) / int CalcNGraphExpession(void) (private)
Freeing the memory / filling the masks and variables / counting the number of variables by the brackets.
11. Global functions (in TMCGROUTView.cpp)
Declared in TMCGROUTView.h, they write text to the status bar of the main window.
| Function | Purpose |
|---|---|
void PutTrace(CString csTrace) |
Outputs text into panel 0 of the status bar (the cursor coordinates) |
void PutTrace(char *szTrace) |
The same, an overload for a C string |
void PutStatistics(CString csTrace) |
Outputs text into panel 1 of the status bar (the graph type) |
void PutStatistics(char *szTrace) |
The same for a C string |
Also, Tmcgrviw.h declares auxiliary global path functions (MakeRelatPathFile,
MakeFullPathFile, SelectDirName, CalcNDirInPathName, RunExeFileG, CreatProcG)
— their implementation may be in other modules of the package.
12. The .soc document file format
A text file. The first line is the signature #TMCGROUT. Then:
- parameter lines of the form #Key value (recognized by SetOneReadGraphParameters by
the prefixes from Tmcgrviw.h): the units and the X-axis name, the point flags, the
axis types, the limits Xmin/Xmax/Ymin/Ymax, the auto-scale flags, the editor name,
the font, the colors (text/background/axes/grid/points) and the 16-line parameters;
- comments — lines starting with ! (or the part of a line after !);
- graph lines: file_name [caption] [OutFlag] inp1 mod1 inp2 mod2. A name in curly
braces {…} means an expression graph.
The appearance parameters are duplicated into the registry HKCU\…\#TMCGROTS (to be
used as "defaults" in new documents), where the lines are separated by the ¦ character
(0xA6).