Программа PlanarRT_H — API-документация

Пакет TMC Suite. Счётное ядро для электродинамического расчёта планарных структур в H-поляризации (скалярная задача) во временно́й области. Выходной файл: tmc_rth.exe. Язык документации: русский. Все сигнатуры приведены по исходникам из src/kernels/PlanarRT_H/ и общим заголовкам из src/Include/.

Примечание про общий код H и X. PlanarRT_H и PlanarRT_X — это две копии одной кодовой базы (папки src/kernels/PlanarRT_H/ и src/kernels/PlanarRT_X/). Бо́льшая часть файлов в копиях побайтно идентична, но вычислительное ядро различается по содержимому (см. planar_rt_x.md, §2): в X-копии методы тактов 2/3 добавлены прямо в код, без условной компиляции. Содержательно различаются файлы: - TmcRTHRectNode.cpp/.h — 4 подшага вместо 2, массивы большего размера; - TmcRTHNodeDiel.cpp/.h — структура узла без rUo, методы тактов 2/3, блоки *_STAT_Y; - PlanRT_H.cpp — единственное отличие: SetRegistryKey("PlanarRT_H") SetRegistryKey("PlanarRT_X") (раздел реестра настроек).

Остальные файлы (PlanRT_HView.cpp, TmcDialogStatistics.cpp) различаются только пробельными символами. Данная документация описывает H-вариант (2 подтакта на цикл 1T).


1. Назначение программы

PlanarRT_H (tmc_rth.exe) — счётное ядро пакета TMC Suite, выполняющее электродинамический расчёт планарных (двумерных) структур в поляризации H (скалярная задача — одна компонента поля H_z).

Ядро решает задачу распространения электромагнитных волн в двумерном пространстве с произвольным распределением диэлектрической проницаемости (ε), магнитной проницаемости (μ) и проводимости (σ) на основе уравнений Максвелла в конечно-разностной формулировке во временно́й области.

Программа построена по схеме MFC Document/View (MDI). Каждый документ — это .tpl-шаблон (template), описывающий топологию расчётной области, параметры расчёта и выходные данные. Программа умеет:

  • читать .tpl-шаблоны (с препроцессингом через библиотеку PREPR);
  • строить расчётную сетку (nX × nY узлов) и присваивать каждому узлу диэлектрические параметры;
  • выполнять пошаговый или полный расчёт (Run Step / Run All) в отдельном рабочем потоке;
  • записывать выходные данные: временно́е описание сигнала (.t), распределение поля (.ex), топологию (.tt), S-матрицу (.s);
  • экспортировать данные для расчёта диаграммы направленности (ExportToDirectionalPatter, реализация — CFieldIntegrated библиотеки TMCIndan);
  • воспроизводить звуковые эффекты при завершении шага/расчёта (настраиваемые мелодии);
  • запускать внешние вьюверы (TMCROS — сигнал, TMCGROUT — S-матрица, FieldView — поле, TMC_DN — диаграмма направленности) и внешний редактор.

H-поляризация — скалярная задача: на каждом узле сетки хранится одно значение поля. Алгоритм использует 2 подтакта на каждый временно́й цикл 1T (в X-моде — 4, см. planar_rt_x.md).


2. Состав проекта

Файл проекта: PlanRT_H.vcxproj (имя проекта PlanRT_H, цель <TargetName>tmc_rth</TargetName>).

Файл Класс / содержимое Назначение (кратко)
PlanRT_H.cpp/.h CPlanRT_HApp Класс приложения, InitInstance, шаблон документа, SetRegistryKey("PlanarRT_H")
MainFrm.cpp/.h CMainFrame Главное MDI-окно: тулбар, статусбар
ChildFrm.cpp/.h CChildFrame Дочернее MDI-окно документа
PlanRT_HDoc.cpp/.h CPlanRT_HDoc Документ: управление расчётом, запуск внешних программ
PlanRT_HView.cpp/.h CPlanRT_HView Вид: обработчики меню, отрисовка (фон), конфигурация
TmcRTHRectNode.cpp/.h CTmcRTHRectNode Основное вычислительное ядро: сетка, шаг расчёта, рассеяние, возбуждение, S-матрица
TmcRTHNodeDiel.cpp/.h CTmcRTHNodeDiel Обработчик блоков топологии: диэлектрики, металл, поглотители, входы; возбуждение входов
TmcRTH_DialogBlock.cpp/.h CTmcRTH_DialogBlock Диалог информации о блоке
TmcRTH_DialogFormatOutFile.cpp/.h CTmcRTH_DialogFormatOutFile Диалог формата выходных данных
TmcDialogStatistics.cpp/.h CTmcDialogStatistics Диалог статистики
TmcSoundEffProp.cpp/.h CTmcSoundEffProp Свойства звуковых эффектов (PropertySheet)
TmcSoundMel1.cpp/.h CTmcSoundMel1 Страница мелодии
Pl_iofor.cpp/.h Глобальные функции: форматы вывода, флаги командной строки, авто/демо/пакетный режимы
PL_GLFUN.CPP Глобальные функции: PutTrace, PutStatistics, звук, точки входа потоков
StdAfx.cpp/.h Прекомпилированный заголовок MFC
resource.h, PlanRT_H.rc Ресурсы

Кросс-проектные файлы (компилируются как часть проекта, подтверждено в .vcxproj):

Файл Назначение
../../viewers/Tmcrtout/TmcSMatrix.cpp Восстановление S-матрицы из временно́го сигнала
../../viewers/Tmcrtout/TmcTtoS.cpp Обёртка «время → S-матрица»

Зависимости (AdditionalDependencies): sfile95.lib, prepr.lib, exprint.lib, TMCIndan.lib, TMCLibError.lib.

Препроцессорные определения: WIN32;_WINDOWS;DEBUG__1 (плюс _DEBUG/NDEBUG по конфигурации). Дополнительных макросов X-моды у H-проекта нет.

Общие заголовки из src/Include/ (перечислены в .vcxproj как ClInclude, но физически находятся в общем каталоге и документируются отдельно):

Запись ClInclude Где находится Назначение
TmcRTH_BolckList.h src/Include/TmcRTH_BolckList.h Описание списка блоков топологии — общий заголовок библиотеки TMCIndan (класс CTmcRTH_BlockList). Локальной копии в каталоге проекта нет; документация — docs/api/libs/tmcindan.md
Typerth.h src/Include/Typerth.h Общие типы, константы и глобальные функции (см. §3)

Файлы вне сборки (legacy). В каталоге src/kernels/PlanarRT_H/ физически присутствуют, но НЕ включены в PlanRT_H.vcxproj (нет ни ClCompile, ни ClInclude):

Файл Класс Статус
TmcErrorMessage.cpp/.h CTmcErrorMessage Диалог «О программе» / сообщений об ошибках. В сборку не входит, в исходном коде ядра не подключается (#include); упоминается только в файле ClassWizard PlanRT_H.clw. Считать неиспользуемым кодом. → см. §12, п. 11

3. Ключевые типы и константы (заголовок src/Include/Typerth.h)

3.1. Точность вычислений

//#define _PREC_DOUBLE          // выключено
#define _PREC_FLOAT             // включено: точность float

#ifdef _PREC_FLOAT
#define _real float             // базовый тип точности
#endif

#define _ELEM_VAL_RTH_REAL      // включено: элемент поля — вещественный
//#define _ELEM_VAL_RTH_INT     // выключено: целочисленный вариант (с множителем 1024*1024)

#ifdef _ELEM_VAL_RTH_REAL
#define _ELEM_VAL_RTH _real     // тип элемента поля = float
#define _ELEM_VAL_RTH_MULT 1
#endif

Также в Typerth.h выбран вариант сборки _VERSION_PROF___ (закомментированы _VERSION_DEMO___ и _VERSION_EDUC___).

3.2. Физические константы

Константа Значение Смысл
C0___ 299792458 Скорость света (м/с)
MU0___ 12.566370614e-7 Магнитная постоянная (Гн/м)
EPS0___ 8.854187817e-12 Электрическая постоянная (Ф/м)
PI___ 3.141592653589 Число π
ELECTRON_Q___ 1.602176565e-19 Заряд электрона (Кл) — используется только X-ядром
ELECTRON_M___ 9.10938356e-31 Масса электрона (кг) — используется только X-ядром

ELECTRON_Q___ и ELECTRON_M___ — это константы, а не переключатели режима. Подробнее об их роли в X-моде и о макросах проекта X — planar_rt_x.md, §2.

3.3. Типы узлов (nType)

Значения поля nType структуры узла и блока (совпадают со значениями nType класса CTmcRTH_Input библиотеки TMCIndan):

Значение Смысл
0 Диэлектрик, ε < 0
1 Диэлектрик, ε > 0
-1 Металл
-2 Поглотитель
-3 Вход X слева (направление >)
-4 Вход X справа (направление <)
-5 Вход Y сверху (направление V)
-6 Вход Y снизу (направление ^)

3.4. Глобальные функции Typerth.h (реализация — PL_GLFUN.CPP)

Функция Назначение
void PutTrace(CString) / void PutTrace(char*) Вывод строки трассировки в панель 0 статусбара главного окна
void PutStatistics(CString) / void PutStatistics(char*) Вывод статистики в статусбар
void PutSinchronizFlag(BOOL bTopologyFlag, BOOL bFieldFlag1, BOOL bSinchFlag1) Индикация в статусбаре состава вывода: «Output: Signal [+ Topology] [+ Field] [+ Sinchronization]»
void PutModel(void) / CString GetModel(void) Строка модели/версии
void ReadSystemType(void) Чтение типа системы
void BeepStepEnd(int i) / void BeepAllEnd(void) Звуковое уведомление о завершении шага / всего расчёта
void s_alarm(int) / void s_play(int far*) / void s_tone(int freq, int time) Низкоуровневое воспроизведение звука (остатки win16-кода: far)
Set/GetMelody1Interval, Set/GetMelody1, Set/GetMelody2Interval, Set/GetMelody2 Настройка двух мелодий уведомлений
SetAutoStartRunOn/Off(), SwitchAutoStartRunFlag(), BOOL IsAutoStartRun() Автозапуск расчёта при открытии документа
void SetDeltaT(char*) / void SetDeltaT(double) / double GetDeltaT() / BOOL IsDeltaTDefine() / void SwitchDeltaT() Управление шагом времени Δt (в т.ч. из командной строки)
BOOL IsPointInTr(x1,y1, x2,y2, x3,y3, x0,y0) Геометрический предикат: лежит ли точка (x0,y0) внутри треугольника
UINT ReadDataGlobal(LPVOID) Точка входа потока чтения данных; pParam — указатель на CPlanRT_HDoc; вызывает pDoc->ReadData()
UINT RunStepGlobal(LPVOID) Точка входа потока одного шага; вызывает pDoc->RunStep()
UINT RunAllGlobal(LPVOID) Точка входа потока полного расчёта; вызывает pDoc->RunAll()
UINT RunStepGlobalOneTacts(LPVOID) Точка входа потока шага по одному такту

3.5. Глобальные функции Pl_iofor.h (реализация — Pl_iofor.cpp)

Форматы текстового вывода (по умолчанию заданы константами FORMAT_OUT_FILE_*):

Константа Значение по умолчанию Поле
FORMAT_OUT_FILE_NTFORMAT "%9d" Номер такта nT
FORMAT_OUT_FILE_DTCurrentFORMAT "%15.7g" Текущее время
FORMAT_OUT_FILE_NBFORMAT "%4d" Номер блока
FORMAT_OUT_FILE_DINPFORMAT "%15.7g" Входной сигнал
FORMAT_OUT_FILE_DOUTFORMAT "%15.7g" Выходной сигнал
FORMAT_OUT_FILE_DFLDOUTFORMAT "" Поле (пусто — бинарный вывод)
Функция Назначение
SetnTFormat/GetnTFormat, SetdTcurrentFormat/GetdTcurrentFormat, SetnBFormat/GetnBFormat, SetdInpFormat/GetdInpFormat, SetdOutFormat/GetdOutFormat, SetdFieldOutFormat/GetdFieldOutFormat Установка/чтение printf-форматов выходных файлов
void SetDefaultOutputFormat(void) Сброс всех форматов к значениям по умолчанию
SetAutoRunOn/Off(), SwitchAutoRunFlag(), BOOL IsAutoRun() Авто-режим
SetDemoRunOn/Off(), BOOL IsDemoRun() Демо-режим
SetBatchRunOn/Off(), SwitchBatchRunFlag(), BOOL IsBatchRun() Пакетный (batch) режим
void Set_CommandLine_Flags(char *lpszCmdLine) Разбор флагов командной строки
CMainFrame *GetMainFramePointer__() / SetMainFramePointer__(CMainFrame*) Доступ к главному окну из глобального кода
void SetProcessInformation(PROCESS_INFORMATION) / PROCESS_INFORMATION GetProcessInformation() Данные запущенного внешнего процесса (вьювера)
void SetPointerClassView(CPlanRT_HView*) Регистрация указателя на вид
void RunOnViewField1(void) Вызов команды «View Field 1» извне

4. Структуры данных узлов (TmcRTHNodeDiel.h)

4.1. sTmcRTHNodeDielOne — узел (H-поляризация, 2 такта)

struct STMCRTH_NODEDIELONE
{
    _ELEM_VAL_RTH rU;       // падающее напряжение на диэлектрике (такт 0)
    _ELEM_VAL_RTH rU_Cur;   // текущее напряжение
    _ELEM_VAL_RTH rU_Cur1;  // напряжение такта «текущий+1»
    _ELEM_VAL_RTH rUo;      // рассеянное напряжение (для входов)
    _real rY;               // проводимость узла
    int   nNodeGlobal;      // номер узла в глобальной топологии
    int   nType;            // тип узла (см. §3.3)
};
typedef struct STMCRTH_NODEDIELONE sTmcRTHNodeDielOne;

В H-варианте — 4 компоненты напряжения (rU, rU_Cur, rU_Cur1, rUo). В X-варианте — 8 (rU..rU3, rU_Cur..rU_Cur3), а поле rUo отсутствует (см. planar_rt_x.md, §3.1).

4.2. sTmcRTH_DielNodeList — односвязный список узлов

struct STMCRTH_DIELNODELIST
{
    STMCRTH_DIELNODELIST * pcDielNodeNextList;  // следующий элемент списка
    sTmcRTHNodeDielOne   * pcNodeDielOne;       // узел
};
typedef struct STMCRTH_DIELNODELIST sTmcRTH_DielNodeList;

5. Класс CTmcRTHRectNode — вычислительное ядро

Назначение: управление расчётной сеткой, выполнение шагов расчёта во временно́й области, рассеяние, возбуждение входов, запись выходных файлов и расчёт S-матрицы. Заголовок: TmcRTHRectNode.h · Базовый класс: CWnd Зависит от: Typerth.h, TmcRTHNodeDiel.h, TmcLibError.h, TmcRTH_Indan.h, TmcRTH_IndanParam.h

5.1. Поля (private)

Поле Тип Назначение
cIndan CTmcRTH_Indan Менеджер входных данных (.tpl) — библиотека TMCIndan
cParam CTmcRTH_IndanParam Параметры расчёта (секция PARAM)
cError CTmcLibError Накопитель ошибок
pcNodeDiel CTmcRTHNodeDiel* Массив обработчиков блоков (по одному на блок топологии)
nDiel int Число блоков
nTCurrent int Текущий номер такта времени
nTMax int Максимальный такт (конец расчёта)
dT double Шаг времени Δt
dTCurrent double Текущее физическое время
nX / nY int Число узлов сетки по X / Y
dDelta double Пространственный шаг (Δ = Δx = Δy)
dXmin / dXmax / dYmin / dYmax double Границы расчётного прямоугольника
nNumNode int Общее число узлов = nX × nY
prUNode1Temp _ELEM_VAL_RTH* «Сырой» указатель массива напряжений (хранится для delete[])
prUNode1 _ELEM_VAL_RTH* Рабочий указатель массива напряжений, выровнен на 32 байта
prYNodeTemp _real* «Сырой» указатель массива проводимостей
prYNode _real* Рабочий указатель массива проводимостей, выровнен на 32 байта
bIsReadData volatile BOOL Флаг «данные загружены» (volatile — общение между потоками)
bIsRunStep1Run volatile BOOL Флаг «шаг выполняется»

Выделение массивов (InitNodeArray): запрашивается 2*nNumNode + 32 элементов (по 2 значения на узел плюс запас), после чего рабочий указатель смещается так, чтобы адрес был кратен 32 — выравнивание для эффективного доступа. В X-варианте — 6*nNumNode + 32 (по 6 значений на узел).

5.2. Публичные методы

Метод Назначение
CTmcRTHRectNode() / virtual ~CTmcRTHRectNode() Конструктор / деструктор
void ReadData(CString csFileName, int nStep1) Чтение .tpl-файла csFileName, установка номера шага nStep1, инициализация расчёта
void ReadData(void) Перечитывание текущего файла
void RunStep(void) Выполнение шага расчёта (до nTMax)
void Stop(void) Остановка расчёта (сброс bIsReadData)
BOOL IsReadData(void) TRUE, если данные загружены
BOOL IsRunStep(void) TRUE, если шаг выполняется
BOOL IsError(void) TRUE при накопленной ошибке (cError.IsError())
CString GetErrorMessage(void) Текст ошибки
int GetNStepMax(CString csFileName) Максимальное число шагов для данного файла
CTmcRTH_IndanOutput* GetOutput(void) Доступ к подсистеме выходных данных
CTmcRTH_IndanParam& GetParam(void) Доступ к параметрам
CTmcRTH_IndanTopology& GetTopology(void) Доступ к топологии
void ExportToDirectionalPatter(void) Экспорт для диаграммы направленности: cIndan.GetOutput()->GetFieldIntegrated().ExportToDirectionalPattern(cParam)
BOOL GetTopologyFlag(void) Флаг вывода топологии
BOOL GetSoundEffect(void) Флаг звуковых эффектов
BOOL GetFieldFlag(void) Флаг вывода поля
BOOL GetSinchronizationFieldOutput(void) Флаг синхронного вывода поля
void PutTopol(void) Запись файла топологии
void OnOffSoundEffects(void) Переключение звуковых эффектов
void OnOffSinchronizationFieldOutput(void) Переключение синхронизации вывода поля
void OnOffFieldOutput(void) Переключение вывода поля

Примечание к названию: ExportToDirectionalPatter — так в коде (без конечной n); внутренняя функция TMCIndan называется ExportToDirectionalPattern.

5.3. Приватные методы

Чтение и инициализация:

Метод Назначение
void ReadTopologySection(void) Чтение секции TOPOLOGY
void ReadParamSection(void) Чтение секции PARAM
void ReadLinkListSection(void) Чтение секции LINK_LIST
void ReadOutputSection(void) Чтение секции OUTPUT
void SetStepNumber(int nStep) Установка номера шага
void InitKernel(void) Инициализация ядра перед расчётом
void InitNodeArray(void) / void DeleteNodeArray(void) Выделение/освобождение массивов узлов (с выравниванием, см. §5.1)
void InitDielArray(void) / void DeleteDielArray(void) Выделение/освобождение массива блоков pcNodeDiel
void SetDielTopology(void) Присвоение узлам параметров по блокам
void SetDielInNodeList(void) Включение узлов блоков в общий список
void DeleteDielList(sTmcRTH_DielNodeList **pcNodeDielList1) Освобождение списка узлов
BOOL IsDataInit(void) Проверка инициализации данных
void DeleteData(void) Полное освобождение данных

Расчётный цикл:

Метод Назначение
void RunKernel(void) Главный цикл: for(; nTCurrent < nTMax; ...) RunKernel1T(); затем PutSmatrix(). Каждые 100 тактов выводит прогресс и затраченное время через PutTrace/PutStatistics
void RunKernel1T(void) Один цикл 1T = 2 подтакта (см. §5.4)
void RunStep1(void) Выполнение одного шага (обёртка с установкой флагов)
void RunExciteInputs(void) / void RunExciteInputs1(void) Возбуждение входов (подтакты 0 и 1)
void RunScatteringNode(void) / void RunScatteringNode1(void) Рассеяние на узлах сетки (подтакты 0 и 1)
near void RunScatteringNode1line(_ELEM_VAL_RTH *pr_111, _real *prY_111, int nx_111, int nX_111) Рассеяние по одной строке сетки (подтакт 0). pr_111 — массив напряжений строки, prY_111 — проводимости, nx_111 — индекс строки, nX_111 — длина строки. Квалификатор near — остаток win16
near void RunScatteringNode1line1(...) То же для подтакта 1 (параметры идентичны)
void RunBlockNode(void) / void RunBlockNode1(void) Обработка блоков: вызов CTmcRTHNodeDiel::RunBlockNode/RunBlockNode1 для каждого блока (подтакты 0 и 1)

Вывод:

Метод Назначение
void PutField(int ii) Запись распределения поля подтакта ii (0 или 1)
void PutSmatrix(void) Расчёт и запись S-матрицы: cIndan.GetOutput()->PutSmatrix()
void PutTopology(void) Запись файла топологии (.tt)
void DistributionIntegrated(int ii) Накопление интегрированного распределения поля (для диаграммы направленности)
void OutputnT(void) Вывод номера текущего такта
void DeleteOutputFile(void) Удаление выходных файлов перед перезапуском
BOOL IsFieldFileRead(void) Проверка чтения файла поля
void PutStepEndSound(void) Звук завершения шага

5.4. Алгоритм одного цикла 1T (H-поляризация, 2 подтакта)

Точная последовательность из RunKernel1T() (TmcRTHRectNode.cpp:537):

Подтакт 0:
  RunExciteInputs();          // возбуждение входов
  RunScatteringNode();        // рассеяние на узлах
  RunBlockNode();             // обработка блоков
  PutField( 0 );              // запись поля
  DistributionIntegrated(0);  // накопление для ДН
  nTCurrent++;  dTCurrent += dT;

Подтакт 1:
  RunExciteInputs1();
  RunScatteringNode1();
  RunBlockNode1();
  PutField( 1 );
  DistributionIntegrated(1);
  nTCurrent++;  dTCurrent += dT;

Счётчик nTCurrent увеличивается внутри каждого подтакта на 1 (итого +2 за цикл 1T). По завершении главного цикла RunKernel вызывает PutSmatrix().

В X-моде: 4 подтакта (+4 за цикл), вызовы DistributionIntegrated закомментированы (см. planar_rt_x.md, §4).


6. Класс CTmcRTHNodeDiel — блоки топологии

Назначение: представление одного блока топологии (прямоугольник, круг, полигон; диэлектрик, металл, магнетик, поглотитель, вход) — список его узлов, проводимости, возбуждение входов. Заголовок: TmcRTHNodeDiel.h · Базовый класс: CWnd

6.1. Поля (private)

Поле Тип Назначение
cError CTmcLibError Ошибки блока
nBlock int Номер блока
csBlock CString Тип блока (ключевое слово из .tpl: RECT, CIRCLE, POLYGON, …)
nNumNode int Число узлов в блоке
pcNodeDielOne sTmcRTHNodeDielOne* Массив узлов блока
dXCenter / dYCenter double Координаты центра блока
dYInput double Проводимость входного блока
dTmin / dTmax double Диапазон времени возбуждения входа
csEpsExpr CString Выражение для ε (вычисляется библиотекой exprint)
csW CString Угловая скорость (вращающийся блок)
csVx / csVy CString Линейные скорости центра вращения
nX0 / nY0 int Центр вращения (x0, y0)
nTxCurrent / nTyCurrent int Счётчики движения блока по X / Y
nTxMove / nTyMove int Периоды движения блока по X / Y
nType int Тип блока (см. §3.3)
dY1_InputAdmitance double Проводимость входа (вспомогательная)
dWidthWaveg double Ширина волновода (для входа)
dUnormir double Нормировка напряжения возбуждения
csFileNameEps CString Имя .eps-файла (блок из файла)
dX0 / dY0 double Координаты (вспомогательные)
pbIsStop volatile BOOL* Указатель на флаг остановки (из ядра)

6.2. Публичные методы

Метод Назначение
CTmcLibError& SetBlock(CTmcRTH_BlockList *pcNextBlockList, CTmcRTH_IndanParam &cParam, CTmcRTH_IndanOutput *cOut, _real *prYNode, volatile BOOL *pbStopFlag, CString csCurrentPath) Инициализация блока по описанию из .tpl (CTmcRTH_BlockList — TMCIndan): определяет тип, строит список узлов, заполняет проводимости prYNode. csCurrentPath — путь для поиска .eps-файлов
CTmcLibError& SetBorderXmin(int nX, int nY) / SetBorderXmax(int nX, int nY) / SetBorderYmax(int nX, int nY) / SetBorderYmin(int nX) Обработка границ расчётной области
void SetBlockInDielList(sTmcRTH_DielNodeList **pcNodeDielList, int nNumNode1, CTmcLibError &cError1) Включение узлов блока в общий список узлов ядра
void ExciteInputs(CTmcLibError &cError1, double dWT, double dT, _ELEM_VAL_RTH *pr1, int nX, CTmcRTH_IndanParam &cParam, double dtCurrent) Возбуждение входных узлов, подтакт 0. dWT — круговая частота × время, dT — шаг времени, pr1 — массив напряжений, dtCurrent — текущее время
void ExciteInputs1(...) То же, подтакт 1 (сигнатура идентична)
void RunBlockNode(_ELEM_VAL_RTH *prUNode1, _real *prYNode, int nX, int nArraySize) Обновление напряжений узлов блока, подтакт 0
void RunBlockNode1(...) То же, подтакт 1
void AddCurrentPath(CString csCurrentPath) Задание текущего пути (поиск .eps)
CTmcLibError& GetError(void) Доступ к ошибкам
void DeleteData(void) Освобождение данных блока

В X-варианте дополнительно: ExciteInputs2/3, RunBlockNode2/3 (см. planar_rt_x.md, §5).

6.3. Приватные методы (по типам блоков)

Метод Назначение
SetRect() / SetCirc() / SetPoly() Диэлектрический блок (прямоугольник / круг / полигон)
SetRectMetal() / SetCircMetal() / SetPolyMetal() Металлический блок
SetRectMagnetic() / SetCircMagnetic() / SetPolyMagnetic() Магнитный блок
SetRectAbsorber() / SetCircAbsorber() / SetPolyAbsorber() Поглотитель
SetRectFile() Блок с распределением ε из .eps-файла
SetInpXLeft() / SetInpXRight() / SetInpYTop() / SetInpYBot() Входные блоки (4 направления)

Все методы Set* принимают CTmcRTH_BlockList *pcNextBlockList (описание блока) и CTmcRTH_IndanParam &cParam (параметры), возвращают CTmcLibError&; SetRect/SetRectFile дополнительно принимают CString csCurrentPath, методы входов — CTmcRTH_IndanOutput *cOut.

Вспомогательные приватные методы:

Метод Назначение
double SetInputAdmitance(double dFreq, double dDelta) Расчёт проводимости входа
double SetAbsorberAdmitance(double dFreq, double dDelta) Расчёт проводимости поглотителя
void CalculateYForInput(double dFreq, double dDelta) Проводимость входных узлов
void SetYForInput(CTmcRTH_IndanParam&) / void SetYLineForDiel(CTmcRTH_IndanParam&, _real *prYNode) Заполнение массивов проводимостей
_real CalcEps(double x, double y, CTmcRTH_IndanParam &cParam) Вычисление ε в точке (x, y) по выражению csEpsExpr
double dFaza(CTmcRTH_IndanParam&, double dtCurrent) / double dAmplitude(...) Фаза и амплитуда сигнала возбуждения в момент времени dtCurrent
void SetnType(void) Установка типа узлов блока
void SetAbsorberNodeType(CTmcRTH_IndanParam&) / void SetMagneticPolygonType(CTmcRTH_IndanParam&) Типы узлов поглотителя / магнитного полигона
void CalculatedXYCenter(CTmcRTH_IndanParam&) Вычисление центра блока
void AddList(sTmcRTHNodeDielOne*, sTmcRTH_DielNodeList**) Добавление узла в список
void OutputUpUo(double dUp, double dUo, CTmcLibError&) Вывод падающего/рассеянного напряжений
double atan2__1(double y, double x) Вариант atan2
void SeachEpsFileName(CString) / void AddFileEpsExtention(void) / BOOL IsFullName(void) Поиск и нормализация имени .eps-файла
void SaveFileRect(...) Сохранение прямоугольника в файл
void DeleteDublicateData(void) / void DeleteStatDielData(void) Очистка дублирующихся/статических данных

6.4. Формат .eps-файла (распределение ε)

Константы формата определены в начале TmcRTHNodeDiel.h:

#define TMC_RTH_EPSFILE_EXT_   "eps"
#define TMC_RTH_EPSFILE_ID_    "#TamicRTH_planar_DistributionDielectricPermeability_File_V2.00 2000"
#define TMC_RTH_EPSFILE_TYPE_  "#TopologyPrimitiv "
#define TMC_RTH_EPSFILE_Delta_ "#dDelta "
#define TMC_RTH_EPSFILE_XMIN_  "#Xmin "
#define TMC_RTH_EPSFILE_YMIN_  "#Ymin "
#define TMC_RTH_EPSFILE_NX_    "#nX "
#define TMC_RTH_EPSFILE_NY_    "#nY "
#define TMC_RTH_EPSFILE_NPoint_ "#nPoint "
#define TMC_RTH_EPSFILE_NAccur_ "#nAccuracy "
#define TMC_RTH_EPSFILE_NdFrmt_ "#sNodeFormat "
#define TMC_RTH_EPSFILE_VlFrmt_ "#sValueFormat "

Файл начинается с идентификатора #TamicRTH_planar_..., далее — параметры сетки (#dDelta, #Xmin, #Ymin, #nX, #nY, число точек, точность, форматы узла/значения), затем данные.

Точная раскладка. Заголовок — текстовый, каждая строка завершается парой байт 13, 10 (CR LF). Пробел после метки значим. Порядок и смысл полей (сверено с авторским описанием Tamic\TMC\DISTR\MANUALS\RT_HPLANAR\FormEps.doc, 1999, и с кодом TmcRTHNodeDiel.cpp:6811 — запись, :7227 — чтение):

Метка Пример значения Смысл
#TamicRTH_planar_DistributionDielectricPermeability_File_V2.00 2000 Метка файла. В описании 1999 г. — версия V1.00; в коде V2.00 2000
#TopologyPrimitiv RECT_STAT Тип топологического примитива
#dDelta 0.0005 Пространственный дискрет, в метрах
#Xmin 0 Абсцисса самой левой точки, в метрах
#Ymin 0 Ордината самой нижней точки, в метрах
#nX 33 Число точек по оси X
#nY 13 Число точек по оси Y
#nPoint 429 Число точек в примитиве (обычно nX * nY)
#nAccuracy 8 Число байт в значении: 8 — двойная точность, 4 — одинарная. Пишется как sizeof(_real)
#sNodeFormat NULL Зарезервированная строка
#sValueFormat NULL Зарезервированная строка

Далее — бинарный массив из #nPoint записей. Каждая запись:

Поле Размер Содержимое
значение #nAccuracy (8 или 4) взвешенное значение (_real)
номер узла 4 (int) глобальный номер узла в примитиве

Итого размер массива — #nPoint * (#nAccuracy + 4) байт: 12 байт на точку для двойной точности, 8 — для одинарной.

Записывается не «чистая» ε, а взвешенное значение. В TmcRTHNodeDiel.cpp:6837–6847 поле rY инициализируется единицей, затем делится пополам на каждой границе примитива (i == 0, i == nY-1, j == 0, j == nX-1 — то есть у рёбер коэффициент 0.5, в углах 0.25) и лишь потом умножается на CalcEps(x, y). Не интерпретируйте содержимое как ε напрямую.

Совместимость float double. Читатель сверяет #nAccuracy с sizeof(_real) и при несовпадении конвертирует (TmcRTHNodeDiel.cpp:7354 и ветка case 4: — чтение во float с расширением до _real). Поэтому .eps, созданные старой одинарной сборкой, читаются текущей двойной. Допустимы только значения 4 и 8 — иначе ошибка nAccuracy = %d != 4 and != 8.


7. Класс CPlanRT_HDoc — документ

Назначение: управление расчётом (через cRectNode), запуск внешних программ, хранение настроек. Заголовок: PlanRT_HDoc.h · Базовый класс: CDocument

7.1. Поля (private)

Поле Тип Назначение
cRectNode CTmcRTHRectNode Вычислительный объект
nStep int Текущий шаг
bIsReadData volatile BOOL Флаг загрузки данных
csEditorName CString Внешний текстовый редактор (.tpl)
csExternViewer CString Вьювер сигналов (TMCROS)
csExternViewerField CString Вьювер полей (FieldView)
csExternViewerSmatrix CString Вьювер S-матриц (TMCGROUT)
csExternViewerDirectPattern CString Вьювер диаграмм направленности (TMC_DN)

7.2. Настройки в реестре

Раздел задаётся в InitInstance: SetRegistryKey("PlanarRT_H"). Имена параметров — константы в PlanRT_HDoc.h:

Константа Имя параметра Содержимое
PLANRT_H_RAZDEL_INI PlanRT_H Config Имя секции
PLANRT_H_EXTERNEDITORNAME_INI ExternEditorName Путь к редактору
PLANRT_H_EXTERNVIEWERNAME_INI ExternViewerName Вьювер сигналов
PLANRT_H_EXTERNFIELDVIEWERNAME_INI ExternFieldViewerName Вьювер полей
PLANRT_H_EXTERNDIRPATVIEWERNAM_INI ExternDirectPatViewerName Вьювер ДН
PLANRT_H_EXTERNSMVIEWERNAME_INI ExternSmatrixViewerName Вьювер S-матриц
PLANRT_H_BACKGROUNDCOLOR_INI BackGroundColor Цвет фона
PLANRT_H_OUTFORMATNT_INIPLANRT_H_OUTFORMATOUT_INI OutputFormatnT/dT/nB/dInp/dOut Форматы вывода (§3.5)
PLANRT_H_OUTFORMATOUTFILED_INI OutputFormatdOutField Формат вывода поля
PLANRT_H_OUTPUTSOUNDFLAG_INI SoundEffectsFlag Флаг звука
PLANRT_H_OUTFIELDSINCHRFLAG_INI OutputSinchrFlagdOutField Синхронный вывод поля
PLANRT_H_OUTFIELDFLAG_INI OutputFlagdOutField Флаг вывода поля
PLANRT_H_MNWNDSIZEPLACE_INI MainFrameSizeAndPlace__1 Положение главного окна

7.3. Методы

Управление расчётом:

Метод Назначение
void ReadData(void) Чтение .tpl (делегирует cRectNode)
void RunStep(void) / void RunAll(void) Шаг / полный расчёт
void Stop(void) Остановка
BOOL IsRun(void) / BOOL IsReadData(void) Флаги состояния
void BackStep(void) / void SkipStep(void) / void SetFirstStep(void) Навигация по шагам
int GetnStep(void) Текущий шаг
CString GetErrorMessage(void) Текст ошибки
CTmcRTHRectNode& GetRectNode(void) Прямой доступ к ядру
CTmcRTH_IndanOutput* GetOutput(void) / CTmcRTH_IndanParam& GetParam(void) / CTmcRTH_IndanTopology& GetTopology(void) Доступ к данным ядра
void ExportToDirectionalPatter(void) Экспорт для ДН
void CloseAndExit(void) Закрытие документа и выход

Флаги вывода и звука (делегируют cRectNode): GetTopologyFlag(), GetSoundEffect(), GetFieldFlag(), GetSinchronizationFieldOutput(), PutTopology(), SetSoundFlag(int), OnOffSoundEffects(), SetOutFieldOutFlag(int), SetOutSinchrFieldOutFlag(int), OnOffSinchronizationFieldOutput(), OnOffFieldOutput().

Внешние программы:

Метод Назначение
BOOL RunViewer(void) Запуск вьювера сигналов
BOOL RunViewerField(void) Запуск вьювера полей
BOOL RunViewerSmatrix(void) Запуск вьювера S-матриц
BOOL RunViewerDirectPattern(void) Запуск вьювера ДН
Set/GetExternEditorName, Set/GetExternViewer, Set/GetExternViewerField, Set/GetExternViewerSmatrix, SetExternViewerDirectionalpattern / GetExternViewerDirectPat Настройка путей внешних программ
BOOL RunExeFile(CString csNameExe) / BOOL RunExeFile(char*) / BOOL RunExeFile(CString, CString csArgCommLine) / BOOL RunExeFile(char*, char*) Запуск внешнего exe (4 перегрузки, с аргументами и без); внутри — CreatProc(char *lpszComLine) (private)

Переопределения MFC: OnNewDocument(), Serialize(CArchive&), OnCloseDocument(), CanCloseFrame(CFrameWnd*).


8. Класс CPlanRT_HView — вид

Назначение: обработчики меню/тулбара, отрисовка фона окна документа. Заголовок: PlanRT_HView.h · Базовый класс: CScrollView

8.1. Поля (private)

Поле Тип Назначение
cSoundDialog CTmcSoundEffProp Диалог звуковых эффектов
scBackgoundColor COLORREF Цвет фона
bIsReadData volatile BOOL Флаг загрузки

Приватные методы: OnDrawBackground(CDC*), ReadData(), WriteFile().

8.2. Команды меню (обработчики afx_msg)

Меню Run:

Метод Действие
OnRunStartstep Один шаг расчёта
OnRunAll Полный расчёт
OnRunStop Остановка
OnRunRestartstep / OnRunRestartall Перезапуск шага / всего расчёта
OnRunSkipstep / OnRunBackstep Пропуск шага / шаг назад

Меню View:

Метод Действие
OnViewStatistics Окно статистики (CTmcDialogStatistics)
OnViewOutput Выходной сигнал → внешний вьювер (TMCROS)
OnViewField / OnViewField1 Распределение поля → FieldView; также публичный OnViewField11(void) для вызова извне
OnViewTopology Топология
OnViewDirectionalpattern Диаграмма направленности → TMC_DN

Меню Config:

Метод Действие
OnConfigEditor Выбор внешнего редактора
OnConfigViewerOutputsignal / OnConfigViewerField / OnConfigViewerSmatrix / OnConfigViewerDirectionalpattern Выбор внешних вьюверов
OnConfigColorBackGround Цвет фона
OnConfigFormatOutputDataFile Формат выходных данных (CTmcRTH_DialogFormatOutFile)
OnConfigSinchronization Синхронизация вывода поля
OnConfigSound / OnConfigSoundMelody Звуковые эффекты / мелодия
OnConfigSmatrix Настройка S-матрицы
OnConfigAutorun Авто-режим
OnConfigSetup Общие настройки
OnConfigDirectionalpattern Настройка ДН

Прочее: OnEditEdit (открыть .tpl в редакторе), OnFileSaveAs, OnClose, OnDestroy, публичный Stop(void).

Обработчики OnUpdate* (доступность пунктов меню): OnUpdateConfigSinchronization, OnUpdateViewField, OnUpdateConfigSound, OnUpdateViewTopology, OnUpdateViewField1, OnUpdateRunRun, OnUpdateRunRestartall, OnUpdateRunStartstep, OnUpdateRunRestartstep, OnUpdateRunSkipstep, OnUpdateRunBackstep, OnUpdateRunStop, OnUpdateFileClose, OnUpdateConfigAutorun, OnUpdateViewDirectionalpattern.

Переопределения MFC: OnDraw(CDC*), PreCreateWindow, DestroyWindow, OnInitialUpdate, OnPreparePrinting, OnBeginPrinting, OnEndPrinting.


9. Диалоги

В сборку входят пять диалоговых классов (подтверждено по PlanRT_H.vcxproj). Класс CTmcErrorMessage в сборку не входит — см. §2, «Файлы вне сборки».

9.1. CTmcRTH_DialogBlock — информация о блоке топологии

Назначение: просмотр параметров одного блока топологии (тип, координаты вершин, выражение ε, скорости движения) с навигацией «предыдущий/следующий блок». Заголовок: TmcRTH_DialogBlock.h · Базовый класс: CDialog · Ресурс: IDD_TMC_RTH_TOPBLOCK

Поля (public):

Поле Тип Назначение
m_pcParam CTmcRTH_IndanParam* Параметры расчёта (TMCIndan)
m_pcBlockList CTmcRTH_BlockList* Отображаемый блок (TMCIndan)
i int Индекс текущего блока
dX[10] / dY[10] CString Рабочие массивы координат вершин

Поля DDX (обмен с элементами диалога):

Поле Тип Назначение
m_nBlock int Номер блока
m_nType int Тип блока (см. §3.3)
m_nMemory double Память, занятая блоком
m_nXY int Число узлов блока
m_csString CString Текстовое описание блока
m_csVx / m_csVy CString Линейные скорости центра
m_csW CString Угловая скорость вращения
m_csEpsExpr CString Выражение для ε
dX0 / dY0 double Координаты центра
dX1dX10 / dY1dY10 CString Координаты вершин (до 10)
csXminText / csXmaxText / csYminText / csYmaxText CString Подписи границ
dXmin / dXmax / dYmin / dYmax double Габариты блока
m_csLongUnit CString Единица длины

Методы:

Метод Назначение
CTmcRTH_DialogBlock(CWnd* pParent = NULL) Конструктор
void PrepareData(void) Заполнение полей диалога из m_pcBlockList и m_pcParam
void DoDataExchange(CDataExchange* pDX) DDX/DDV
void OnOK() Закрытие диалога
afx_msg void OnCancel1() Отмена
afx_msg void OnTmcblockbuttonnext() / OnTmcblockbuttonprev() Переход к следующему / предыдущему блоку

9.2. CTmcRTH_DialogFormatOutFile — формат выходных данных

Назначение: настройка printf-форматов столбцов выходных текстовых файлов (см. §3.5). Заголовок: TmcRTH_DialogFormatOutFile.h · Базовый класс: CDialog · Ресурс: IDD_TMC_CONFIG_OUTFFORMAT

Поля (public): BOOL IsSetDefaultFormat — признак сброса к форматам по умолчанию.

Поля DDX:

Поле Тип Формат столбца
m_csnT CString Номер такта nT
m_csdTcurrent CString Текущее время
m_csnBlock CString Номер блока
m_csdInp CString Входной сигнал
m_csdOut CString Выходной сигнал
m_csdOutField CString Поле

Методы:

Метод Назначение
CTmcRTH_DialogFormatOutFile(CWnd* pParent = NULL) Конструктор
void DoDataExchange(CDataExchange* pDX) DDX/DDV
afx_msg void OnSetDefaultFormat() Сброс всех форматов к значениям по умолчанию (SetDefaultOutputFormat, см. §3.5)

9.3. CTmcDialogStatistics — статистика расчёта

Назначение: сводка по текущему шагу расчёта: число узлов/блоков, память, физические параметры, размеры области в длинах волн, точность. Заголовок: TmcDialogStatistics.h · Базовый класс: CDialog · Ресурс: IDD_TMC_STATISTICS

Поля (public): CString csAccuracy (точность); int nFlagStep (флаг шага). Поля (private): CTmcRTH_BlockList * pcBlockList — блок для окна информации.

Поля DDX:

Поле Тип Назначение
m_nStep int Номер шага
m_nNumNode int Число узлов сетки
m_dMemory double Занятая память
m_nBlock int Число блоков
m_csErrorMessage CString Текст ошибки
m_cParam CTmcRTH_IndanParam Параметры (TMCIndan)
m_cTopol CTmcRTH_IndanTopology Топология (TMCIndan)
m_cOut CTmcRTH_IndanOutput* Подсистема вывода (TMCIndan)
dDelta, dFreq, dt, dtT double Шаг сетки, частота, шаг времени
dTsizeWL, dTsizeWL1, dXsizeWL, dYsizeWL double Размеры области в длинах волн
dXmin/dXmax/dYmin/dYmax, dTmin/dTmax double Границы области и времени
dWaveLen, dWaveLenDelt double Длина волны и её доля на шаг сетки
csTolerance CString Допуск

Методы:

Метод Назначение
CTmcDialogStatistics(CWnd* pParent = NULL) Конструктор
void PrepareData(void) Расчёт и заполнение полей статистики
void DoDataExchange(CDataExchange* pDX) DDX/DDV
afx_msg void OnViewBlockInformation() Открыть окно информации о блоке (CTmcRTH_DialogBlock)
afx_msg void OnStepPrev() / OnStepNext() Переход к предыдущему / следующему шагу
afx_msg void OnCancel1() Закрытие
void DeleteData(void) (private) Освобождение данных

Известный баг: кнопка статистики не работает в новых версиях H и X (окно не вызывается, приложение закрывается, при компиляции — предупреждения). См. ISSUES.md.

9.4. CTmcSoundEffProp — свойства звуковых эффектов

Назначение: контейнер-вкладка (PropertySheet) настроек двух мелодий уведомлений. Заголовок: TmcSoundEffProp.h · Базовый класс: CPropertySheet (DECLARE_DYNAMIC)

Поля (public): CTmcSoundMel1 cMelody1, CTmcSoundMel1 cMelody2 — две страницы мелодий (см. §9.5).

Методы:

Метод Назначение
CTmcSoundEffProp(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0) Конструктор с заголовком из ресурса
CTmcSoundEffProp(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0) Конструктор с текстовым заголовком
virtual ~CTmcSoundEffProp() Деструктор

9.5. CTmcSoundMel1 — страница мелодии

Назначение: страница настройки одной мелодии: интервал и 12 нот. Заголовок: TmcSoundMel1.h · Базовый класс: CPropertyPage (DECLARE_DYNCREATE) · Ресурс: IDD_TMC_SOUND_MELODY1

Поля (public): CString csMelodyName — имя мелодии.

Поля DDX:

Поле Тип Назначение
m_SoundInterval int Интервал между нотами
m_Note1m_Note12 int 12 нот мелодии

Методы:

Метод Назначение
CTmcSoundMel1() / ~CTmcSoundMel1() Конструктор / деструктор
void DoDataExchange(CDataExchange* pDX) DDX/DDV

10. Формат входного файла (.tpl)

Секции шаблона (разбираются методами Read*Section через библиотеку TMCIndan; детальное описание формата — docs/api/libs/tmcindan.md):

Секция Назначение
STEP Число шагов расчёта (nTMax)
PARAM Параметры: частота, Δ, Tmin/Tmax, Xmin/Xmax/Ymin/Ymax, высота, единицы измерения
TOPOLOGY Блоки: прямоугольники, круги, полигоны, входы, поглотители
LINK_LIST Связи между блоками
OUTPUT Конфигурация выходных файлов

Перед разбором файл проходит препроцессинг библиотекой PREPR (макроподстановки, промежуточный файл $$vr$$s.prc).


11. Форматы выходных файлов

Расширение Содержимое Потребитель
.t Временно́й сигнал TMCROS
.ex Распределение поля (бинарный, заголовок #TMC_GraphicsOutputFieldFile) FieldView
.tt Топология (имя формируется в TMCIndan: csFileNameTopology.Format("%s.tt", ...)) FieldView
.s S-матрица TMCGROUT
.eps Распределение ε (вход и выход, формат §6.4) ядро

Файлы .dop — это документы вьювера TMC_DN (диаграммы направленности); ядро напрямую .dop не пишет — экспорт данных для ДН выполняет CFieldIntegrated::ExportToDirectionalPattern (TMCIndan, см. docs/api/libs/tmcindan.md).

Запись выходных файлов реализована в подсистеме CTmcRTH_IndanOutput библиотеки TMCIndan.


The PlanarRT_H program — API documentation

TMC Suite package. A compute kernel for the electrodynamic computation of planar structures in H-polarization (a scalar problem) in the time domain. Output file: tmc_rth.exe. All signatures are taken from the sources in src/kernels/PlanarRT_H/ and the shared headers from src/Include/.

A note on the shared H and X code. PlanarRT_H and PlanarRT_X are two copies of one codebase (the folders src/kernels/PlanarRT_H/ and src/kernels/PlanarRT_X/). Most files in the copies are byte-for-byte identical, but the computation core differs in content (see planar_rt_x.md, §2): in the X copy the step 2/3 methods are added directly in the code, without conditional compilation. The files that differ in substance: - TmcRTHRectNode.cpp/.h — 4 sub-steps instead of 2, larger arrays; - TmcRTHNodeDiel.cpp/.h — the node structure without rUo, the step 2/3 methods, the *_STAT_Y blocks; - PlanRT_H.cpp — the only difference: SetRegistryKey("PlanarRT_H") SetRegistryKey("PlanarRT_X") (the settings registry key).

The other files (PlanRT_HView.cpp, TmcDialogStatistics.cpp) differ only in whitespace. This documentation describes the H variant (2 sub-steps per 1T cycle).


1. Purpose of the program

PlanarRT_H (tmc_rth.exe) is a compute kernel of the TMC Suite package that performs the electrodynamic computation of planar (two-dimensional) structures in H-polarization (a scalar problem — one field component H_z).

The kernel solves the problem of electromagnetic-wave propagation in a two-dimensional space with an arbitrary distribution of permittivity (ε), permeability (μ) and conductivity (σ), based on Maxwell's equations in a finite-difference time-domain formulation.

The program is built on the MFC Document/View (MDI) scheme. Each document is a .tpl template describing the topology of the computation area, the computation parameters and the output data. The program can:

  • read .tpl templates (with preprocessing via the PREPR library);
  • build the computation grid (nX × nY nodes) and assign dielectric parameters to each node;
  • perform a step-by-step or full computation (Run Step / Run All) in a separate worker thread;
  • write the output data: the time signal description (.t), the field distribution (.ex), the topology (.tt), the S-matrix (.s);
  • export data for the radiation-pattern computation (ExportToDirectionalPatter, the implementation — CFieldIntegrated of the TMCIndan library);
  • play sound effects on step/computation completion (configurable melodies);
  • launch external viewers (TMCROS — signal, TMCGROUT — S-matrix, FieldView — field, TMC_DN — radiation pattern) and an external editor.

H-polarization is a scalar problem: one field value is stored at each grid node. The algorithm uses 2 sub-steps for each 1T time cycle (in the X-mode — 4, see planar_rt_x.md).


2. Project composition

The project file is PlanRT_H.vcxproj (the project name PlanRT_H, the target <TargetName>tmc_rth</TargetName>).

File Class / contents Purpose (briefly)
PlanRT_H.cpp/.h CPlanRT_HApp The application class, InitInstance, the document template, SetRegistryKey("PlanarRT_H")
MainFrm.cpp/.h CMainFrame The main MDI window: toolbar, status bar
ChildFrm.cpp/.h CChildFrame The child MDI document window
PlanRT_HDoc.cpp/.h CPlanRT_HDoc The document: managing the computation, launching external programs
PlanRT_HView.cpp/.h CPlanRT_HView The view: menu handlers, drawing (background), configuration
TmcRTHRectNode.cpp/.h CTmcRTHRectNode The main computation core: the grid, the computation step, scattering, excitation, the S-matrix
TmcRTHNodeDiel.cpp/.h CTmcRTHNodeDiel The topology-block handler: dielectrics, metal, absorbers, inputs; input excitation
TmcRTH_DialogBlock.cpp/.h CTmcRTH_DialogBlock The block-information dialog
TmcRTH_DialogFormatOutFile.cpp/.h CTmcRTH_DialogFormatOutFile The output-data format dialog
TmcDialogStatistics.cpp/.h CTmcDialogStatistics The statistics dialog
TmcSoundEffProp.cpp/.h CTmcSoundEffProp The sound-effect properties (PropertySheet)
TmcSoundMel1.cpp/.h CTmcSoundMel1 The melody page
Pl_iofor.cpp/.h Global functions: output formats, command-line flags, auto/demo/batch modes
PL_GLFUN.CPP Global functions: PutTrace, PutStatistics, sound, thread entry points
StdAfx.cpp/.h The MFC precompiled header
resource.h, PlanRT_H.rc Resources

Cross-project files (compiled as part of the project, confirmed in the .vcxproj):

File Purpose
../../viewers/Tmcrtout/TmcSMatrix.cpp Reconstructing the S-matrix from a time signal
../../viewers/Tmcrtout/TmcTtoS.cpp The "time → S-matrix" wrapper

Dependencies (AdditionalDependencies): sfile95.lib, prepr.lib, exprint.lib, TMCIndan.lib, TMCLibError.lib.

Preprocessor definitions: WIN32;_WINDOWS;DEBUG__1 (plus _DEBUG/NDEBUG by configuration). The H project has no additional X-mode macros.

Shared headers from src/Include/ (listed in the .vcxproj as ClInclude, but physically located in the common directory and documented separately):

The ClInclude entry Where it is Purpose
TmcRTH_BolckList.h src/Include/TmcRTH_BolckList.h The topology block-list description — the shared header of the TMCIndan library (the CTmcRTH_BlockList class). There is no local copy in the project directory; the documentation is docs/api/libs/tmcindan.md
Typerth.h src/Include/Typerth.h Common types, constants and global functions (see §3)

Files outside the build (legacy). In the directory src/kernels/PlanarRT_H/ they are physically present but NOT included in PlanRT_H.vcxproj (neither ClCompile nor ClInclude):

File Class Status
TmcErrorMessage.cpp/.h CTmcErrorMessage An "About" / error-message dialog. Not part of the build, not #included in the kernel source code; mentioned only in the ClassWizard file PlanRT_H.clw. Treat as unused code.

3. Key types and constants (the header src/Include/Typerth.h)

3.1. Computation precision

//#define _PREC_DOUBLE          // off
#define _PREC_FLOAT             // on: float precision

#ifdef _PREC_FLOAT
#define _real float             // the base precision type
#endif

#define _ELEM_VAL_RTH_REAL      // on: the field element is real
//#define _ELEM_VAL_RTH_INT     // off: the integer variant (with the factor 1024*1024)

#ifdef _ELEM_VAL_RTH_REAL
#define _ELEM_VAL_RTH _real     // the field element type = float
#define _ELEM_VAL_RTH_MULT 1
#endif

Also in Typerth.h the build variant _VERSION_PROF___ is selected (_VERSION_DEMO___ and _VERSION_EDUC___ are commented out).

3.2. Physical constants

Constant Value Meaning
C0___ 299792458 The speed of light (m/s)
MU0___ 12.566370614e-7 The magnetic constant (H/m)
EPS0___ 8.854187817e-12 The electric constant (F/m)
PI___ 3.141592653589 The number π
ELECTRON_Q___ 1.602176565e-19 The electron charge (C) — used only by the X kernel
ELECTRON_M___ 9.10938356e-31 The electron mass (kg) — used only by the X kernel

ELECTRON_Q___ and ELECTRON_M___ are constants, not mode switches. For more on their role in the X-mode and on the X-project macros, see planar_rt_x.md, §2.

3.3. Node types (nType)

The values of the nType field of the node and block structure (they coincide with the nType values of the CTmcRTH_Input class of the TMCIndan library):

Value Meaning
0 Dielectric, ε < 0
1 Dielectric, ε > 0
-1 Metal
-2 Absorber
-3 X input on the left (direction >)
-4 X input on the right (direction <)
-5 Y input on the top (direction V)
-6 Y input on the bottom (direction ^)

3.4. Global functions of Typerth.h (the implementation — PL_GLFUN.CPP)

Function Purpose
void PutTrace(CString) / void PutTrace(char*) Output of a trace string to panel 0 of the main-window status bar
void PutStatistics(CString) / void PutStatistics(char*) Output of statistics to the status bar
void PutSinchronizFlag(BOOL bTopologyFlag, BOOL bFieldFlag1, BOOL bSinchFlag1) Status-bar indication of the output composition: "Output: Signal [+ Topology] [+ Field] [+ Sinchronization]"
void PutModel(void) / CString GetModel(void) The model/version string
void ReadSystemType(void) Reading the system type
void BeepStepEnd(int i) / void BeepAllEnd(void) Sound notification of step / full-computation completion
void s_alarm(int) / void s_play(int far*) / void s_tone(int freq, int time) Low-level sound playback (win16 code remnants: far)
Set/GetMelody1Interval, Set/GetMelody1, Set/GetMelody2Interval, Set/GetMelody2 Configuring the two notification melodies
SetAutoStartRunOn/Off(), SwitchAutoStartRunFlag(), BOOL IsAutoStartRun() Auto-start of the computation on document open
void SetDeltaT(char*) / void SetDeltaT(double) / double GetDeltaT() / BOOL IsDeltaTDefine() / void SwitchDeltaT() Managing the time step Δt (including from the command line)
BOOL IsPointInTr(x1,y1, x2,y2, x3,y3, x0,y0) A geometric predicate: whether the point (x0,y0) is inside the triangle
UINT ReadDataGlobal(LPVOID) The data-reading thread entry point; pParam — a pointer to CPlanRT_HDoc; calls pDoc->ReadData()
UINT RunStepGlobal(LPVOID) The single-step thread entry point; calls pDoc->RunStep()
UINT RunAllGlobal(LPVOID) The full-computation thread entry point; calls pDoc->RunAll()
UINT RunStepGlobalOneTacts(LPVOID) The single-tact step thread entry point

3.5. Global functions of Pl_iofor.h (the implementation — Pl_iofor.cpp)

Text-output formats (set by default by the constants FORMAT_OUT_FILE_*):

Constant Default value Field
FORMAT_OUT_FILE_NTFORMAT "%9d" The tact number nT
FORMAT_OUT_FILE_DTCurrentFORMAT "%15.7g" The current time
FORMAT_OUT_FILE_NBFORMAT "%4d" The block number
FORMAT_OUT_FILE_DINPFORMAT "%15.7g" The input signal
FORMAT_OUT_FILE_DOUTFORMAT "%15.7g" The output signal
FORMAT_OUT_FILE_DFLDOUTFORMAT "" The field (empty — binary output)
Function Purpose
SetnTFormat/GetnTFormat, SetdTcurrentFormat/GetdTcurrentFormat, SetnBFormat/GetnBFormat, SetdInpFormat/GetdInpFormat, SetdOutFormat/GetdOutFormat, SetdFieldOutFormat/GetdFieldOutFormat Setting/reading the printf formats of the output files
void SetDefaultOutputFormat(void) Reset of all formats to the default values
SetAutoRunOn/Off(), SwitchAutoRunFlag(), BOOL IsAutoRun() The auto mode
SetDemoRunOn/Off(), BOOL IsDemoRun() The demo mode
SetBatchRunOn/Off(), SwitchBatchRunFlag(), BOOL IsBatchRun() The batch mode
void Set_CommandLine_Flags(char *lpszCmdLine) Parsing the command-line flags
CMainFrame *GetMainFramePointer__() / SetMainFramePointer__(CMainFrame*) Access to the main window from global code
void SetProcessInformation(PROCESS_INFORMATION) / PROCESS_INFORMATION GetProcessInformation() Data of the launched external process (viewer)
void SetPointerClassView(CPlanRT_HView*) Registering the pointer to the view
void RunOnViewField1(void) Calling the "View Field 1" command from outside

4. Node data structures (TmcRTHNodeDiel.h)

4.1. sTmcRTHNodeDielOne — a node (H-polarization, 2 tacts)

struct STMCRTH_NODEDIELONE
{
    _ELEM_VAL_RTH rU;       // the incident voltage on the dielectric (tact 0)
    _ELEM_VAL_RTH rU_Cur;   // the current voltage
    _ELEM_VAL_RTH rU_Cur1;  // the "current+1" tact voltage
    _ELEM_VAL_RTH rUo;      // the scattered voltage (for inputs)
    _real rY;               // the node conductance
    int   nNodeGlobal;      // the node number in the global topology
    int   nType;            // the node type (see §3.3)
};
typedef struct STMCRTH_NODEDIELONE sTmcRTHNodeDielOne;

In the H variant — 4 voltage components (rU, rU_Cur, rU_Cur1, rUo). In the X variant — 8 (rU..rU3, rU_Cur..rU_Cur3), and the field rUo is absent (see planar_rt_x.md, §3.1).

4.2. sTmcRTH_DielNodeList — a singly linked node list

struct STMCRTH_DIELNODELIST
{
    STMCRTH_DIELNODELIST * pcDielNodeNextList;  // the next list element
    sTmcRTHNodeDielOne   * pcNodeDielOne;       // the node
};
typedef struct STMCRTH_DIELNODELIST sTmcRTH_DielNodeList;

5. The CTmcRTHRectNode class — the computation core

Purpose: managing the computation grid, performing the time-domain computation steps, scattering, input excitation, writing the output files and computing the S-matrix. Header: TmcRTHRectNode.h · Base class: CWnd Depends on: Typerth.h, TmcRTHNodeDiel.h, TmcLibError.h, TmcRTH_Indan.h, TmcRTH_IndanParam.h

5.1. Fields (private)

Field Type Purpose
cIndan CTmcRTH_Indan The input-data manager (.tpl) — the TMCIndan library
cParam CTmcRTH_IndanParam The computation parameters (the PARAM section)
cError CTmcLibError The error accumulator
pcNodeDiel CTmcRTHNodeDiel* The array of block handlers (one per topology block)
nDiel int The number of blocks
nTCurrent int The current time-tact number
nTMax int The maximum tact (the end of the computation)
dT double The time step Δt
dTCurrent double The current physical time
nX / nY int The number of grid nodes along X / Y
dDelta double The spatial step (Δ = Δx = Δy)
dXmin / dXmax / dYmin / dYmax double The boundaries of the computation rectangle
nNumNode int The total number of nodes = nX × nY
prUNode1Temp _ELEM_VAL_RTH* The "raw" pointer of the voltage array (kept for delete[])
prUNode1 _ELEM_VAL_RTH* The working pointer of the voltage array, aligned to 32 bytes
prYNodeTemp _real* The "raw" pointer of the conductance array
prYNode _real* The working pointer of the conductance array, aligned to 32 bytes
bIsReadData volatile BOOL The "data loaded" flag (volatile — communication between threads)
bIsRunStep1Run volatile BOOL The "step running" flag

Array allocation (InitNodeArray): 2*nNumNode + 32 elements are requested (2 values per node plus a reserve), after which the working pointer is shifted so that the address is a multiple of 32 — alignment for efficient access. In the X variant — 6*nNumNode + 32 (6 values per node).

5.2. Public methods

Method Purpose
CTmcRTHRectNode() / virtual ~CTmcRTHRectNode() Constructor / destructor
void ReadData(CString csFileName, int nStep1) Reading the .tpl file csFileName, setting the step number nStep1, initializing the computation
void ReadData(void) Re-reading the current file
void RunStep(void) Performing a computation step (up to nTMax)
void Stop(void) Stopping the computation (resetting bIsReadData)
BOOL IsReadData(void) TRUE if the data is loaded
BOOL IsRunStep(void) TRUE if a step is running
BOOL IsError(void) TRUE on an accumulated error (cError.IsError())
CString GetErrorMessage(void) The error text
int GetNStepMax(CString csFileName) The maximum number of steps for the given file
CTmcRTH_IndanOutput* GetOutput(void) Access to the output-data subsystem
CTmcRTH_IndanParam& GetParam(void) Access to the parameters
CTmcRTH_IndanTopology& GetTopology(void) Access to the topology
void ExportToDirectionalPatter(void) Export for the radiation pattern: cIndan.GetOutput()->GetFieldIntegrated().ExportToDirectionalPattern(cParam)
BOOL GetTopologyFlag(void) The topology-output flag
BOOL GetSoundEffect(void) The sound-effects flag
BOOL GetFieldFlag(void) The field-output flag
BOOL GetSinchronizationFieldOutput(void) The synchronous field-output flag
void PutTopol(void) Writing the topology file
void OnOffSoundEffects(void) Toggling the sound effects
void OnOffSinchronizationFieldOutput(void) Toggling the field-output synchronization
void OnOffFieldOutput(void) Toggling the field output

A note on the name: ExportToDirectionalPatter — thus in the code (without a final n); the internal TMCIndan function is called ExportToDirectionalPattern.

5.3. Private methods

Reading and initialization:

Method Purpose
void ReadTopologySection(void) Reading the TOPOLOGY section
void ReadParamSection(void) Reading the PARAM section
void ReadLinkListSection(void) Reading the LINK_LIST section
void ReadOutputSection(void) Reading the OUTPUT section
void SetStepNumber(int nStep) Setting the step number
void InitKernel(void) Initializing the kernel before the computation
void InitNodeArray(void) / void DeleteNodeArray(void) Allocating/freeing the node arrays (with alignment, see §5.1)
void InitDielArray(void) / void DeleteDielArray(void) Allocating/freeing the block array pcNodeDiel
void SetDielTopology(void) Assigning parameters to the nodes by block
void SetDielInNodeList(void) Including the block nodes in the common list
void DeleteDielList(sTmcRTH_DielNodeList **pcNodeDielList1) Freeing the node list
BOOL IsDataInit(void) Checking data initialization
void DeleteData(void) Full data release

The computation loop:

Method Purpose
void RunKernel(void) The main loop: for(; nTCurrent < nTMax; ...) RunKernel1T(); then PutSmatrix(). Every 100 tacts it outputs the progress and elapsed time via PutTrace/PutStatistics
void RunKernel1T(void) One 1T cycle = 2 sub-steps (see §5.4)
void RunStep1(void) Performing one step (a wrapper with flag setting)
void RunExciteInputs(void) / void RunExciteInputs1(void) Excitation of the inputs (sub-steps 0 and 1)
void RunScatteringNode(void) / void RunScatteringNode1(void) Scattering at the grid nodes (sub-steps 0 and 1)
near void RunScatteringNode1line(_ELEM_VAL_RTH *pr_111, _real *prY_111, int nx_111, int nX_111) Scattering along one grid row (sub-step 0). pr_111 — the row's voltage array, prY_111 — the conductances, nx_111 — the row index, nX_111 — the row length. The near qualifier is a win16 remnant
near void RunScatteringNode1line1(...) The same for sub-step 1 (identical parameters)
void RunBlockNode(void) / void RunBlockNode1(void) Block handling: calling CTmcRTHNodeDiel::RunBlockNode/RunBlockNode1 for each block (sub-steps 0 and 1)

Output:

Method Purpose
void PutField(int ii) Writing the field distribution of sub-step ii (0 or 1)
void PutSmatrix(void) Computing and writing the S-matrix: cIndan.GetOutput()->PutSmatrix()
void PutTopology(void) Writing the topology file (.tt)
void DistributionIntegrated(int ii) Accumulating the integrated field distribution (for the radiation pattern)
void OutputnT(void) Output of the current tact number
void DeleteOutputFile(void) Deleting the output files before a restart
BOOL IsFieldFileRead(void) Checking the reading of the field file
void PutStepEndSound(void) The step-completion sound

5.4. The algorithm of one 1T cycle (H-polarization, 2 sub-steps)

The exact sequence from RunKernel1T() (TmcRTHRectNode.cpp:537):

Sub-step 0:
  RunExciteInputs();          // input excitation
  RunScatteringNode();        // scattering at the nodes
  RunBlockNode();             // block handling
  PutField( 0 );              // field writing
  DistributionIntegrated(0);  // accumulation for the RP
  nTCurrent++;  dTCurrent += dT;

Sub-step 1:
  RunExciteInputs1();
  RunScatteringNode1();
  RunBlockNode1();
  PutField( 1 );
  DistributionIntegrated(1);
  nTCurrent++;  dTCurrent += dT;

The counter nTCurrent is incremented by 1 inside each sub-step (i.e. +2 per 1T cycle). On completion of the main loop, RunKernel calls PutSmatrix().

In the X-mode: 4 sub-steps (+4 per cycle), the DistributionIntegrated calls are commented out (see planar_rt_x.md, §4).


6. The CTmcRTHNodeDiel class — the topology blocks

Purpose: the representation of one topology block (rectangle, circle, polygon; dielectric, metal, magnetic, absorber, input) — the list of its nodes, the conductances, the input excitation. Header: TmcRTHNodeDiel.h · Base class: CWnd

6.1. Fields (private)

Field Type Purpose
cError CTmcLibError The block errors
nBlock int The block number
csBlock CString The block type (the keyword from the .tpl: RECT, CIRCLE, POLYGON, …)
nNumNode int The number of nodes in the block
pcNodeDielOne sTmcRTHNodeDielOne* The array of block nodes
dXCenter / dYCenter double The coordinates of the block center
dYInput double The conductance of the input block
dTmin / dTmax double The input excitation time range
csEpsExpr CString The expression for ε (evaluated by the exprint library)
csW CString The angular velocity (a rotating block)
csVx / csVy CString The linear velocities of the rotation center
nX0 / nY0 int The rotation center (x0, y0)
nTxCurrent / nTyCurrent int The block motion counters along X / Y
nTxMove / nTyMove int The block motion periods along X / Y
nType int The block type (see §3.3)
dY1_InputAdmitance double The input conductance (auxiliary)
dWidthWaveg double The waveguide width (for an input)
dUnormir double The excitation-voltage normalization
csFileNameEps CString The .eps-file name (a block from a file)
dX0 / dY0 double The coordinates (auxiliary)
pbIsStop volatile BOOL* A pointer to the stop flag (from the kernel)

6.2. Public methods

Method Purpose
CTmcLibError& SetBlock(CTmcRTH_BlockList *pcNextBlockList, CTmcRTH_IndanParam &cParam, CTmcRTH_IndanOutput *cOut, _real *prYNode, volatile BOOL *pbStopFlag, CString csCurrentPath) Initializing the block from the .tpl description (CTmcRTH_BlockList — TMCIndan): determines the type, builds the node list, fills the conductances prYNode. csCurrentPath — the path for finding .eps files
CTmcLibError& SetBorderXmin(int nX, int nY) / SetBorderXmax(int nX, int nY) / SetBorderYmax(int nX, int nY) / SetBorderYmin(int nX) Handling the boundaries of the computation area
void SetBlockInDielList(sTmcRTH_DielNodeList **pcNodeDielList, int nNumNode1, CTmcLibError &cError1) Including the block nodes in the kernel's common node list
void ExciteInputs(CTmcLibError &cError1, double dWT, double dT, _ELEM_VAL_RTH *pr1, int nX, CTmcRTH_IndanParam &cParam, double dtCurrent) Excitation of the input nodes, sub-step 0. dWT — the angular frequency × time, dT — the time step, pr1 — the voltage array, dtCurrent — the current time
void ExciteInputs1(...) The same, sub-step 1 (identical signature)
void RunBlockNode(_ELEM_VAL_RTH *prUNode1, _real *prYNode, int nX, int nArraySize) Updating the block-node voltages, sub-step 0
void RunBlockNode1(...) The same, sub-step 1
void AddCurrentPath(CString csCurrentPath) Setting the current path (finding .eps)
CTmcLibError& GetError(void) Access to the errors
void DeleteData(void) Freeing the block data

In the X variant additionally: ExciteInputs2/3, RunBlockNode2/3 (see planar_rt_x.md, §5).

6.3. Private methods (by block type)

Method Purpose
SetRect() / SetCirc() / SetPoly() A dielectric block (rectangle / circle / polygon)
SetRectMetal() / SetCircMetal() / SetPolyMetal() A metal block
SetRectMagnetic() / SetCircMagnetic() / SetPolyMagnetic() A magnetic block
SetRectAbsorber() / SetCircAbsorber() / SetPolyAbsorber() An absorber
SetRectFile() A block with an ε distribution from an .eps file
SetInpXLeft() / SetInpXRight() / SetInpYTop() / SetInpYBot() Input blocks (4 directions)

All Set* methods take CTmcRTH_BlockList *pcNextBlockList (the block description) and CTmcRTH_IndanParam &cParam (the parameters), return CTmcLibError&; SetRect/SetRectFile additionally take CString csCurrentPath, the input methods — CTmcRTH_IndanOutput *cOut.

Auxiliary private methods:

Method Purpose
double SetInputAdmitance(double dFreq, double dDelta) Computing the input conductance
double SetAbsorberAdmitance(double dFreq, double dDelta) Computing the absorber conductance
void CalculateYForInput(double dFreq, double dDelta) The conductance of the input nodes
void SetYForInput(CTmcRTH_IndanParam&) / void SetYLineForDiel(CTmcRTH_IndanParam&, _real *prYNode) Filling the conductance arrays
_real CalcEps(double x, double y, CTmcRTH_IndanParam &cParam) Computing ε at the point (x, y) by the expression csEpsExpr
double dFaza(CTmcRTH_IndanParam&, double dtCurrent) / double dAmplitude(...) The phase and amplitude of the excitation signal at the time dtCurrent
void SetnType(void) Setting the block node types
void SetAbsorberNodeType(CTmcRTH_IndanParam&) / void SetMagneticPolygonType(CTmcRTH_IndanParam&) The absorber / magnetic-polygon node types
void CalculatedXYCenter(CTmcRTH_IndanParam&) Computing the block center
void AddList(sTmcRTHNodeDielOne*, sTmcRTH_DielNodeList**) Adding a node to the list
void OutputUpUo(double dUp, double dUo, CTmcLibError&) Output of the incident/scattered voltages
double atan2__1(double y, double x) A variant of atan2
void SeachEpsFileName(CString) / void AddFileEpsExtention(void) / BOOL IsFullName(void) Finding and normalizing the .eps-file name
void SaveFileRect(...) Saving a rectangle to a file
void DeleteDublicateData(void) / void DeleteStatDielData(void) Cleaning duplicate/static data

6.4. The .eps-file format (ε distribution)

The format constants are defined at the start of TmcRTHNodeDiel.h:

#define TMC_RTH_EPSFILE_EXT_   "eps"
#define TMC_RTH_EPSFILE_ID_    "#TamicRTH_planar_DistributionDielectricPermeability_File_V2.00 2000"
#define TMC_RTH_EPSFILE_TYPE_  "#TopologyPrimitiv "
#define TMC_RTH_EPSFILE_Delta_ "#dDelta "
#define TMC_RTH_EPSFILE_XMIN_  "#Xmin "
#define TMC_RTH_EPSFILE_YMIN_  "#Ymin "
#define TMC_RTH_EPSFILE_NX_    "#nX "
#define TMC_RTH_EPSFILE_NY_    "#nY "
#define TMC_RTH_EPSFILE_NPoint_ "#nPoint "
#define TMC_RTH_EPSFILE_NAccur_ "#nAccuracy "
#define TMC_RTH_EPSFILE_NdFrmt_ "#sNodeFormat "
#define TMC_RTH_EPSFILE_VlFrmt_ "#sValueFormat "

The file starts with the identifier #TamicRTH_planar_..., then the grid parameters (#dDelta, #Xmin, #Ymin, #nX, #nY, the number of points, the accuracy, the node/value formats), then the data.


7. The CPlanRT_HDoc class — the document

Purpose: managing the computation (through cRectNode), launching external programs, storing the settings. Header: PlanRT_HDoc.h · Base class: CDocument

7.1. Fields (private)

Field Type Purpose
cRectNode CTmcRTHRectNode The computation object
nStep int The current step
bIsReadData volatile BOOL The data-loaded flag
csEditorName CString The external text editor (.tpl)
csExternViewer CString The signal viewer (TMCROS)
csExternViewerField CString The field viewer (FieldView)
csExternViewerSmatrix CString The S-matrix viewer (TMCGROUT)
csExternViewerDirectPattern CString The radiation-pattern viewer (TMC_DN)

7.2. Registry settings

The key is set in InitInstance: SetRegistryKey("PlanarRT_H"). The parameter names are constants in PlanRT_HDoc.h:

Constant Parameter name Contents
PLANRT_H_RAZDEL_INI PlanRT_H Config The section name
PLANRT_H_EXTERNEDITORNAME_INI ExternEditorName The path to the editor
PLANRT_H_EXTERNVIEWERNAME_INI ExternViewerName The signal viewer
PLANRT_H_EXTERNFIELDVIEWERNAME_INI ExternFieldViewerName The field viewer
PLANRT_H_EXTERNDIRPATVIEWERNAM_INI ExternDirectPatViewerName The RP viewer
PLANRT_H_EXTERNSMVIEWERNAME_INI ExternSmatrixViewerName The S-matrix viewer
PLANRT_H_BACKGROUNDCOLOR_INI BackGroundColor The background color
PLANRT_H_OUTFORMATNT_INIPLANRT_H_OUTFORMATOUT_INI OutputFormatnT/dT/nB/dInp/dOut The output formats (§3.5)
PLANRT_H_OUTFORMATOUTFILED_INI OutputFormatdOutField The field output format
PLANRT_H_OUTPUTSOUNDFLAG_INI SoundEffectsFlag The sound flag
PLANRT_H_OUTFIELDSINCHRFLAG_INI OutputSinchrFlagdOutField Synchronous field output
PLANRT_H_OUTFIELDFLAG_INI OutputFlagdOutField The field-output flag
PLANRT_H_MNWNDSIZEPLACE_INI MainFrameSizeAndPlace__1 The main-window position

7.3. Methods

Computation management:

Method Purpose
void ReadData(void) Reading the .tpl (delegates to cRectNode)
void RunStep(void) / void RunAll(void) Step / full computation
void Stop(void) Stopping
BOOL IsRun(void) / BOOL IsReadData(void) State flags
void BackStep(void) / void SkipStep(void) / void SetFirstStep(void) Step navigation
int GetnStep(void) The current step
CString GetErrorMessage(void) The error text
CTmcRTHRectNode& GetRectNode(void) Direct access to the kernel
CTmcRTH_IndanOutput* GetOutput(void) / CTmcRTH_IndanParam& GetParam(void) / CTmcRTH_IndanTopology& GetTopology(void) Access to the kernel data
void ExportToDirectionalPatter(void) Export for the RP
void CloseAndExit(void) Closing the document and exit

Output and sound flags (delegate to cRectNode): GetTopologyFlag(), GetSoundEffect(), GetFieldFlag(), GetSinchronizationFieldOutput(), PutTopology(), SetSoundFlag(int), OnOffSoundEffects(), SetOutFieldOutFlag(int), SetOutSinchrFieldOutFlag(int), OnOffSinchronizationFieldOutput(), OnOffFieldOutput().

External programs:

Method Purpose
BOOL RunViewer(void) Launching the signal viewer
BOOL RunViewerField(void) Launching the field viewer
BOOL RunViewerSmatrix(void) Launching the S-matrix viewer
BOOL RunViewerDirectPattern(void) Launching the RP viewer
Set/GetExternEditorName, Set/GetExternViewer, Set/GetExternViewerField, Set/GetExternViewerSmatrix, SetExternViewerDirectionalpattern / GetExternViewerDirectPat Configuring the paths of the external programs
BOOL RunExeFile(CString csNameExe) / BOOL RunExeFile(char*) / BOOL RunExeFile(CString, CString csArgCommLine) / BOOL RunExeFile(char*, char*) Launching an external exe (4 overloads, with and without arguments); internally — CreatProc(char *lpszComLine) (private)

MFC overrides: OnNewDocument(), Serialize(CArchive&), OnCloseDocument(), CanCloseFrame(CFrameWnd*).


8. The CPlanRT_HView class — the view

Purpose: the menu/toolbar handlers, drawing the document-window background. Header: PlanRT_HView.h · Base class: CScrollView

8.1. Fields (private)

Field Type Purpose
cSoundDialog CTmcSoundEffProp The sound-effects dialog
scBackgoundColor COLORREF The background color
bIsReadData volatile BOOL The loaded flag

Private methods: OnDrawBackground(CDC*), ReadData(), WriteFile().

8.2. Menu commands (afx_msg handlers)

The Run menu:

Method Action
OnRunStartstep One computation step
OnRunAll Full computation
OnRunStop Stopping
OnRunRestartstep / OnRunRestartall Restart of the step / full computation
OnRunSkipstep / OnRunBackstep Skip a step / step back

The View menu:

Method Action
OnViewStatistics The statistics window (CTmcDialogStatistics)
OnViewOutput The output signal → the external viewer (TMCROS)
OnViewField / OnViewField1 The field distribution → FieldView; also the public OnViewField11(void) for calling from outside
OnViewTopology The topology
OnViewDirectionalpattern The radiation pattern → TMC_DN

The Config menu:

Method Action
OnConfigEditor Choosing the external editor
OnConfigViewerOutputsignal / OnConfigViewerField / OnConfigViewerSmatrix / OnConfigViewerDirectionalpattern Choosing the external viewers
OnConfigColorBackGround The background color
OnConfigFormatOutputDataFile The output-data format (CTmcRTH_DialogFormatOutFile)
OnConfigSinchronization The field-output synchronization
OnConfigSound / OnConfigSoundMelody The sound effects / the melody
OnConfigSmatrix The S-matrix settings
OnConfigAutorun The auto mode
OnConfigSetup General settings
OnConfigDirectionalpattern The RP settings

Other: OnEditEdit (open the .tpl in the editor), OnFileSaveAs, OnClose, OnDestroy, the public Stop(void).

The OnUpdate* handlers (menu-item availability): OnUpdateConfigSinchronization, OnUpdateViewField, OnUpdateConfigSound, OnUpdateViewTopology, OnUpdateViewField1, OnUpdateRunRun, OnUpdateRunRestartall, OnUpdateRunStartstep, OnUpdateRunRestartstep, OnUpdateRunSkipstep, OnUpdateRunBackstep, OnUpdateRunStop, OnUpdateFileClose, OnUpdateConfigAutorun, OnUpdateViewDirectionalpattern.

MFC overrides: OnDraw(CDC*), PreCreateWindow, DestroyWindow, OnInitialUpdate, OnPreparePrinting, OnBeginPrinting, OnEndPrinting.


9. Dialogs

The build contains five dialog classes (confirmed from PlanRT_H.vcxproj). The class CTmcErrorMessage is not part of the build — see §2, "Files outside the build".

9.1. CTmcRTH_DialogBlock — topology-block information

Purpose: viewing the parameters of one topology block (type, vertex coordinates, the ε expression, the motion velocities) with "previous/next block" navigation. Header: TmcRTH_DialogBlock.h · Base class: CDialog · Resource: IDD_TMC_RTH_TOPBLOCK

Fields (public):

Field Type Purpose
m_pcParam CTmcRTH_IndanParam* The computation parameters (TMCIndan)
m_pcBlockList CTmcRTH_BlockList* The displayed block (TMCIndan)
i int The index of the current block
dX[10] / dY[10] CString Working arrays of vertex coordinates

DDX fields (exchange with the dialog controls):

Field Type Purpose
m_nBlock int The block number
m_nType int The block type (see §3.3)
m_nMemory double The memory occupied by the block
m_nXY int The number of block nodes
m_csString CString The text description of the block
m_csVx / m_csVy CString The linear velocities of the center
m_csW CString The angular rotation velocity
m_csEpsExpr CString The expression for ε
dX0 / dY0 double The coordinates of the center
dX1dX10 / dY1dY10 CString The vertex coordinates (up to 10)
csXminText / csXmaxText / csYminText / csYmaxText CString The boundary labels
dXmin / dXmax / dYmin / dYmax double The block bounds
m_csLongUnit CString The length unit

Methods:

Method Purpose
CTmcRTH_DialogBlock(CWnd* pParent = NULL) The constructor
void PrepareData(void) Filling the dialog fields from m_pcBlockList and m_pcParam
void DoDataExchange(CDataExchange* pDX) DDX/DDV
void OnOK() Closing the dialog
afx_msg void OnCancel1() Cancel
afx_msg void OnTmcblockbuttonnext() / OnTmcblockbuttonprev() Go to the next / previous block

9.2. CTmcRTH_DialogFormatOutFile — the output-data format

Purpose: configuring the printf formats of the output text-file columns (see §3.5). Header: TmcRTH_DialogFormatOutFile.h · Base class: CDialog · Resource: IDD_TMC_CONFIG_OUTFFORMAT

Fields (public): BOOL IsSetDefaultFormat — the reset-to-default flag.

DDX fields:

Field Type Column format
m_csnT CString The tact number nT
m_csdTcurrent CString The current time
m_csnBlock CString The block number
m_csdInp CString The input signal
m_csdOut CString The output signal
m_csdOutField CString The field

Methods:

Method Purpose
CTmcRTH_DialogFormatOutFile(CWnd* pParent = NULL) The constructor
void DoDataExchange(CDataExchange* pDX) DDX/DDV
afx_msg void OnSetDefaultFormat() Reset of all formats to the default values (SetDefaultOutputFormat, see §3.5)

9.3. CTmcDialogStatistics — the computation statistics

Purpose: a summary of the current computation step: the number of nodes/blocks, the memory, the physical parameters, the area sizes in wavelengths, the accuracy. Header: TmcDialogStatistics.h · Base class: CDialog · Resource: IDD_TMC_STATISTICS

Fields (public): CString csAccuracy (the accuracy); int nFlagStep (the step flag). Fields (private): CTmcRTH_BlockList * pcBlockList — the block for the information window.

DDX fields:

Field Type Purpose
m_nStep int The step number
m_nNumNode int The number of grid nodes
m_dMemory double The occupied memory
m_nBlock int The number of blocks
m_csErrorMessage CString The error text
m_cParam CTmcRTH_IndanParam The parameters (TMCIndan)
m_cTopol CTmcRTH_IndanTopology The topology (TMCIndan)
m_cOut CTmcRTH_IndanOutput* The output subsystem (TMCIndan)
dDelta, dFreq, dt, dtT double The grid step, frequency, time step
dTsizeWL, dTsizeWL1, dXsizeWL, dYsizeWL double The area sizes in wavelengths
dXmin/dXmax/dYmin/dYmax, dTmin/dTmax double The area and time boundaries
dWaveLen, dWaveLenDelt double The wavelength and its fraction per grid step
csTolerance CString The tolerance

Methods:

Method Purpose
CTmcDialogStatistics(CWnd* pParent = NULL) The constructor
void PrepareData(void) Computing and filling the statistics fields
void DoDataExchange(CDataExchange* pDX) DDX/DDV
afx_msg void OnViewBlockInformation() Open the block-information window (CTmcRTH_DialogBlock)
afx_msg void OnStepPrev() / OnStepNext() Go to the previous / next step
afx_msg void OnCancel1() Closing
void DeleteData(void) (private) Freeing the data

Known bug: the statistics button does not work in the new versions of H and X (the window is not shown, the application closes, with warnings at compile time). See ISSUES.md.

9.4. CTmcSoundEffProp — the sound-effect properties

Purpose: a tab container (PropertySheet) for the settings of two notification melodies. Header: TmcSoundEffProp.h · Base class: CPropertySheet (DECLARE_DYNAMIC)

Fields (public): CTmcSoundMel1 cMelody1, CTmcSoundMel1 cMelody2 — two melody pages (see §9.5).

Methods:

Method Purpose
CTmcSoundEffProp(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0) A constructor with a caption from a resource
CTmcSoundEffProp(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0) A constructor with a text caption
virtual ~CTmcSoundEffProp() The destructor

9.5. CTmcSoundMel1 — the melody page

Purpose: the page for configuring one melody: the interval and 12 notes. Header: TmcSoundMel1.h · Base class: CPropertyPage (DECLARE_DYNCREATE) · Resource: IDD_TMC_SOUND_MELODY1

Fields (public): CString csMelodyName — the melody name.

DDX fields:

Field Type Purpose
m_SoundInterval int The interval between notes
m_Note1m_Note12 int The 12 notes of the melody

Methods:

Method Purpose
CTmcSoundMel1() / ~CTmcSoundMel1() Constructor / destructor
void DoDataExchange(CDataExchange* pDX) DDX/DDV

10. The input file format (.tpl)

The template sections (parsed by the Read*Section methods through the TMCIndan library; the detailed format description — docs/api/libs/tmcindan.md):

Section Purpose
STEP The number of computation steps (nTMax)
PARAM The parameters: the frequency, Δ, Tmin/Tmax, Xmin/Xmax/Ymin/Ymax, the height, the units
TOPOLOGY The blocks: rectangles, circles, polygons, inputs, absorbers
LINK_LIST The links between the blocks
OUTPUT The output-file configuration

Before parsing, the file goes through preprocessing by the PREPR library (macro substitution, the intermediate file $$vr$$s.prc).


11. The output file formats

Extension Contents Consumer
.t The time signal TMCROS
.ex The field distribution (binary, the header #TMC_GraphicsOutputFieldFile) FieldView
.tt The topology (the name is formed in TMCIndan: csFileNameTopology.Format("%s.tt", ...)) FieldView
.s The S-matrix TMCGROUT
.eps The ε distribution (input and output, the format §6.4) the kernel

The .dop files are documents of the TMC_DN viewer (radiation patterns); the kernel does not write .dop directly — the export of data for the RP is performed by CFieldIntegrated::ExportToDirectionalPattern (TMCIndan, see docs/api/libs/tmcindan.md).

The writing of the output files is implemented in the CTmcRTH_IndanOutput subsystem of the TMCIndan library.