Редактор заданий TPL Designer
Назначение и место в пакете
TPL Designer — графический редактор файлов задания .tpl для счётных ядер пакета:
planarrt_h (H-поляризация) и planarrt_x (E-поляризация с подмагниченной плазмой).
Пользователь рисует геометрию мышью, заполняет поля портов, сигналов и вывода, а
программа пишет задание, которое ядро гарантированно примет и посчитает так, как
нарисовано. Язык .tpl (текст с препроцессором в духе C) полон ловушек: в файл пишется
добавка eps-1, а не сама eps; INPUT_X — это вход с апертурой вдоль оси Y; перенос строки
в макросе — ровно два обратных слеша; экспоненту вычислитель ядра не понимает. Каждая
такая ловушка закрыта кодом генератора, а то, что кодом закрыть нельзя, ловит проверка
до записи файла.
Место в конвейере пакета (см. обзор теории):
TPL Designer (рисунок, поля) ← этот модуль
│ validate() → emitMono / emitMacro / emitChunks → writeTask (CP1251, CRLF)
▼
<имя>.tpl [+ <имя>_step.h, .sig, .eps, пакетные файлы]
│ препроцессор prepr → разбор TMCIndan
▼
ядро planarrt_h / planarrt_x → .s, .t, .tt, поля, ДН → вьюверы
Обратный путь тоже есть: readTplFile открывает готовое задание — своё или
написанное руками — и возвращает его в модель редактора.
Полный справочник языка задания — руководство пользователя
docs/user-manual/tpl-guide.md (в корне пакета). Препроцессор ядра описан на странице
библиотеки prepr, разбор задания ядром — на странице
библиотеки TMCIndan, форматы файлов — на странице
форматов файлов.
Архитектура подпроекта
Подпроект лежит в src/tpl_designer и состоит из двух слоёв с жёсткой границей:
| Слой | Каталог | Зависит от | Роль |
|---|---|---|---|
| Ядро генератора | src/core (статическая библиотека tpl_core) |
только Qt6::Core (+ OpenCASCADE для STEP) | модель задания, проверка, эмиттер, чтение .tpl, сетка и размещение, импорт 3D, файлы .eps и .sig, оценка памяти, CP1251, перевод, каталог образцов |
| Интерфейс | src/gui |
tpl_core, Qt6::Widgets |
мастер, холст, диалоги, библиотека образцов, запуск ядер |
| Тесты и утилиты | tests, tools |
tpl_core |
модульные тесты ядра, выгрузка образцов, снимки окон |
Граница проведена в src/core/CMakeLists.txt: подключать Qt6::Widgets к ядру нельзя.
Поэтому вся логика генерации проверяется тестами без запуска окон, а интерфейс только
собирает Project и вызывает функции ядра. Связь с ядрами пакета — чисто файловая:
редактор ничего не линкует из счётных библиотек, он пишет текст и запускает ядра
отдельными процессами.
Все функции ядра генератора — чистые: получают модель по ссылке и возвращают значения (текст, список замечаний, оценку). Общих изменяемых данных нет, кроме таблиц перевода и каталога образцов, которые строятся по текущему языку (см. перевод).
Состав ядра
| Файл | Роль |
|---|---|
project.h/.cpp |
модель задания Project и её помощники: единицы, стороны прямоугольника, покрытие точки фигурой, правила портов, свип |
emitter.h/.cpp |
validate, моно-задание, макро-версия, угловой свип, конвейер; запись чисел без экспоненты |
tplreader.h/.cpp |
препроцессор по правилам ядра и чтение .tpl обратно в модель |
taskfiles.h/.cpp |
writeTask — единственный путь записи задания на диск, имена сопутствующих файлов |
expr.h/.cpp |
вычислитель выражений ExprProgram (формулы eps, сигналов, координат) |
placement.h/.cpp |
проверки размещения фигур на сетке, окна съёма, контур ДН, прямоугольник B |
physics.h |
справочные формулы: отсечки, плазменная и циклотронная частоты |
sigfile.h/.cpp |
формы падающей волны, файл .sig, полоса и опора сигнала |
epsfile.h/.cpp |
запись и чтение файла распределения .eps |
ramestimate.h/.cpp |
оценка оперативной памяти ядра |
cp1251.h/.cpp |
кодировка CP1251 и чтение текстовых файлов задания |
lang.h/.cpp |
выбор языка и функция перевода tpl::tr |
mesh3d, meshio, meshslice, convexsplit, meshgen, meshimport, materialmap |
импорт 3D-модели: чтение STL/OBJ, сечение плоскостью, разбиение на выпуклые части, перенос в фигуры |
stepio.h, stepio_occt.cpp, stepio_none.cpp |
чтение STEP через OpenCASCADE; заглушка для сборки без него |
samples/* |
каталог образцов задач: рецепты, таблицы стандартов, паспорта |
Модель задания
Модель описана в project.h и хранит то, что вводит человек, а не то, что пишется в
файл. Пересчёт в правила языка — дело эмиттера.
Project
├─ name, description, kernel (H | X), unit (единица ввода; в файл — всегда мм)
├─ box (счётная область, мм), delta (шаг сетки, мм), timeMax (конец счёта, нс)
├─ freqs (ГГц; одна — моно-задание, больше — макро-версия)
├─ shapes[] Shape: id, name, kind (Rectangle | Circle | Polygon | Polyline),
│ material (Metal | Magnetic | Absorber | Dielectric), eps,
│ edges[4] (стороны прямоугольника), epsProfile, plasma, скорость
├─ ports[] Port: id, side, from..to (апертура), plane, active, mode (H10 | Plane),
│ signal (формула или файл .sig), eps / epsAuto (среда в сечении входа)
├─ output OutputSettings: файл сигналов, топология, поля, SMATRIX, ДН, /Time
├─ variants[] варианты геометрии (выключенные фигуры), exciters[] очередь возбуждений
├─ sweep AngleSweep: поворот объекта по шагам
└─ chunking Chunking: разложение сетки частот по нескольким заданиям
Главные соглашения модели:
- Сама eps, а не добавка.
Shape::eps,Port::eps, формулаEpsProfile::formulaхранят eps; эмиттер пишетeps-1ровно в одном месте для каждого случая (fillExpression,epsProfileLines,portLine). - Абсолютные координаты сцены, мм. Разложение на «локальные координаты + анкер
#LINK_LIST» делает эмиттер. Исключение — круг: в блокеCIRCLE_STATцентра нет, центром служит анкер. - Материал — контур, выражение — область.
Metal,Magnetic,Absorberядро ставит только на периметр; диэлектрик, профиль eps и плазма — заливка (Shape::isContour). - Плазма — одна фигура с несколькими величинами. N (м^-3), B (Тл), Y (сеточные
потери) и sigma (См/м) в языке — разные блоки
*_STAT_N/_B/_Y/_Sс одной геометрией; в модели это поля однойPlasma. Каждая величина может быть числом, формулой от координат или файлом (FILE_N/_B/_Y). См. модель плазмы и единицы. - Порт задаёт направление, а не границу.
PortSideговорит, куда пойдёт падающая волна; плоскость входа может стоять внутри области (Port::plane). Ядро выводит направление по половине области, где лежит плоскость (directionForPlane). - Среда входа по умолчанию — среда под входом.
Port::epsAuto(по умолчанию включено): eps входа берётся из диэлектрической фигуры, накрывающей середину апертуры (portMediumEps); см. параметр W порта. - Номера блоков общие у фигур и портов; произвольны, но уникальны и не меньше 1
(
Project::nextFreeId).
Число шагов задания (Project::stepCount): варианты x возбуждения x частоты; при угловом
свипе — опорный шаг плюс по шагу на угол. Число файлов конвейера — Project::chunkCount.
Конвейер «проект → проверка → эмиттер → файлы»
Project
│ validate(p) → Diagnostics { errors, warnings }
│ errors не пусто → запись запрещена, список показывается человеку
▼
emitChunks(p) → QVector<TaskChunk> (без конвейера — один элемент)
│ для каждой части: needsMacro ? emitMacro : emitMono
▼
writeTask(...) → <имя>.tpl, <имя>_step.h (CP1251, CRLF),
файлы .sig, .eps, пакетные <имя>_run.bat/.sh
Правило проверки одно: ошибка — только то, что ядро отвергнет или молча посчитает не то, что нарисовано; всё остальное — предупреждение, которое записи не мешает. Задание, которое ядро считает, генератор обязан сохранить.
Записывает задание на диск только writeTask — им пользуются мастер, библиотека
образцов, «Мои образцы» и служебные утилиты. Своя запись «рядом» в одном из мест уже
приводила к заданию без файла .sig, поэтому другого пути нет. Подробнее — в разделе
запись файлов.
Проверка задания
validate(const Project&) проверяет задание в таком порядке (тексты замечаний — на
языке интерфейса):
- Задание в целом. Имя задано и без точки; есть частоты;
DELTA > 0,TIME > 0, область не пуста. Больше 99 частот в одном задании без конвейера — ошибка (kMaxFreqs: потолок.s, тонов ДН и постобработки, см. многочастотный расчёт); больше 20 входов — предупреждение. Для многочастотной ДН — окно, не кратное 1/df между тонами (утечка тонов), и оценка памяти не меньше 2 ГБ (см. оценка памяти). - Имена файлов сигналов, S-матрицы и ДН: заданы, без точки (расширение ядро дописывает само).
- Номера блоков: не меньше 1 и без повторов.
- Фигуры. Линия — не меньше двух точек и не заливка; контур — не меньше трёх
точек; заливной полигон — больше трёх вершин, невыпуклый — предупреждение (ядро
выпуклость не проверяет, поле выйдет неверным); у круга
rMax > rMin, у сектора конечный угол больше начального; у прямоугольника положительные размеры и хоть одна сторона; фигура целиком вне области — предупреждение. Плазма: только ядро X; не у движущегося блока; имена файлов величин без точки и латиницей; N <= 0 — предупреждение (плазменная ветка не включится); B без перекрывающей N — предупреждение (подмагничивание пропадёт). Профиль eps: формула разбирается и даёт число в контрольных точках (epsSamplePoints), имя файла без точки и латиницей, не у движущейся фигуры, не вместе с плазмой. - Порты. Апертура не нулевая; eps входа строго больше нуля — иначе ядро
отвергнет файл (
eps = W + 1 <= 0); плоскость входа внутри области и в той же половине, что и направление (иначе ядро молча развернёт волну); апертура ближе2*DELTAк краю — предупреждение (ядро поджмёт её); окно пассивного порта не заходит в счёт. Порт с сигналом из файла проверяетcheckFileSignal(см. падающая волна из файла). - Широкая полоса. Два порта не пишут волну в один файл; частота согласования
(
FREQ) рядом с полосой сигнала; плазма при широкополосном сигнале — предупреждение (X-ядро считает плазменную добавку один раз, изFREQ). - Конвейер, варианты, возбуждения. Частот в одной части от 1 до 99; конвейер
несовместим с угловым свипом; у вариантов есть уникальные метки файлов без точки,
выключенные фигуры существуют; два профиля не пишут один
.eps; порты очереди возбуждений существуют и не повторяются; окно S-матрицы не за концом счёта. - Угловой свип (см. ниже).
- Размещение на сетке —
checkPlacement(см. размещение). - Описание без символов вне CP1251.
- Предупреждения в конце: ни одного активного порта; несколько активных портов
при снятии
.s(это уже не матрица рассеяния); неполная очередь возбуждений (столбцы S останутся пустыми); больше 60 шагов (оценка времени); поля на каждом шаге свипа.
Сознательно не проверяются одномодовость одночастотного порта, полоса непрозрачности плазмы, отрицательная eps вне входа, «форма импульса»: это не ошибки задания, а его физика, и рабочие задания такие проверки объявляли бы ошибочными. Отсечки H10/H20 проверяются только у широкополосного порта с сигналом из файла: там матрицу восстанавливает постобработка в предположении одной моды, и выше отсечки H20 число вышло бы молча неверным.
Эмиттер: моно-задание
emitMono(p) пишет один файл, где каждый шаг #STEP выписан явно. Шаги идут по
сочетаниям «вариант x возбуждение» (combos), внутри — по частотам. Шаг строит
stepLines:
#STEP
#PARM
ANGLE_UNIT radian; FREQ_UNIT GHz; LONG_UNIT mm; TIME_UNIT ns;
DELTA …; TIME 0.; …; X_MIN …; X_MAX …; Y_MIN …; Y_MAX …; FREQ …;
#END_PARM
#TOPOLOGY
BLOCK n; ! имя — пояснение
<тело блока>
END_B
…
#END_TOPOLOGY
#LINK_LIST
T n; X0; Y0;
…
#END_LINK
#OUTPUT
FILE <сигналы>; [TOPOLOGY;] [FIELDS;]
[SMATRIX <файл>; <FREQ>; Tmin; Tmax;] [FIELD_DISTRIBUTION_M <файл>; <FREQ>; Tmin; Tmax;]
#END_OUTPUT
#END_STEP
Как закрываются правила языка:
| Правило языка / ловушка | Где закрыто |
|---|---|
Заголовок всегда #TMC_RT_H (тега #TMC_RT_X нет); #EOF обязателен |
header, конец emitMono/emitMacro |
Единицы в #PARM — одни и те же: радианы, ГГц, мм, нс |
stepLines |
Блоки #TOPOLOGY и строки T #LINK_LIST не расходятся |
оба строятся из одного списка buildBlocks |
В файл идёт добавка eps-1; у профиля — (формула)-1 в скобках (подстановка текстовая) |
fillExpression, epsProfileLines |
| Прямоугольник и полигон — абсолютные координаты с анкером (0;0); круг — центр в анкере | shapeAnchor |
| Разные стороны прямоугольника одним блоком не выразить | edgeLines: по ломаной на сторону, свободные номера блоков |
POLYGON_STAT меньше чем с тремя строками L ядро не грузит |
padToThreePoints: середина отрезка |
| Замкнутый контур материала закрывается повтором первой точки; заливка — обход по часовой стрелке | polygonPoints |
Плазма — до четырёх блоков _N/_B/_Y/_S одной геометрии; B — прямоугольником шире плазмы на kBMarginCells шага (или ровно по плазме при bExact) |
buildBlocks, plasmaBRect |
Профиль eps: [имя] пишется только на первом шаге, где фигура появляется; файл .eps — только у прямоугольника |
epsProfileShapes, createEps |
| Вход: 8 параметров, Faza обязательна при Amp, восьмой — добавка eps-1 среды входа (вакуум не пишется) | portLine, portEps |
| Пассивный вход: окно [2TIME; 3TIME] и Amp = 0 | portWindow, portLine |
| Плоскость входа — анкер порта | portAnchor |
Сигнал из файла — [имя] на месте Amp, без пробела перед скобкой |
portLine |
Подпись SMATRIX — частота шага; окно обязательно, кроме многочастотного шага |
stepLines, stepIsWideband |
ДН — только FIELD_DISTRIBUTION_M |
stepLines |
| Экспоненты в числах нет никогда | formatNumber, formatCompact, plainDecimal, plainLiterals |
| Имя ядра в шапке без расширения — файл одинаков на всех системах | header |
Числа. formatCompact пишет до 10 значащих цифр (шести не хватало для круговорота
«открыл — сохранил»: координаты ползли) и никогда экспонентой: 3.1e17 уходит как
310000000000000000. formatNumber добавляет .0 целым числам, formatFreq пишет
частоту с одним знаком, если она кратна 0.1 ГГц, иначе со всеми нужными знаками.
plainLiterals переписывает числа с экспонентой внутри формул пользователя.
Имена выходных файлов шага. Файл сигналов получает добавки варианта (_<tag>),
возбуждения (_p<номер>) и, при нескольких частотах, частоты (_f3p9): имя у шага
одно, а шагов много, и без метки каждый следующий шаг переписывал бы .t предыдущего.
Файл S-матрицы общий для всех возбуждений одного варианта (шаги дописывают в него свои
столбцы) и разный у разных вариантов. Шапка задания перечисляет все файлы .s, которые
надо удалить перед прогоном: ядро их дописывает, а не перезаписывает.
Профиль eps считается один раз. Шаг, на котором фигура с профилем появляется
впервые, пишет [имя] и создаёт .eps; остальные шаги пишут только формулу (файл
частотно-независим, частотный коэффициент ядро применяет само).
Эмиттер: макро-версия
При нескольких частотах (или угловом свипе) needsMacro возвращает true, и
emitMacro пишет два файла: <имя>.tpl и <имя>_step.h. Шаг описан один раз —
макросом с параметрами, а число шагов равно числу строк вызова; рассинхронизировать
шаги невозможно.
! <имя>_step.h
#define wgstep Freq__; Tfile__; Sfile__; @\\
#STEP\\
#PARM\\
…\\
FREQ Freq__;\\
…\\
BLOCK 1;\\ ! волновод: нижняя стенка
…\\
#END_STEP
! <имя>.tpl
#TMC_RT_H
! …шапка…
#include <имя>_step.h
wgstep 3.0; wg_f3; wg;
wgstep 3.2; wg_f3p2; wg;
…
#EOF
Параметры макроса: Freq__ (частота), Tfile__ (файл сигналов), Sfile__ (при
снятии S-матрицы), Dfile__ (при ДН). На каждое сочетание «вариант x возбуждение» —
свой макрос (<имя>step1, <имя>step2, …; имя не длиннее 32 символов), потому что
топология у них разная.
Правила препроцессора, которые закрывает macroText (см.
перенос строки и #define):
- перенос — ровно два обратных слеша
\\в конце каждой строки, кроме последней; у последней переноса нет — это признак конца макроса; - подпись блока (
! имя) ставится за переносом: препроцессор вырезает!первым, и комментарий перед\\унёс бы сам перенос; #includeстоит выше вызовов; включаемый файл лежит рядом с.tpl(ядро ищет его только в папке задания).
То, что должно случиться ровно один раз (поля только на первом шаге, сохранение профиля eps), в теле макроса выразить нельзя — «первого шага» внутри макроса нет. Такой шаг пишется явно перед вызовами своего сочетания, а соответствующая строка вызова пропускается.
Конвейер заданий по частотам
В один файл .s пакет укладывает не больше 99 частот. Сетку гуще делит
emitChunks: при Project::chunking задание раскладывается на части по
freqsPerTask частот — <имя>_001, <имя>_002, … (ширина номера по числу частей,
чтобы файлы шли по порядку). У каждой части свои имена файлов сигналов, .s и ДН (с
той же добавкой _001): .s дописывается, и общие точки разных частей перемешались
бы, а при запуске пачкой файл испортился бы от одновременной записи. Файл падающей
волны .sig, наоборот, общий — имя фиксируется по исходному заданию. В описание каждой
части дописывается, какие частоты она считает. Без конвейера emitChunks возвращает
одно задание — вызывающему не нужно ветвление.
Широкополосный сигнал из файла конвейер не заменяет: в плазме X-ядро считает
плазменную добавку один раз, из FREQ, и для широкой полосы в плазме верный путь —
именно пачка заданий (см. многочастотный расчёт).
Угловой свип
Повернуть источник язык не позволяет: входов два вида, и плоская волна идёт только
вдоль осей. Поэтому для рассеяния под разными углами поворачивается объект
(AngleSweep): выбранные фигуры поворачиваются от шага к шагу вокруг оси
sweepPivot (по умолчанию — центр габарита объекта, ось ездит вместе с ним).
- Координаты повёрнутых фигур пишутся выражениями от угла:
x' = cx + dx*cos(a) - dy*sin(a),y' = cy + dx*sin(a) + dy*cos(a), гдеa = Ang__*0.0174532925199433(rotX,rotY). Ядро считаетcos/sinв координатахLи анкерахT, поэтому шаг описан один раз макросом<имя>rot Ang__; Tfile__; …. - Прямоугольник при повороте становится полигоном из четырёх углов; у круга поворачиваются центр (анкер) и раскрыв сектора.
- Опорный шаг (
referenceStep) — та же сцена без объекта, в файлы с добавкой_ref. - У каждого угла свой файл
.s(<имя>_a30.s,sweepSFile), подписанный частотойFREQ: ядро не даёт подписывать точку одночастотногоSMATRIXничем, кроме частоты. Метка углаa30,a12p5,am15(sweepFileTag) — без точки. - Возбуждается единственный порт очереди или порты с флагом «активный»
(
sweepExciter).
Шапка задания несёт служебную строку
! @TPLD-SWEEP blocks=…; pivot=x,y; angles=…; ref=0|1 (sweepHeader). Для ядра это
комментарий, а чтение по ней разворачивает фигуры обратно и собирает свип.
Проверка запрещает (ошибки): свип без фигур или углов; несколько частот; вместе с
вариантами, очередью из нескольких портов или конвейером; повтор угла (два шага в один
файл); профиль eps и плазму формулой у поворачиваемой фигуры (координаты формулы
пришлось бы поворачивать внутри чужого выражения); B и Y — только прямоугольником по
осям; движущиеся блоки. Выход повёрнутой фигуры за область — предупреждение.
emitMono для свипа пишет все шаги явно (emitSweepMono), emitMacro — макросом
(emitSweepMacro).
Чтение .tpl
readTplFile(path) / readTplText(text, baseDir) возвращают ReadResult: модель,
предупреждения, ошибки, признак макро-версии, имена включённых файлов и текст после
препроцессора (тот, что ядро кладёт в <имя>.tpl~$Prepr$~). Кодировка файла
определяется автоматически (CP1251 или UTF-8).
Чтение «мягкое»: что модель не выражает, не теряется молча, а попадает в
предупреждения с номером строки исходного файла. Ошибка — только когда разбирать
нечего (нет #TMC_RT_H, нет ни одного #STEP).
Препроцессор (preprocess) повторяет библиотеку prepr по коду,
а не по справочнику:
!вырезается первым до конца строки (поэтому!перед\\убивает перенос);\\и всё после него до конца строки выбрасывается, строка склеивается со следующей;#includeвставляет файл из папки задания (имя ищется без учёта регистра: задания пишут на Windows, а читать их могут на Linux и macOS); после каждой вставки склейка повторяется; не больше 64 вставок;#define ИМЯ [пар1; пар2;] @ телораскрываются от последнего к первому, каждое — только ниже своего места; подстановка по целым идентификаторам[A-Za-z0-9_]; внешние скобки фактического параметра заменяются пробелами; длина имени и число параметров не ограничиваются. Строка#defineзаменяется пустой — номера строк в предупреждениях остаются настоящими.
Разбор (parseSteps) режет плоский текст на шаги и секции #PARM, #TOPOLOGY,
#LINK_LIST, #OUTPUT. Отсутствующие поля #PARM наследуются от предыдущего шага,
как в ядре; величины сразу переводятся в мм, нс и ГГц по LONG_UNIT, TIME_UNIT,
FREQ_UNIT. Ключевые слова сравниваются с разделителем (TIME_UNIT не совпадает с
TIME), примитивы — по таблице от длинного к короткому (RECT_STAT_N раньше
RECT_STAT).
Сборка модели (buildStep, затем readTplText):
- локальные координаты + анкер → координаты сцены; добавка eps-1 → eps; формула
(X)-1→X; формулы из файла в см или м пересчитываются в мм; - лишняя вершина отрезка (добивка до трёх точек повтором или серединой) убирается
молча (
dropPaddingPoints); контур с повтором первой точки становится замкнутым полигоном, без повтора — ломаной; - плазменные блоки одной области склеиваются в одну фигуру (
mergePlasmaInto); блок B, шире плазмы не больше чем наkBMarginCellsшага, тоже считается «той же фигурой», а совпадающий с плазмой ставитPlasma::bExact; - анкер профиля eps и плазмы, не совпадающий с центром фигуры, сохраняется
(
customOrigin): иначе при сохранении среда сдвинулась бы; - вход: мода по первому параметру, направление — по половине области, плоскость —
из анкера; сигнал узнаётся по виду Amp (гаусс — по выражению, файл — по
[имя], тогда форма восстанавливается из служебной строки@TPLD-SIGфайла.sig, а чужой файл берётся таблицей); пассивный вход — окно позже конца счёта или нулевая Amp; восьмой параметр — добавка eps среды входа; - одинаковые фигуры и порты разных шагов склеиваются по ключам (
shapeKey,portKey); различающиеся шаги восстанавливаются как частоты, очередь возбуждений и варианты геометрии; повёрнутый объект свипа разворачивается по служебной строке; - имена фигур берутся из комментариев
BLOCK n; ! имя — пояснениеисходного текста (и включаемых файлов), имена вариантов — из комментариев! вариант: …, описание — из шапки «Задание сгенерировано TPL Designer». Оба языка понимаются при любом текущем; - в конце — сверка: сколько шагов даст обратная запись модели. Не совпало — значит, часть различий между шагами модель не выражает, и об этом есть предупреждение.
Выражения
Формулы встречаются в задании повсюду: профиль eps и величины плазмы от координат,
форма сигнала a(t), координаты при чтении чужих файлов. Их считает собственный
вычислитель ExprProgram (expr.h/.cpp) — тот же язык, что у вычислителя ядра:
- разбор рекурсивным спуском в дерево (
compile— один раз,eval— сколько угодно); разбирать формулу в цикле по узлам нельзя, для этого и есть скомпилированная программа; - пробелы внутри выражения удаляются целиком (
6 . 3— законная запись числа); - операции
+ - * /, степень^(правоассоциативная), функцииabs exp log log10 sqrt sin cos tan sinh cosh tanh asin acos atanстрочными со скобкой;ANGLE_UNITдействует на тригонометрию; - промежуточные
infиNaNдопустимы (как в C:x/exp(500)даёт законный ноль), отвергается только нечисловой итог; evalEps(x, y)— быстрый путь для формул среды: подставляетx,y,r = sqrt(x^2+y^2)иf = atan2(y, x). ⚠️fв формуле среды — полярный угол, а не частота: так подставляет ядро;scaleCoordinatesпереписываетx,y,rв(x*k)— так формулы из файлов в см или м переводятся в мм.
Пределы: глубина дерева 4000, вложенность скобок 1000.
⚠️ Экспоненциальную запись чисел (1e17) старые сборки вычислителя ядра не понимают:
«1» — число, e17 — неизвестная функция. Эмиттер её не пишет никогда (см.
эмиттер).
Геометрия и сетка
Язык знает три примитива площади: прямоугольник по осям, круг (кольцо, сектор) и
полигон. Кривых нет — дуги и окружности как линии редактор разбивает на ломаные с
шагом порядка DELTA. Всё, что ядро заливает, обязано быть выпуклым: заливку
полигона ядро строит веером от первой вершины, и невыпуклая область молча даёт неверное
поле. Поэтому произвольную область (например, сечение 3D-модели) редактор режет на
выпуклые куски (convexPieces, convexsplit.h):
- область режется вертикальными полосами по абсциссам всех вершин;
- в каждой полосе рёбра, пересекающие её, сортируются снизу вверх и попарно дают трапеции;
- трапеция сливается с куском слева, если их общий край совпадает и выпуклость сохраняется;
- треугольнику добавляется середина самой длинной стороны (
padTriangle): у заливного полигона должно быть больше трёх вершин.
Стенки (металл, магнитная стенка, поглотитель) — это контуры: замкнутый контур
записывается с повтором первой точки, ломаная — как есть, но не меньше чем тремя
точками. Узлы сетки ядро ставит с шагом DELTA от границ области; о том, как
располагать блоки относительно узлов, — правила сетки.
Размещение на сетке
checkPlacement (placement.h/.cpp) вызывается из validate и проверяет то, что
ядро посчитает не так, как нарисовано:
- фигура выходит за область дальше чем на полшага — предупреждение (ядро отбросит выступающую часть);
- магнитная стенка или поглотитель кругом либо полигоном не крупнее
2*DELTA— предупреждение (стенка тоньше ячейки); - плазма (ядро X): граница блока B режет плазму; краевой резонанс в полосе
расчёта (±2 %) — верхнегибридная частота краевого слоя
sqrt(fp^2/2 + fce^2)при широком блоке B иsqrt(fp^2/2 + fce^2/4)при B ровно по плазме (на границе блока ядро ополовинивает значения); плазма и eps > 1 в одних узлах; B в диэлектрике без N; подмагниченная плазма у магнитной стенки; плазма на поглотителе; добавка eps в пределах 0.004 от 4 (ядро её сдвигает). См. плазменная частота, циклотронная частота, отсечки и резонансы; - окна снятия S-матрицы и ДН раньше установления — предупреждение; время установления оценивается снизу проходом волны по диагонали области:
- окно ДН, которое ядро не закроет до конца счёта, — ошибка: ядро дотягивает окно до целого числа периодов, и при файлов ДН не будет вовсе;
- поглотитель, плазма и вход относительно контура интегрирования ДН (10 шагов от края области), см. контур в ближней зоне.
Там же два помощника эмиттера и рецептов:
plasmaBRect— прямоугольник блока B: шире плазмы на два шага с каждой стороны (kBMarginCells), обрезанный по области; сторона не расширяется, если задела бы чужую плазму или формула B на краю перестала бы давать число;patternWindowSafeEnd— конец окна ДН не позжеTIME - 1/f_min, округлённый вниз до 0.01 нс и сдвинутый так, чтобы ядро закрыло окно.
Импорт 3D-моделей
Геометрию можно взять из 3D-модели: сечение тела плоскостью превращается в фигуры
задания (meshio, mesh3d, meshslice, meshimport, materialmap).
файл STL / OBJ / STEP ──► Mesh (тела: треугольники, имя, материал, цвет)
weld: склейка вершин ──► срез плоскостью ──► замкнутые контуры и ломаные
──► упрощение (Дуглас — Пейкер) ──► материал по имени ──► фигуры Project
- Чтение по расширению: STL двоичный узнаётся по размеру
84 + 50*N, в текстовом каждоеsolid <имя>— отдельное тело; OBJ — тело на каждый объектo/gи материалusemtl, многоугольные грани разбиваются веером, цвета берутся из.mtl(Kd). - Склейка вершин (
weld) — по решётке с шагом1e-7диагонали модели (проверяются 27 соседних ячеек); выродившиеся треугольники выбрасываются. - Срез (
meshslice): вершина на плоскости считается «выше»; точка на ребре вычисляется в порядке ключа ребра, поэтому соседние треугольники получают её одинаковой до бита, и отрезки сшиваются в цепочки по общим рёбрам без допусков. Вложенность контуров — по правилу чётности. - Перенос в задание (
buildImportShapes): металл, магнитная стенка и поглотитель становятся контуром (замкнутым или ломаной); диэлектрик — выпуклыми кусками (см. геометрия); незамкнутый контур диэлектрика не вставляется — об этом пишется пояснение. Имена очищаются от символов вне CP1251. - Материал по имени (
materialmap) угадывается регулярными выражениями по имени тела или материала; побеждает первое совпадение, пользователь может переназначить.
meshgen строит тестовые тела и используется только тестами и утилитой
tools/make_models.
Импорт STEP
STEP читается через OpenCASCADE (stepio_occt.cpp, интерфейс stepio.h):
- сборка обходится средствами XCAF; имена, материалы и цвета наследуются от родительских узлов;
- единица результата принудительно миллиметры (
xstep.cascade.unit); - допуск триангуляции —
1e-3диагонали модели, но не меньше1e-4мм.
Какой файл попадёт в сборку, решает src/core/CMakeLists.txt: при найденном
OpenCASCADE — stepio_occt.cpp, иначе — заглушка stepio_none.cpp, которая честно
отвечает «эта сборка STEP не читает» (STL и OBJ при этом работают). В выпуске пакета
OpenCASCADE обязателен, и заглушка в него не входит.
Файл распределения .eps
Неоднородная среда задаётся формулой в любой фигуре; файл <имя>.eps пишет само ядро
блоком RECT_STAT [имя]выражение (только прямоугольник), а читается он блоком
FILE <имя>; x1; x2; y1; y2; — координаты блока ядро при этом не использует, сетку
берёт из файла, а на место ставит анкер. Редактор умеет и писать такой файл сам
(epsFileBytes, по образцу записи ядра), и читать чужой (epsfile.h):
- текстовая шапка с переводами строк CRLF:
#dDelta,#Xmin,#Ymin— в метрах, далее#nX,#nY,#nPoint,#nAccuracy; - затем записи «
doubleзначение +int32линейный индекс» по строкам сетки,j = iY*nX + iX; - значение —
вес * выражение, вес узла 1 внутри, 0.5 на ребре, 0.25 в углу прямоугольника; значения округляются до1e-12, чтобы файл был одинаков на всех системах.
Файл частотно-независим: частотный коэффициент ядро применяет само на каждом шаге.
#dDelta файла обязан совпадать с DELTA шага. См.
диэлектрик и проводимость шлейфа и
форматы файлов.
Падающая волна из файла .sig
Ядро само умеет только a = Amp(t,f)*sin(2*pi*FREQ*t + Faza(t,f)) — несущую под
огибающей. Любая другая форма (гребёнка тонов, ЛЧМ, видеоимпульс, пила, таблица точек)
задаётся файлом: на месте Amp пишется [имя], и файл <имя>.sig задаёт всю a(t)
(см. падающая волна из файла). Файл пишет
sigfile.h/.cpp:
- текст, две колонки «время в
TIME_UNIT, значение»; комментарии!и#; - шаг записи — вдвое мельче шага ядра
dt = DELTA/(c*sqrt(2))(см. шаг по времени); точек не больше 400 000, иначе шаг укрупняется (об этом предупреждает проверка); - интервал — опора сигнала, обрезанная по [0; TIME]; окно порта повторяет её;
- у многотона строка
#FREQ f1 f2 …(не больше 99 тонов); ядро переносит её в шапку.t, и постобработка берёт тоны оттуда, а не ищет по спектру; - гребёнка: каждый тон с полной амплитудой, плавное включение только на первых 5 % посылки — сглаживать конец нельзя: многотон обрабатывается на установившемся участке в конце счёта;
- служебная строка
@TPLD-SIGхранит параметры формы с 17 значащими цифрами — по ней чтение задания возвращает саму форму, а не таблицу точек; - имя файла по умолчанию —
<задание>_in<N>; точки в имени быть не должно (расширение ядро дописывает само только к имени без точки).
FREQ при сигнале из файла — частота согласования порта; suggestedFreq ставит её
в центр полосы гребёнки и ЛЧМ, на несущую радиоимпульса, на частоту повторения пилы и
меандра. SMATRIX такого шага ядро считает по всей полосе сигнала (см.
многочастотный расчёт).
Оценка памяти
ramEstimate (ramestimate.h/.cpp) оценивает оперативную память ядра заранее — чтобы
расчёт не остановился на ошибке выделения памяти после долгой подготовки сетки.
- Узлы: , так же .
- Сетка: 52 байта на узел у ядра H, 127 — у ядра X.
- ДН по всей области: байта на узел ( числа
double). - ДН по полосам у границы (см. полосы у границы):
Многотонная ДН считается по полосам всегда; одночастотная — если ДН по всей области
заняла бы больше четверти свободной памяти и сетка не меньше 32x32 узлов.
* Число тонов ДН ограничено 99 (kMaxFreqs).
Проверка предупреждает, если многочастотной ДН понадобится 2 ГБ и больше: это потолок 32-разрядного ядра.
Кодировка CP1251
Ядра читают задание в CP1251, а Qt 6 этой кодировки не знает: QStringEncoder для
windows-1251 молча отдаёт 0 байт. Поэтому кодек свой (cp1251.h/.cpp):
- запись (
toCp1251): ASCII как есть, «А…я» — смещением, остальное — по таблице старшей половиныkHighTable[128]; похожие символы не подставляются: всё, чего нет в CP1251 (греческие буквы, стрелки, знаки), становится?и поднимает флагlossy. Проверка ловит такие символы заранее — в описании задания и в именах; - чтение (
readTplFileText) определяет кодировку само: BOM — UTF-8; есть байты старше 0x7F и текст корректен как UTF-8 — UTF-8; иначе CP1251; байт 0x98 (в CP1251 не определён) читается как U+FFFD; - файл задания одинаков на всех системах: своя таблица вместо системного
кодировщика, переводы строк всегда CRLF, имя ядра в шапке без расширения; запись
атомарная, через
QSaveFile.
В тексте, уходящем в .tpl, допустимы только символы CP1251: вместо ε, λ, →
пишется eps, lambda, ->.
Перевод интерфейса и заданий
Все тексты ядра генератора — замечания проверки, комментарии и имена в .tpl,
названия образцов и паспорта — идут через tpl::tr("русский", "English") (lang.h).
Функция выбирает строку по глобальному флагу языка при каждом вызове, поэтому:
- переведённый текст нельзя хранить в
static— язык «застынет» на первом обращении; таблицы строятся функциями и хранятся по одной на язык (каталог образцов, паспортbaked.cpp); - русский текст неизменен байт в байт: при русском языке все файлы прежние;
английские строки, уходящие в
.tpl, — только ASCII (--вместо—); - чтение понимает свои файлы на обоих языках при любом текущем: «Задание сгенерировано» / «Task generated», «Ядро:» / «Kernel:», « — » / « -- » в подписях блоков, «вариант» / «variant»;
plural()склоняет числительные: по-русски три формы, по-английски две.
Имена фигур — данные задания и при смене языка не переводятся.
Запись задания на диск
writeTask (taskfiles.h/.cpp) — единственный путь записи задания:
- части конвейера (
emitChunks):<имя>.tplи, у макро-версии,<имя>_step.h— в CP1251 с CRLF; - при нескольких частях — пакетные файлы
<имя>_run.batи<имя>_run.sh; оба удаляют файлы.sперед прогоном каждой части (ядро их дописывает) и ищут ядро под обоими именами; - файлы падающей волны
.sigдля портов с сигналом из файла; - сопутствующие файлы (
companionsобразцов, напримерlens.eps).
taskFileNames перечисляет имена, которые появятся, — по ним интерфейс предупреждает о
перезаписи. runFlags даёт ключи запуска ядра: /Arb или /Arb /Time (отчёт о времени
расчёта — ключ командной строки, в языке задания его нет, и сам .tpl от него не
меняется).
Каталог образцов
Библиотека образцов (src/core/samples) — это рецепты, а не файлы. Образец
Sample хранит идентификатор латиницей, раздел, название, строку для плитки, стандарт,
справку, ядро (H или X), список параметров Param и функцию build: Values -> Build.
Параметр бывает четырёх видов — число, целое, выбор, флажок; все значения передаются
числами double по ключу.
Build — результат рецепта: готовый Project, строки паспорта «теория» (формулы из
rf.cpp), пояснения и сопутствующие файлы companions (например, lens.eps).
Как образец превращается в задание (make(s, v)):
- недостающие значения берутся по умолчанию;
- каждое значение прижимается к [min; max];
- целые, выборы и флажки округляются;
- вызывается
build; - пустое описание задания заменяется названием образца.
Записывает задание тот же writeTask, что и мастер, — вместе со companions и файлом
.sig. Каждый рецепт при значениях по умолчанию обязан проходить validate() без
ошибок и без потерь CP1251.
| Файл | Содержание |
|---|---|
sample.h, catalog.cpp |
описание образца, каталог из пяти разделов (волноводы, антенны, микрополосковые, среды, уроки); таблица строится функцией и хранится по одной на язык |
kit.h/.cpp |
Builder — сборка задания: номера блоков из одного счётчика, фигуры, входы, стенки волновода, рамка поглотителя, частоты, время счёта и окна снятия; правила выбора шага сетки |
waveguides.cpp |
9 рецептов: H-ядро, входы H10, сечение по стандарту |
antennas.cpp |
5 рецептов: открытая область с рамкой поглотителя, S11 и ДН |
microstrip.cpp, microstrip2.cpp, msplanar.h |
14 рецептов на планарной модели микрополоски (эффективные ширина и eps, входы плоской волны с ручной eps входа); два — с падающей волной из .sig |
media.cpp |
13 рецептов: слой, профиль eps, файл .eps, линза Люнеберга, плазма (X-ядро), ЭПР с вариантами геометрии и угловым свипом |
standards.cpp |
22 сечения EIA/IEC (полоса из стандарта), 24 сечения ГОСТ 20900-75 (расчётная полоса 1.25–1.9 fc), 9 подложек |
rf.cpp |
формулы паспорта: длина волны в волноводе, диафрагма, штырь, слой, прототипы фильтров, микрополоска, ЭПР цилиндра и полосы |
baked.cpp |
числа, посчитанные ядром при значениях по умолчанию; порождается скриптом tools/bake_samples.py (команда cpp), руками не правится |
usersamples.h/.cpp |
«Мои образцы»: Документы/TPL Designer/Мои образцы/<название>/ с заданием и sample.json |
lessons.cpp, lessons.qrc |
уроки: 7 авторских заданий из ресурса, читаются тем же readTplText |
Правила Builder, на которые опираются рецепты:
- шаг сетки (
chooseDelta) — не крупнее lambda/20 и четверти наименьшей детали, из «круглого» ряда 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 8 (с порядком); размер детали укладывается в целое число ячеек (deltaFitting), см. правила сетки; - время счёта округляется вверх до 5 нс, окно снятия S-матрицы — последние 25 % счёта, но не меньше 3 нс; конец окна ДН подрезается так, чтобы ядро его закрыло;
- поля и топологию рецепты не включают — проверочные прогоны иначе идут десятки минут;
- ломаная стенки пишется тремя точками (
POLYGON_STATменьше чем с тремя строкамиLне грузится).
Паспорт baked.cpp показывается у карточки только при значениях по умолчанию
(isDefault): числа посчитаны ровно для них.
⚠️ Ссылка Shape& или Port&, полученная от Builder, становится недействительной после
следующего добавления: вектор переселяется. Рецепты сначала добавляют все порты и
фигуры, а потом правят их по индексу.
Подводные камни
- Ошибка запрещает запись. Поэтому ошибкой считается только то, что отвергнет ядро; новое замечание о «физическом смысле» в ошибки добавлять нельзя — рабочие задания перестанут сохраняться.
.sдописывается. Шапка задания и пакетные файлы называют все файлы.s, которые надо удалить перед прогоном; без этого к новым точкам подмешаются старые.- Ссылки в векторы модели.
Shape&илиPort&нельзя держать через добавление следующего элемента:QVectorпереселяется. - Имена файлов в
src/coreне должны совпадать со стандартными заголовками (каталог стоит в путях поиска; файлsignal.hперекрыл бы системный<signal.h>). - Номера строк в предупреждениях чтения — из исходного файла: препроцессор
оставляет на месте
#defineпустую строку. - Регистр имён файлов (
#include,.sig) при чтении не учитывается: задания пишут на Windows, а читают и на Linux, и на macOS. - Круговорот «записал — прочитал» обязан возвращать ту же модель: числа пишутся с
10 значащими цифрами, добивка отрезка убирается при чтении, формула
(X)-1разбирается обратно вX, повёрнутый прямоугольник свипа снова становится прямоугольником.
Интерфейс
Интерфейс (src/gui, исполняемый файл TplDesigner) — тонкий слой над ядром генератора.
Он только собирает модель tpl::Project из рисунка и полей и вызывает функции ядра:
проверку validate, эмиттеры emitMono / emitMacro / emitChunks, чтение
readTplFile, запись writeTask, оценку памяти ramEstimate, файлы .sig и .eps,
импорт 3D. Синтаксиса .tpl окна не знают: ни одна строка задания не собирается в
src/gui. Платформенных веток в коде интерфейса нет, кроме двух мест «для человека» —
имя ядра в подсказке (kernelnames.h) и запрос объёма памяти (sysmemory.cpp); на
содержимое файла задания они не влияют.
Сборка: src/gui/CMakeLists.txt, цель TplDesigner линкуется с tpl_core, общей
библиотекой оформления пакета tmc_ui_base (gui_common: шрифты, окно «О программе»,
перевод — см. общий интерфейс) и Qt6::Widgets. Все окна работают в
одном потоке — потоке интерфейса; фоновых потоков у интерфейса нет.
Состав интерфейса
| Файл | Роль |
|---|---|
main.cpp |
точка входа: приложение, хранилище настроек, шрифты, язык, таблица стилей, сторож колеса, оболочка QMainWindow с коротким меню и стеком страниц, пересоздание страниц при смене языка, открытие файла из командной строки |
startwindow.* |
StartWindow — стартовое окно: четыре карточки «Создать», «Открыть», «Взять образец», «Вспомогательные файлы» |
mainwindow.* |
MainWindow — мастер задания: пять разделов, холст, проверка, отмена, чтение и запись задания |
geometryview.* |
GeometryView — холст геометрии (QGraphicsView): рисование, выделение, привязка, ручки, слои, режим картинки для образцов |
propertypanel.* |
PropertyPanel — панель свойств выделенного объекта рядом с холстом |
runplanpage.* |
RunPlanPage — раздел «Что считать»: очередь возбуждений, варианты геометрии, угловой свип |
shapedialog.* |
ShapeDialog — полная форма фигуры |
portdialog.* |
PortDialog — полная форма порта: размещение, среда входа, сигнал |
signalgallery.*, signalpreview.* |
галерея форм сигнала и предпросмотр a(t) со спектром |
filemaker.* |
FileMakerDialog — мастерская вспомогательных файлов .sig и .eps |
import3ddialog.*, meshview.* |
импорт сечения 3D-модели: окно выбора плоскости и вид модели |
samplespage.* |
SamplesPage — библиотека образцов и «Мои образцы» |
calculatordialog.* |
CalculatorDialog — справочный калькулятор среды и волновода |
issuedialog.* |
IssueDialog — прокручиваемое окно замечаний, collapseIssues |
memorydonut.*, sysmemory.* |
кольцевая диаграмма памяти и запрос ОЗУ у системы |
settings.*, settingsdialog.* |
настройки вида и окно настроек |
dtheme.* |
цвета и таблица стилей, fitToScreen |
wheelguard.* |
WheelGuard — колесо мыши не меняет поля без фокуса |
kernelnames.h |
имя ядра и строка запуска на текущей системе |
app.rc, app.manifest, resources.qrc, resources/ |
значок .exe и манифест Windows, ресурсы Qt (значок окна, стрелки счётчиков), значки для macOS и Linux |
Окна и страницы
Программа — одно окно верхнего уровня. main.cpp создаёт QMainWindow, в центре
которого лежит QStackedWidget из трёх страниц:
QMainWindow (меню: «Настройки» → Language / Язык; «Справка» → «О программе TPL Designer…»)
└─ QStackedWidget
├─ StartWindow — стартовое окно
├─ MainWindow — мастер задания (владеет tpl::Project)
└─ SamplesPage — библиотека образцов
Меню намеренно короткое, как у программ пакета: «Настройки» (выбор языка —
tmci18n::addLanguageMenu) и «Справка» (единое окно «О программе» tmcabout::show из
gui_common). Меню «Файл» нет: создание и открытие задания ведут стартовое окно и
мастер, запись — кнопка «Создать файл задания» в разделе «Проверка».
Страницы не знают друг о друге: каждая только испускает сигналы, а связи ставит
main.cpp.
| Действие | Сигнал | Что делает main.cpp |
|---|---|---|
| «Создать» | StartWindow::createRequested |
если в мастере есть работа (MainWindow::hasContent), спрашивает «Начать новое / Вернуться к прежнему»; затем resetProject и переход в мастер |
| «Открыть» | StartWindow::openRequested |
окно выбора .tpl, MainWindow::loadFromFile; при неудаче остаётся на старте |
| «Взять образец» | StartWindow::samplesRequested |
показывает SamplesPage |
| «Вспомогательные файлы» | StartWindow::filesRequested |
модальный FileMakerDialog поверх старта (с проектом мастера) |
| «Открыть образец» | SamplesPage::openRequested(project, companions) |
при наличии работы спрашивает подтверждение, затем MainWindow::openSample |
| «Назад» в библиотеке | SamplesPage::backRequested |
возврат на старт |
| «В начало» в мастере | MainWindow::backToStartRequested |
возврат на старт; задание в мастере сохраняется |
Задание можно передать первым аргументом командной строки (TplDesigner задание.tpl;
аргумент, начинающийся с -, не считается файлом) — так работает ярлык Linux
Exec=TplDesigner %f. Размер окна — не меньше 1280x820 и не меньше, чем просит
разметка (minimumSizeHint): на шрифтах шире Segoe UI окно иначе открылось бы уже
своего содержимого.
Поток действий пользователя
- Старт. Пользователь выбирает «Создать», «Открыть», образец или вспомогательный файл.
- Мастер (
MainWindow). Слева — дерево из пяти разделов, справа — страница раздела, под ней — список замечаний проверки, внизу «Назад» / «Далее». Разделы доступны в любом порядке; «Далее» просто ведёт по ним по очереди:
| № | Раздел | Страница | Что задаётся |
|---|---|---|---|
| 1 | Расчёт | buildSetupPage |
имя файла, ядро H или X, единицы линейки, счётная область, DELTA, TIME, одна частота или диапазон, конвейер заданий |
| 2 | Геометрия | buildGeometryPage |
фигуры и порты на холсте, свойства в панели, список объектов |
| 3 | Что считать | RunPlanPage |
очередь возбуждений, варианты геометрии, угловой свип |
| 4 | Вывод данных | buildOutputPage |
файл сигналов, топология, поля, S-матрица и её окно, ДН и её окно, замер времени |
| 5 | Проверка | buildSummaryPage |
сводка, диаграмма памяти, текст файла, «Создать файл задания», «Сохранить как образец…» |
Слева под деревом — «Калькулятор среды» (CalculatorDialog), «Вспомогательные
файлы» (FileMakerDialog) и «В начало»: они нужны на любом шаге.
3. Проверка на каждом шаге. После любой правки MainWindow::refreshAll вызывает
tpl::validate и заполняет список замечаний под страницей (ошибки красным,
предупреждения жёлтым, повторы схлопнуты collapseIssues). Ошибку видно там, где её
сделали, а не в конце мастера.
4. Запись (MainWindow::onGenerate): снова validate — при ошибках окно
IssueDialog и отказ; выбор папки (по умолчанию — папка открытого файла); вопрос о
перезаписи существующего .tpl (если включён в настройках; отдельно сказано, что
перезаписывается тот самый открытый файл); tpl::writeTask пишет .tpl, _step.h,
части конвейера и пакетные файлы, .sig, сопутствующие .eps. Итог перечисляет
записанные файлы, напоминает удалить .s перед прогоном (ядро его дописывает) и
держать _step.h рядом с заданием, даёт строку запуска ядра
(kernelRunCommand(kernel, name, tpl::runFlags(p))) или имя пакетного файла
конвейера и предупреждает, если часть символов не легла в CP1251. Затем предлагает
«В начало» или «Остаться в задании».
Мастер ядра не запускает: он пишет файлы и говорит, чем их считать. Запуск —
строкой из итога или пакетным файлом <имя>_run.bat / <имя>_run.sh конвейера.
Мастер и проект
MainWindow владеет единственным экземпляром tpl::Project (m_project). Холст,
панель свойств и страница «Что считать» получают на него указатель (setProject)
и правят его на месте. Поэтому разделы мастера не теряют состояния при переключении:
у всех одно задание.
Два направления синхронизации:
- поля разделов «Расчёт» и «Вывод данных» → проект:
pullFromForm(на каждое изменение поля). Частоты собираетcollectFreqs: одна частота или сетка «от — до — шаг» с допуском полшага на последнюю точку; - проект → поля:
pushToForm(при открытии файла, образца, отмене). Флагm_loadingне даёт этим записям вернуться обратно в проект.
После любой правки refreshAll обновляет всё зависимое: подписи о виде файла (одна
частота — обычный .tpl; несколько — макро-версия <имя>.tpl + <имя>_step.h; больше
tpl::kMaxFreqs = 99 — ошибка с двумя ссылками-выходами: «взять шаг»
stepForMaxFreqs или «разложить» по конвейеру), оценку памяти ДН, холст, панель
свойств, список объектов, сводку и замечания.
Окна снятия едут за временем счёта (followTimeWindow). Окно S-матрицы и окно ДН
живут в «Выводе данных», а TIME — в «Расчёте». Если после правки TIME окно перестало
помещаться в счёт, оно ставится на последнюю четверть счёта, но не короче 3 нс; окно,
выставленное внутри счёта вручную, не трогается. Окно ДН, которое ядро не закроет до
TIME (оно дотягивает окно до целого числа периодов), подрезается
tpl::patternWindowSafeEnd.
Отмена и возврат. История — снимки всего проекта (m_undo, m_redo, глубина
kUndoDepth = 120): задание маленькое, копия дешевле, чем описание каждой правки
командой. Холст, панель свойств и страница «Что считать» перед правкой испускают
aboutToEdit — мастер снимает снимок (snapshot), после правки — projectEdited /
edited, и мастер вызывает refreshAll. Импорт 3D и принятая полная форма объекта —
одна правка, одна отмена. Поля разделов «Расчёт» и «Вывод данных» в историю не
попадают.
Открытие файла (loadFromFile): tpl::readTplFile; при неудаче — окно ошибок и
прежнее состояние. Иначе проект заменяется, запоминаются папка и имя (для
«сохранить туда же» и для честного «перезапишете оригинал»), подхватываются файлы
.eps блоков FILE из папки задания (m_companions, пишутся рядом при каждой записи).
Затем — сводка числами (фигуры, порты, частоты, варианты, была ли макро-версия и что
подключено #include) и одно окно IssueDialog, если чтение дало предупреждения или
проверка — ошибки.
Образец (openSample) открывается как новое задание без исходной папки; его
сопутствующие файлы (например, lens.eps) ложатся рядом при каждой записи.
«Сохранить как образец…» (onSaveAsSample) кладёт задание без ошибок проверки в «Мои
образцы» (samples::saveUserSample) с названием и описанием.
Полные формы. Двойной щелчок по объекту или «Все свойства…» → onEditRequested:
ShapeDialog для фигуры, PortDialog для порта. Принятая форма заменяет объект
одним шагом отмены. После PortDialog с сигналом из файла частота задания (при одной
частоте) ставится в PortDialog::wantedFreq() — это частота согласования порта
(tpl::suggestedFreq), и об этом пишется в строке подсказки: уехавшая FREQ молча
портит согласование.
Вид геометрии
GeometryView — наследник QGraphicsView. Сцена пустая: фигуры не хранятся как
элементы QGraphicsItem, всё рисуется заново из tpl::Project в
drawBackground / drawForeground. Так у модели один источник правды, и картинка
не может разойтись с тем, что запишет эмиттер. Координаты сцены — миллиметры, ось Y
направлена вверх (как в задании).
Модель и сигналы. Холст получает указатель на проект (setProject) и правит его
сам. О правках он сообщает сигналами: aboutToEdit (до правки — для отмены),
projectEdited (после), selectionChanged, toolChanged, cursorMoved (координаты
после привязки, мм — в строку под холстом), hintChanged (подсказка «что делать
дальше» к инструменту), editRequested (двойной щелчок — полная форма),
mergeRequested (пункт «Соединить» контекстного меню).
Инструменты (enum class Tool, кнопки с подписями слева от холста и буквенные
клавиши, которые работают только когда холст в фокусе):
| Инструмент | Как рисуется | Что получается |
|---|---|---|
Select |
щелчок, протяжка, ручки | выделение, перетаскивание, правка размеров, поворот |
Rect |
протяжка | прямоугольник (RECT_STAT) |
Line |
щелчок за щелчком, двойной щелчок или Enter — конец | ломаная (POLYGON_STAT материала, не замкнута) |
Contour |
так же | замкнутый контур |
Circle |
протяжка из центра | круг |
Arc |
центр → радиус → раскрыв | сектор кольца |
ArcLine |
начало → конец → выгиб | дуга как линия (кривая стенка): окружность по трём точкам, разбитая на звенья с шагом DELTA; три точки на одной прямой дают отрезок |
Port |
протяжка | вход: апертура и направление падающей волны |
Ломаная, контур и дуга завершаются в finishChain (двойной щелчок или Enter;
повторные точки снимаются). Shift делает направление звена кратным 45°, а поворот за
ручку — кратным 15°. Новая фигура получает материал «металл» и имя по своему виду
(«Линия N»). Порт получает сторону по направлению протяжки (sideForDrag) или по
ближайшей стороне области (nearestSide).
Язык задания кривых не знает (POLYGON_STAT — только список вершин), поэтому дугу,
скругление (filletSelected) и сшивание кусков в одну фигуру (mergeShapes) делает
редактор: иначе такую геометрию пришлось бы готовить сторонней программой.
Привязка (findSnap). Допуск задан в пикселях экрана (kSnapPx = 11) и
переводится в миллиметры по текущему масштабу. Порядок, от сильной цели к слабой:
- характерные точки нарисованного — вершины, центры, середины сторон — и углы счётной области;
- любая точка на линиях фигур и на окружностях;
- узел сетки с шагом DELTA задания (
gridStep; 1 мм, если шаг не задан).
Метка «к чему прилипли» показывается у курсора. При перетаскивании выделенного привязка — только к сетке, и сама перетаскиваемая фигура из целей исключается. Привязку и сетку переключают кнопки над холстом; начальные положения — из настроек. Узлы сетки — это узлы расчётной сетки ядра: блок на узлах и границы, кратные шагу, ядро считает точно (см. правила сетки и размещение на сетке).
⚠️ Так как допуск — в пикселях, вписывать вид (zoomToFit) имеет смысл только после
того, как виджет получил размер (после возврата в цикл событий): при нулевом размере
масштаб выходит крошечным, и привязка тянет точки за десятки миллиметров.
Разбор попаданий (pick), допуск kPickPx = 7 пикселей:
- метки портов (радиус
kPortMarkerPx+ 2 пикселя) и линии апертур; - выделенная фигура — пока фигура выделена, щелчок по ней достаётся ей, кто бы ни лежал сверху (иначе тело внутри прямоугольника распределения eps нельзя было бы сдвинуть);
- все фигуры сверху вниз (позже нарисованная — сверху).
Попасть можно в фигуру целиком, в сторону прямоугольника или в вершину ломаной:
Selection хранит вид (ShapeBody, ShapeEdge, ShapeVertex, PortBody), номер
объекта и номер стороны или вершины. Это нужно, чтобы мышью выразить «магнитная стенка
только сверху»: такие стороны эмиттер раскладывает на отдельные блоки.
Слои рисования. drawBackground — фон, сетка, пунктир счётной области.
drawForeground — сначала площадные фигуры (заливки, поле eps по формуле в выбранной
палитре), потом контурные (стенки) — стенки поверх заливок, а край заливки тонкой
полупрозрачной линией: край области не должен читаться как стенка. Дальше — свип,
порты (апертура, стрелка направления у активного), контур интегрирования ДН пунктиром,
размеры выделенной фигуры, ручки, предпросмотр рисуемой фигуры, линейки, шкала eps.
Правило: если на холсте что-то выглядит стенкой, это должно быть стенкой в расчёте.
Выделение и набор. Щелчок выделяет один объект; Ctrl+щелчок набирает
несколько фигур (повторный снимает). То же делают несколько строк списка объектов
справа. Набор двигается, дублируется (duplicateSelected, со сдвигом на 4 шага
сетки), удаляется (deleteSelected) и соединяется (mergeShapes) целиком; «Соединить»
доступна, только когда выбрано не меньше двух линий или контуров
(MainWindow::updateMergeButton). Список объектов и холст показывают одно выделение;
при смене выделения список только подсвечивается (syncLegendSelection), а
перестраивается лишь при правке проекта (refreshLegend) — иначе Ctrl-клик по строке
перестраивал бы список и терял набор.
Масштаб и сдвиг. Колесо — масштаб под курсором (шаг 1.15); средняя кнопка или Alt+левая —
сдвиг холста; кнопки «Вписать», «Приблизить», «Отдалить» (шаг 1.25). Клавиши холста: Esc —
отменить рисование или снять выделение, Enter — закончить ломаную, Del — удалить.
Правая кнопка — контекстное меню: «Свойства...», «Соединить в одну фигуру (N)», «Дублировать (N)», «Удалить (N)». Полосы прокрутки скрыты. Отмены в самом холсте нет: он только испускает aboutToEdit, историю ведёт мастер.
Режим картинки (setPreview(true)): мышь, фокус и клавиши выключены; нет ручек,
линеек, размеров и подсказок; отступ сцены 3 % вместо 14 % + 5 мм, вид вписывается
заново при каждом изменении размера. Статический GeometryView::render(project, size)
рисует копию проекта в картинку вне экрана. Так SamplesPage и окно импорта 3D рисуют
задание тем же кодом, что и мастер.
Панель свойств
PropertyPanel стоит справа от холста над списком объектов и показывает свойства того,
что выделено: фигуры, стороны прямоугольника, вершины или порта. Строки формы созданы
один раз (build), а видимыми становятся только относящиеся к делу (updateDerived):
- фигура — имя, материал (металл, магнитная стенка, поглотитель — контур; диэлектрик — заливка), eps с подсказкой «в файл уйдёт добавка eps-1», размеры прямоугольника или круга/сектора, число вершин;
- в X-ядре — плазма в одной фигуре: N (м^-3), B (Тл), потери sigma (См/м) и сеточное Y,
числом или формулой; у прямоугольника — величина из файла (
FILE_N/_B/_Y); флажок «B ровно по плазме»; подсказка с частотамиf_p,f_ceи отсечками X-моды (tpl::plasmaBands); - сторона прямоугольника — «сторона существует», свой материал стороны;
- порт — направление волны, плоскость входа, апертура, роль (активный/пассивный), тип
волны (H10 или плоская); подсказка — одномодовый диапазон апертуры
c/(2a)...c/a.
Каждое изменение поля сразу пишется в проект (pushToProject): aboutToEdit →
правка → edited. Текстовые поля пишутся по окончании ввода, а пока панель сама пишет
в проект (m_pushing), значения полей не перезаписываются — иначе курсор прыгал бы во
время набора числа. Направление порта панель приводит в согласие с половиной области
(tpl::directionForPlane): иначе ядро молча развернуло бы падающую волну. Ломаная,
которой назначили заливку, молча замыкается в контур — выражение eps ядро всегда
понимает как область. Ряд кнопок внизу: «Скруглить» с радиусом, «Все свойства…»,
«Соединить», «Дублировать», «Удалить».
Что считать
RunPlanPage — раздел 3 мастера. Он правит Project::exciters (очередь возбуждений
портов: каждое возбуждение — свой #STEP и свой столбец S-матрицы),
Project::variants (варианты геометрии: название, тег файлов, какие фигуры входят;
у каждого варианта свой .s) и Project::sweep (поворот объекта по шагам для ЭПР:
фигуры объекта, ось, углы, опорный шаг без объекта). Внизу страница показывает, что
получится: число шагов (Project::stepCount) и имена файлов. Правит проект по
указателю с той же парой сигналов aboutToEdit / edited. Подробности модели — в
разделах модель задания и угловой свип.
Окна и диалоги
| Окно | Кто открывает | Что делает |
|---|---|---|
ShapeDialog |
двойной щелчок по фигуре, «Все свойства…» | полная форма фигуры: тип и имя, материал и eps, eps формулой с проверкой при наборе (tpl::ExprProgram::compile, epsVariables, epsSamplePoints), профиль из файла .eps (только прямоугольник, блок FILE) или запись профиля в файл (только RECT_STAT), своё начало отсчёта x, y; плазма (только X-ядро): N, B, «B ровно по плазме», sigma, Y и файлы FILE_N/_B/_Y; размеры по виду фигуры, таблица вершин; скорость Vx, Vy (блоки *_MOVE). Возвращает изменённую копию tpl::Shape (shape()) |
PortDialog |
двойной щелчок по порту, «Все свойства…» | группы «Размещение» (сторона, апертура, eps входа — по умолчанию добавка среды под входом, tpl::portMediumEps), «Возбуждение» (активность, H10 или плоская волна, сигнал формулой или из файла .sig, своя таблица точек; sigPlan, waveBand, portWindow, parseSigPoints, parseSigTones, toneCutNotice), «Что придёт на вход» (предпросмотр SignalPreview). Частоту задания сам не меняет: wantedFreq (tpl::suggestedFreq) отдаёт её мастеру |
CalculatorDialog |
кнопка «Калькулятор среды» | справка без записи в задание; пары пересчитываются в обе стороны: ширина волновода <-> отсечки H10/H20; диэлектрик — добавка eps-1, длина волны в вакууме и в среде; N <-> f_p (plasmaFreqGHz, concentrationForFreqGHz), B <-> f_ce (cyclotronFreqGHz, fieldForFreqGHz), отсечки X-моды f_L, f_R (plasmaBands). См. плазменную частоту и циклотронную частоту |
FileMakerDialog |
карточка на старте, кнопка в мастере | мастерская файлов, см. ниже |
Import3DDialog |
«Импорт из 3D…» на палитре инструментов | сечение 3D-модели, см. ниже |
SettingsDialog |
«Настройки…» над холстом | вид холста, см. настройки |
IssueDialog |
запись, чтение, сохранение образца | список ошибок и предупреждений |
IssueDialog заменяет QMessageBox для любых списков замечаний: QMessageBox не
прокручивается и на большом чужом задании вырастал за край экрана вместе с кнопкой
«ОК». Здесь текст в прокручиваемой области, кнопки — вне её, окно ужимается до экрана
(dtheme::fitToScreen) до показа. Повторы схлопываются collapseIssues: замечания,
отличающиеся только префиксом «строка N:» / «line N:», сводятся в одно с припиской
«— и ещё k раз(а) то же самое дальше по файлу»; номер строки первого остаётся.
Сигналы на портах
SignalGallery — выбор формы сигнала плитками со значками (waveformIcon; кривая
рисуется paintWaveform по показательным параметрам формы demoWaveshape) и
пояснением к выбранной форме (tpl::waveformHint); смена плитки — сигнал
currentChanged. SignalPreview показывает сигнал порта так, как его посчитает ядро:
- развёртка a(t) на всём времени счёта [0; TIME] с границами окна порта
(
tpl::portWindow); значения —tpl::waveValueили формула ядра (sampleAt); - амплитудный спектр под ней: от 4096 до 65536 выборок (не меньше четырёх на
период верхней частоты), БПФ по основанию 2 с двукратным дополнением нулями,
256 столбиков (в каждом — максимум модуля по попавшим отсчётам); верх шкалы —
2*FREQ или 1.3 верхней частоты полосы, но не выше частоты Найквиста. На спектре —
одномодовый диапазон апертуры H10...H20 и линия
FREQ: видно, попадает ли полоса сигнала из файла в одномодовый диапазон.
Теория — сигнал на порту и
падающая волна из файла; формат — файл .sig.
Вспомогательные файлы
FileMakerDialog — модальное окно с двумя вкладками: «Файл сигнала (.sig)» и «Файл
распределения (.eps)». Открывается карточкой стартового окна и кнопкой мастера; задание,
переданное в конструктор, даёт только умолчания (DELTA, TIME). Своего пути записи у окна
нет — оно пишет теми же функциями ядра, что и мастер.
- Вкладка
.sig: галерея формSignalGallery, поля формы (набор —tpl::waveFields), таблица точек иSignalPreview; сводкаtpl::sigPlan(шаг записи, число точек, обрезка по времени),waveBand,suggestedFreq. Файл пишетсяtpl::sigFileText+toCp1251; при потере символов CP1251 не пишется. Таблицу можно набрать руками или взять из любой формы (20 точек на период верхней частоты, от 400 до 50000). Готовый.sigоткрывается: если его писала эта программа (служебная строка@TPLD-SIG), возвращается сама форма со всеми параметрами, иначе точки и тоны (parseSigPoints,parseSigTones) ложатся в форму «Своя таблица»; тонов больше 99 — предупреждениеtoneCutNotice. - Вкладка
.eps: формула eps(x, y, r, f), флажок «Начало в центре», картаEpsMapViewпоtpl::epsValues(показывает добавку eps-1), записьtpl::epsFileBytes. Чужой.epsчитается (readEpsHeader,readEpsValues), и карта показывает его числа по узлам — формулы у прочитанного файла нет.
Импорт 3D
«Импорт из 3D…» на палитре инструментов (MainWindow::onImport3D) спрашивает файл
модели (STL, OBJ, при сборке с OpenCASCADE — STEP; фильтр tpl::meshFileFilter) и
открывает Import3DDialog с копией проекта. Поток окна:
loadFile->tpl::readMeshFile. Единицы STEP берутся из файла, у STL и OBJ их выбирает человек;rescaleмасштабирует и сшивает сетку (Mesh::scale,Mesh::weld).- Таблица тел: материал каждого тела — запомненный выбор (
QSettings,import3d/materials/<имя>) или догадка по имени (tpl::guessMaterial). - Плоскость XY, YZ или XZ — кнопкой или щелчком по модели в 3D (
MeshView::planeClicked: луч из глаза до ближайшей плоскости); положение — ползунком или полем, мм. updateSlice:tpl::sliceMesh->tpl::simplifySlice(допуск DELTA/2) -> при «в центр области»tpl::centeringShift->tpl::buildImportShapes(поворот на 90°, зеркало, сдвиг, номера блоков сnextFreeId). Не помещается срез — по галочке область расширяется с запасом 10 DELTA. Предпросмотр «Что вставится» —GeometryViewна задании с фигурами среза.- Мастер забирает
result(), новую область (resultBox,boxChanged) и строку происхождения (provenance,tpl::sliceProvenance) и вставляет фигуры одной правкой (MainWindow::insertImport): одна отмена убирает весь импорт, происхождение дописывается в описание задания, новые фигуры выделяются.
MeshView — QOpenGLWidget (шейдеры GLSL 1.10): тела (сначала непрозрачные, потом
полупрозрачные) и полупрозрачные плоскости; рамки, подписи и линия среза рисуются на
прозрачном дочернем виджете поверх (QPainter внутри paintGL виден не на всех
системах). Камера на орбите: левая кнопка — поворот, колесо — масштаб, средняя кнопка
или Alt+левая — сдвиг. Сечение и превращение его в фигуры делает ядро генератора —
см. импорт 3D-моделей и импорт STEP.
Библиотека образцов
SamplesPage — страница стека в три колонки:
- слева — разделы («Все», разделы каталога
tpl::samples::sections, «Мои образцы») и поиск по всем словам по всей библиотеке; - в середине — плитки образцов (
TileDelegate); картинки рисует статическийGeometryView::renderпо таймеру, по две за проход цикла событий, чтобы страница не замирала; - справа — карточка: эскиз (
GeometryViewв режимеsetPreview), параметры рецептаParam(число, целое, выбор, флажок; после правки задание пересобирается через 120 мс), итогtpl::validate, паспорт — «теория» (Build::theory) и «посчитано ядром» (tpl::samples::baked, только при значениях по умолчанию,isDefault), пояснения, сопутствующие файлы, справка.
Задание строит buildFor: make(sample, values) для встроенного рецепта или
loadUserSample для своего. «Открыть в редакторе» и двойной щелчок по плитке испускают
openRequested(project, companions) — дальше main.cpp и MainWindow::openSample.
«Записать» пишет задание прямо из библиотеки: проверка, выбор папки (запоминается в
QSettings, samples/lastDir), вопрос о перезаписи по tpl::taskFileNames, запись
tpl::writeTask, строка запуска kernelRunLine. «Мои образцы» читаются
userSamples (список перечитывается при каждом показе страницы), удаляются
removeUserSample; кладёт их туда мастер («Сохранить как образец…»). См. каталог
образцов.
Память
Раздел «Проверка» показывает, поместится ли расчёт в память этого компьютера.
MainWindow::updateMemoryChart берёт объём и свободную часть ОЗУ у системы
(sysmem::query: Windows — GlobalMemoryStatusEx, macOS — sysctl и
host_statistics64, Linux — MemAvailable из /proc/meminfo) и оценку памяти
задания tpl::ramEstimate(project, available) — свободную память ей передают, потому
что по ней ядро само решает, копить ли ДН по всей области или по краю, и картинка
обязана решить так же. MemoryDonut рисует кольцо всей ОЗУ: сплошной сектор
«занято», заштрихованные «сетка ядра» и «ДН», при нехватке — красные сектора и красная
дуга перебора; сектор меньше 1.5° расширяется до 1.5°, чтобы был виден. Подпись:
поместится, впритык (больше 80 % свободного) или может не поместиться; от 2 ГБ —
напоминание о потолке 32-разрядного ядра. Опрос — раз в 3 с, только пока страница на
экране. Это только сведения: записать задание можно в любом случае — считать его
могут на другой машине. См. оценку памяти.
Перевод интерфейса и смена языка
Все строки окон берутся через tpl::tr("русский", "English") (core/lang.h) — та же
функция, что и для текстов ядра генератора (см. перевод). Язык общий
для пакета: main.cpp вызывает tmci18n::install() и ставит
tpl::setEnglish(!tmci18n::russian()). Названия меню переводит словарь пакета
(gui_common/i18n), пункт «О программе TPL Designer…» — своя пара строк
(tmci18n::setOwnText).
tpl::tr выбирает строку при вызове, а окна читают тексты, когда строятся. Поэтому
при смене языка страницы пересоздаются (main.cpp):
- сигнал
QMenu::triggeredменю языка; проверка отложенаQTimer::singleShot(0)до возврата в цикл событий — к этому времени обработчик меню уже сменил выбор; - если язык действительно сменился —
tpl::setEnglish; запоминаются открытая страница, проект мастера и признакhasContent; - три страницы удаляются из стека (
deleteLater) и строятся заново функциейbuildсо всеми связями сигналов; - если в мастере была работа —
MainWindow::setProject(проект); открывается та же страница.
Обработчики сигналов берут страницы через структуру Pages по ссылке, поэтому всегда
обращаются к текущим, а не к удалённым. Имена фигур и портов — данные задания и при
смене языка не переводятся. История отмены при пересоздании не переносится.
Настройки
settings::Values — только предпочтения вида: градиентная заливка eps по формуле,
цветовая шкала eps, значение eps под курсором, палитра (Viridis, тепловая, серая),
сетка, привязка, размеры выделенной фигуры, вопрос перед перезаписью .tpl. Ничего,
что влияет на содержимое .tpl, в настройках нет: файл задания зависит только от
нарисованного и введённого. Хранилище — INI %APPDATA%/TMC_Suite_Qt/TPL Designer.ini
на Windows (settings::installStorage направляет туда и QSettings по умолчанию и
однократно переносит ключи реестра прежних версий), QSettings("TMC", "TplDesigner")
на Linux и macOS. Значения читаются при первом обращении (settings::values) и
записываются сразу (settings::setValues).
SettingsDialog применяет изменения сразу, по каждому флажку, — результат виден
на холсте за окном; кнопки «Отмена» нет, есть «Вернуть по умолчанию». Сигнал
settingsChanged перерисовывает холст. Шкалу eps, сетку и привязку можно переключать и
кнопками над холстом, не открывая окна.
Оформление
Оформление совпадает с программами пакета: тёмная палитра и шрифты Inter (интерфейс) и
JetBrains Mono (текст задания в предпросмотре). main.cpp объявляет программу
(theme::setProgram("tpldesigner")) и загружает шрифты (theme::uiFontFamily) из
gui_common, а таблицу стилей ставит свою — dtheme::styleSheet(). Общие элементы в
ней — те же значения, что в программах пакета (оформление),
дополнительно — свойства виджетов редактора: accent (акцентная кнопка), tool
(кнопка инструмента холста; нажатая — бирюзовая), card (карточка стартового окна и
библиотеки), hline (разделитель), dim, mute, h1, h2 (виды подписей). Цвета
палитры (dtheme::bg() … dtheme::warn()) нужны и холсту: он рисует их сам, и
таблица стилей с холстом не расходятся. dtheme::fitToScreen ужимает диалоги до 95 %
ширины и 88 % высоты экрана — окно, у которого не видно кнопок, не работает.
Значок окна — :/icons/resources/app.ico; значок .exe в проводнике — ресурс Windows
app.rc (это разные вещи, нужны обе).
Колесо мыши
WheelGuard ставится один раз на всё приложение (qApp->installEventFilter), поэтому
действует и на окна, созданные позже. Счётчики, выпадающие списки и ползунки (кроме
полос прокрутки) меняют значение колесом только когда поле уже в фокусе:
- на
QEvent::Polishполитика фокусаQt::WheelFocusменяется наQt::StrongFocus— фокус только щелчком и Tab, иначе колесо отдавало бы фокус полю раньше проверки; - на
QEvent::Wheelу поля без фокуса событие отвергается (ignore) и поглощается; Qt передаёт отвергнутое событие родителю — области прокрутки страницы, и страница листается.
Так при прокрутке страницы к «Далее» не меняются частота или шаг сетки, через поля которых проезжает указатель.
Подводные камни интерфейса
- Задание пишет только
tpl::writeTask. Своей записи файлов у окон нет — ни у мастера, ни у библиотеки, ни у мастерской файлов. - Длинные списки замечаний — только
IssueDialog, неQMessageBox. - Переведённый текст не хранить в
staticи не строить заранее: страницы пересоздаются при смене языка, аtpl::trвычисляется при вызове. - Указатель на проект. Холст, панель и «Что считать» держат
tpl::Project*мастера. Послеundo/redoиsetProjectмастер раздаёт его заново; указатели на отдельные фигуры и порты (PropertyPanel::shape,port) действительны только до изменения состава фигур. - Список объектов не перестраивать на выделении — только подсвечивать
(
syncLegendSelection); перестраивать — на правке проекта (refreshLegend). - Допуск привязки — в пикселях:
zoomToFitдо получения виджетом размера даёт неверный масштаб и «липкую» привязку. - Имена объектов виджетов (
shapeXMin,mergeShapes,btnNext,fileMaker,memoryDonutи др.) нужны служебной утилите снимковgui_shot, которая проходит руководство пользователя настоящими событиями; переименовывать их нельзя без правки утилиты.
Тесты и инструменты
Логика генератора живёт в библиотеке tpl_core без окон, поэтому почти всё, что
обещает редактор («ядро примет и посчитает так, как нарисовано»), проверяется
модульными тестами Qt Test без запуска интерфейса. Тесты — десять программ в каталоге
tests (около 190 тестовых слотов); каждая линкуется с tpl_core и Qt6::Test и
регистрируется в CTest. Интерфейс проверяется отдельно утилитой
gui_shot, а то, что задание действительно считается, — прогоном
ядер по заданиям из sample_gen, sig_gen и
gen_lr2.
Большинство тестов — сторожа конкретных ловушек языка .tpl или ошибок, уже
найденных прогонами: имя слота называет свойство (twoPointLineGetsThirdPoint,
noExponentReachesTheKernel), а комментарий к слоту в коде — ошибку, которую он ловит.
Падение такого теста означает, что выход эмиттера или чтение «поехали» именно в этом
месте.
Запуск
Тесты собираются общей сборкой пакета (build/build_win.sh); исполняемые файлы лежат в
build/obj/bin. Запуск всех тестов редактора:
cd build/obj/src/tpl_designer
ctest --output-on-failure
Один набор — ctest -R test_emitter, или напрямую build/obj/bin/test_emitter.exe;
отдельный слот — test_emitter.exe macroHasTwoBackslashesAndNoComments (стандартные
ключи Qt Test, например -v2 для подробного вывода). Тесты не открывают окон и не
запускают ядра; файлы, которые им нужно записать, пишутся во временные папки.
Запускать после любой правки src/core (эмиттер, проверка, чтение, сетка, образцы),
перед выпуском и после обновления Qt: часть сторожей ловит именно различия Qt и
стандартной библиотеки на разных системах.
Эталонные данные
Большинство наборов строит проекты в памяти и в файлах не нуждается. Внешние эталоны
подключаются путями, которые CMake передаёт макросами (tests/CMakeLists.txt):
| Макрос | Папка по умолчанию | Что там | Кто использует |
|---|---|---|---|
TMC_SAMPLES_DIR |
samples/TEST пакета |
задания ЛР1 и ЛР2, проверенные прогонами ядра | test_cp1251, test_tplreader |
TMC_IVTAN_DIR |
samples/IVTAN пакета |
full09.tpl — #include, десятки #define, CIRCLE_STAT, ABSORBER |
test_tplreader |
TMC_ERROR_DIR |
TMC_Suite_Mac/samples/error (соседний проект) |
mini_file.TPL — задание с блоком FILE |
test_tplreader |
TPLD_MODELS_DIR |
src/tpl_designer/data/models |
3D-модели, выпускаемые make_models |
test_mesh (STEP) |
Пути переопределяются переменными кэша CMake с теми же именами. Если эталона нет на
месте, слот (или строка данных) пропускается через QSKIP — набор при этом не падает,
но и проверка не выполнена: в выводе CTest это видно как SKIP.
test_cp1251 — кодировка
13 слотов. Проверяет собственный кодек CP1251 (см. кодировка CP1251):
ASCII проходит байт в байт, кириллица и «ё/Ё» (0xB8/0xA8) кодируются верно,
непредставимый символ (в том числе греческие буквы) становится ? и взводит флаг
lossy, а чистый текст флаг не взводит. Запись writeCp1251File даёт только CRLF и
сохраняет \\; чтение различает UTF-8, UTF-8 с BOM и CP1251. Данные встроены в тест;
matchesGoldenFileBytes сверяется с LR2_1_wg_p1.tpl из TMC_SAMPLES_DIR.
Главные сторожа:
wholeTableMatchesWindowsCodepage— все 256 байт в обе стороны против кодовой страницы 1251 Windows (0x98 -> U+FFFD): только это гарантирует одинаковый файл на всех системах;qtOwnEncoderIsBrokenForCp1251— фиксирует, что кодировщик Qt для windows-1251 молча отдаёт пустоту; если в сборке он работает (ICU), его байты обязаны совпасть с таблицей.
test_emitter — запись задания
40 слотов, внешних данных нет: проекты строятся в памяти (волновод 240 x 80 мм, шаг 1 мм, 4 ГГц, порты 7 и 12). Покрывает моно-задание и макро-версию:
- шапка
#TMC_RT_H,#EOF, строкиTв#LINK_LIST(по одной на блок), сторона порта по анкеру, вход внутри области, центр круга в анкере; - добавка eps-1 вместо eps, ключевые слова материалов, профиль eps и блок
FILE, eps входа (добавка, eps строго больше 0); - плазма X-ядра:
_N/_B/_Y, блок B шире плазмы на 2 шага,CIRCLE_STAT_Y,FILE_N/_B; - полигоны: замыкание контура, третья точка у отрезка, обход по часовой стрелке, раскладка прямоугольника по сторонам;
- сигналы: окно пассивного порта, гаусс без оператора
^; - очередь возбуждений и варианты геометрии (свои
.s, имена в шапке); - макро-версия:
#defineна сочетание, ровно\\в переносе, подписи только за переносом,FIELDSна первом шаге.
Главные сторожа: generatedFileDoesNotDependOnTheSystem (имя ядра без .exe/.app,
CP1251 без потерь, CRLF, без BOM), twoPointLineGetsThirdPoint,
macroHasTwoBackslashesAndNoComments, portCanStandInsideTheArea (порт, чья сторона не
совпала с половиной коробки, — ошибка), cutoffIsJudgedByPortAperture.
test_epsfile — файл распределения eps
8 слотов, внешних данных нет. Проверяет формат .eps: шапку в метрах
(headerIsInMetres — ошибка в 1000 раз), веса узлов 1 / 0.5 / 0.25 внутри, на ребре и
в углу (nodeWeightsMatchTheKernel — иначе на общем ребре двойная добавка), обход
по строкам j = iY*nX + iX (nodeNumbersGoRowByRow), обратное чтение шапки, отказ на
чужом файле, переменные формулы (r, f — полярный угол, а не частота), ошибку на
неизвестном имени и округление значений до 1e-12, чтобы файл не зависел от математической
библиотеки системы.
test_expr — вычислитель выражений
13 слотов, внешних данных нет. Проверяет вычислитель редактора: числа (в том
числе с экспонентой — в редакторе они законны), арифметику и отказ при делении на 0,
приоритет операций и правую ассоциативность ^, функции и их область определения,
единицы углов (ANGLE_UNIT), пробелы внутри чисел как в ядре (2 3 = 23), отказ на
неизвестных именах и мусоре, ловушку макроса без скобок (38+12/2 = 44, а не 25),
выражения из samples/IVTAN/TOPOLOGY.H (константы вписаны в тест), scaleCoordinates
(заменяет только целые имена x, y). Сторож hugeExpressionDoesNotCrash: 200 000
слагаемых или 100 000 скобок дают отказ, а не переполнение стека.
test_mesh — импорт 3D
13 слотов. Проверяет импорт 3D-моделей: чтение STL (текст и двоичный)
и OBJ (тела, материалы, битая грань — предупреждение), срез sliceMesh (куб, труба,
тор, плоскость по грани), упрощение контура в пределах допуска, разбиение на выпуклые
куски без потери площади, угадывание материала по имени (металлы, eps диэлектриков,
поглотитель, воздух) и полный путь «модель -> фигуры -> validate -> emitMono». Тела
строит meshgen в памяти; два STEP-слота читают модели из TPLD_MODELS_DIR и
пропускаются в сборке без OpenCASCADE или без моделей. Сторож
unweldedMeshDoesNotClose: без сварки вершин контуры среза не замыкаются.
test_placement — размещение и проверки X-ядра
21 слот, внешних данных нет: сцена с плазмой (X-ядро, область 240 x 80 мм,
N = 1e17 м^-3) и встроенный текст .tpl. Три группы:
- запись — единицы первыми в
#PARM; подписьSMATRIXравнаFREQ, при сигнале из файлаSMATRIXбез окна; блок B на 2 шага шире плазмы и не заходит на соседнюю плазму, режимbExact; теги*_STAT_S/_Yу круга, блокиFILE_N/_Y; добавка eps входа по среде (portEpsFollowsTheMedium); - проверка — окно ДН закрывается до
TIME(patternWindowMustCloseBeforeTime: иначе файлов ДН нет), окна съёма после установления, правила контура ДН, краевой резонанс плазмы (edgeLayerResonanceIsWarned), плазма у магнитной стенки и на поглотителе, блок за областью; - чтение — sigma, файл и широкий B возвращаются одной фигурой;
tилиfв W входа; режим «eps по среде».
См. размещение на сетке и проверку задания.
test_samples — библиотека образцов
9 слотов перебирают все рецепты каталога; эталонов нет, файлы пишутся во временные папки:
catalogIsConsistent— целостность каталога: не меньше 30 образцов, уникальные идентификаторы, существующие разделы, непустые описания, умолчания в диапазонах, числаbaked.cppтолько у существующих образцов;everySampleIsValidByDefault— каждый образец при умолчаниях без ошибок проверки, без потерь CP1251 и без полей и топологии (иначе проверочные прогоны идут часами);everySampleSurvivesParameterExtremes,everyWaveguideStandardBuilds— края диапазонов параметров и все сечения стандартов;savedSampleReadsBackUnchanged,englishSamplesAreValidAndReadBack— запись -> чтение -> тот же текст, на обоих языках;epsFileHasKernelFormat—lens.eps: шаг в метрах равенDELTA, 12 байт на узел;formulasGiveKnownValues— справочные значения формул паспорта (отсечка WR-90 6.557 ГГц, прототипы Чебышёва и Баттерворта, микрополоска 50 Ом, функции Бесселя, ряд Ми);userSamplesRoundTrip— «Мои образцы» черезTPLD_USER_SAMPLES.
test_sigfile — падающая волна из файла
20 слотов, внешних данных нет: волновод 60 мм и гребёнка из 10 тонов 3...4.8 ГГц.
Покрывает файл .sig, конвейер заданий и
оценку памяти:
continuousSignalKeepsAmplitudeAtTheEnd— у многотона сглаживается только начало (сглаживание конца давало ошибку 1.9 дБ при внешне исправном задании);freqLineOnlyForMultiTone,stepIsFinerThanTheKernel(шаг.sigвдвое мельче шага ядра),portLineCarriesFileNameInBrackets(без пробела перед[),markerRoundTripsExactly,writeTaskPutsSignalFileNextToTask(CP1251, CRLF);- чтение: форма из файла, чужой файл как таблица, пропавший файл;
- конвейер:
chunkingSplitsGridAndNamesFilesApart(свой.sу каждой части, общий.sig,_run.batи_run.sh),runFlagsCarryTimingKey(ключ/Timeне меняет.tpl); - потолок 99 частот:
toneListIsCappedAt99,foreignFileKeepsItsFreqLine,moreThan99FreqsIsAnError; память многочастотной ДН —patternMemoryGrowsWithTones.
test_sweep — угловой свип
15 слотов, внешних данных нет: сцена рассеяния (пластина и стержень в области 300 x 300 мм, углы 0/30/60 градусов и опорный шаг). Покрывает угловой свип:
- подписи и имена файлов:
labelNeverZero,fileTagHasNoDot,freqKeepsItsDigits(9.35 не округляется до 9.4); - моно-версия пишет свой
.sна каждый угол с подписью, равной частоте (monoWritesReferenceAndAngles); повёрнутая геометрия — выражения отAng__; макро-версия описывает шаг один раз (macroDescribesStepOnce, ровно\\); validationCatchesWhatCannotRotate— несколько частот, варианты, B и профиль eps у поворачиваемой фигуры дают ошибку, а не молчаливую порчу;- круговорот моно- и макро-версии,
pivotFollowsTheObject,singleExciterIsJustTheActivePort,descriptionSurvivesRoundTrip; noExponentReachesTheKernel(запись вида1e17вычислитель ядра не понимает),frequencyMacroKeepsNames.
test_tplreader — чтение задания
39 слотов (из них 2 табличных _data), четыре группы. Покрывает чтение .tpl:
- препроцессор (8) —
!вырезается до склейки по\\, подстановка#defineтекстовая,includeIsFoundRegardlessOfCase(регистр имён на macOS и Linux),warningLineMatchesTheSourceFile(номер строки в предупреждении — из исходного файла); - круговорот (16) — профиль eps формулой, из файла
FILE, со смещённым началом, в круге; плазма N и B возвращается одной фигурой; профиль плазмы и пересчёт единиц; макро-версия; - эталоны (6) —
goldenSurvivesReEmit(эталон -> модель -> эмиттер -> модель),goldenMacroMatchesGoldenPlain(макро- и обычная версия ЛР2 дают одну модель); данные —TMC_SAMPLES_DIR(ЛР1, ЛР2, ЛР2 с плазмой),full09.tplизTMC_IVTAN_DIR,mini_file.TPLизTMC_ERROR_DIR; без файла —QSKIP; - непонятное (5) — добивка отрезка убирается без замечаний, имена фигур берутся из комментариев, текст не меняется при повторных сохранениях, очередь возбуждений не делает активными все входы.
Инструменты: обзор
Каталог tools — служебные консольные программы на C++ (собираются вместе с пакетом,
в выпуск не входят) и скрипты Python. Программы линкуются с tpl_core и работают той
же моделью Project, что редактор: задание, порождённое утилитой, — это ровно тот
файл, который записал бы мастер. Сборка — общая (build/build_win.sh), исполняемые файлы
лежат в build/obj/bin. Все программы пишут отчёт в stdout по-русски.
| Программа | Что делает | Когда запускать |
|---|---|---|
sample_gen |
выгружает образцы библиотеки в задания + manifest.txt |
при правке рецептов; перед обновлением паспортов |
sig_gen |
задания с падающей волной из .sig на каждую форму, конвейер, макро, эталон |
после правок sigfile/эмиттера; при проверке новых сборок ядра |
gen_lr2 |
задания ЛР2 и проверочные случаи эмиттера | после правок эмиттера — проверка прогоном ядра |
tpl_dump |
печатает, что парсер понял в .tpl; выдаёт его эмиттером обратно |
отладка чтения задания без окон |
gui_shot |
снимки окон в PNG и самопроверки интерфейса настоящими событиями | после правок src/gui; для снимков и видео руководства |
make_models |
тестовые 3D-модели (STL, OBJ, STEP) и задания проверки разрезанного диэлектрика | при изменении импорта 3D или набора моделей data/models |
make_icon |
значок программы для Windows, macOS, Linux | при изменении рисунка или палитры значка |
make_pdf |
печать HTML в PDF средствами Qt | из make_guide_pdf.py при выпуске руководства |
Коды возврата у всех программ одинаковы по смыслу: 0 — успех, 1 — ошибка
работы (не записан файл, задание не прошло проверку), 2 — неверная командная
строка (печатается подсказка). Исключение — sig_gen: ошибка отдельного задания
печатается, но код возврата остаётся 0.
sample_gen — выгрузка образцов
sample_gen <папка> [--no-fields] [id ...] [--set ключ=значение ...]
Строит каждый образец библиотеки (samples::all()) с параметрами по умолчанию,
проверяет его validate() и записывает общим tpl::writeTask в <папка>/<id>/ —
задание .tpl (у свипа ещё _step.h) в CP1251 и сопутствующие файлы (.sig, .eps).
--no-fields— выключает поля и топологию, в том числе у авторских заданий раздела «Уроки»: проверочный прогон с ними идёт десятки минут вместо секунд.id ...— выгрузить только перечисленные образцы.--set ключ=значение— подменить параметр рецепта числом (чтобы прогоном ядра проверить ветку, которая включается выбором, например способ расчёта у ПЗФ). Если у образца нет такого параметра, печатается замечание.
Рядом пишется manifest.txt — строка на образец:
id h|x имя.tpl s-файлы... | постановка словами | тег=имя;;тег=имя. По нему скрипт
bake_samples.py гоняет ядра и собирает числа паспортов.
Код 1 — хотя бы у одного образца ошибка проверки, потеря символов CP1251 или сбой записи: каждый рецепт при умолчаниях обязан быть чистым. Порядок обновления паспортов (каталог образцов):
sample_gen <папка> --no-fields
python tools/bake_samples.py run <папка>
python tools/bake_samples.py cpp <папка> src/core/samples/baked.cpp
sig_gen — задания с падающей волной из файла
sig_gen <папка> [--forms] [--pipeline] [--macro] [--ref]
Доказывает прогоном ядра H, что генератор выпускает считаемый файл для каждой
формы сигнала. Устройство во всех заданиях одно — волновод 60 мм со вставкой eps = 2
длиной 60 мм (область 200 x 84 мм, DELTA 1 мм, TIME 40 нс), как в эталоне
samples/MULTIFREQ/wg_wide.tpl пакета, чтобы числа сравнивались с уже сверенным
результатом. Без ключей выполняются все наборы:
| Ключ | Задания | Что проверяет |
|---|---|---|
--forms |
sig_multi, sig_chirp, sig_burst, sig_grf, sig_gvid, sig_mono, sig_trap, sig_saw, sig_tri, sig_sq, sig_expr, sig_tab |
каждая из 12 форм; FREQ — частота согласования, подсказанная формой (suggestedFreq) |
--pipeline |
pipe_001...pipe_004 + пакетные файлы |
конвейер: 40 частот 3.00...4.95 ГГц по 10 в задании |
--macro |
mac.tpl + mac_step.h |
имя файла в квадратных скобках внутри тела макроса — препроцессор ядра |
--ref |
ref |
эталонный свип по 10 частотам 3.0...4.8 ГГц для сверки |
Для каждой формы печатается число точек и шаг .sig (sigPlan). Подробнее о формате
и правилах — раздел падающая волна из файла.
gen_lr2 — проверочные задания эмиттера
gen_lr2 [папка]
Собирает на модели Project набор заданий и пишет их в CP1251 (по умолчанию — в
текущую папку). Каждый проект проходит validate(); на первой ошибке программа
останавливается с кодом 1.
| Задание | Содержание |
|---|---|
wg_p1, wg_p2 |
ЛР2: пустой волновод (ядро X, 4 ГГц), активен вход 1 / вход 2; общий wg.s даёт полную матрицу 2 x 2 |
pl_p1, pl_p2 |
то же с замагниченной плазмой: N = 3.1e17 м^-3, B = 0.071 Тл |
sweep |
свип 3.0...5.0 ГГц (21 точка) — макро-версия |
wide |
свип 1.0...5.0 ГГц (41 точка); нижняя часть ниже отсечки H10 — проверка обязана предупредить, но не запретить |
pulse |
гауссов импульс на входе (центр 20 нс, длительность 5 нс) |
edges |
волновод одним прямоугольником без торцевых сторон и диафрагма-ломаная (ядро H) |
ultra |
2 варианта геометрии x 2 возбуждения = 4 шага в одном файле |
plshapes |
плазма кругом (N + B) и прямоугольником (N + Y) |
tpl_dump — что понял парсер
tpl_dump <файл.tpl> [--expanded] [--reemit [папка]]
Читает задание тем же readTplFile, что команда «Открыть готовое», и печатает модель:
имя, ядро, версию (обычная или макро), подключённые файлы, область, DELTA, TIME,
частоты, фигуры (материал, eps или профиль, плазма, движение, геометрия), порты,
очередь возбуждений, варианты, вывод. Затем — то, что прочитано не полностью, и
ошибки и предупреждения validate() прочитанной модели.
--expanded— дополнительно текст после препроцессора (раскрытые#includeи макросы): видно, во что развернулось задание.--reemit— выдать прочитанную модель эмиттером обратно: без папки — текст.tplв stdout, с папкой — файлы<имя>.tpl(и<имя>_step.h) в CP1251. Так глазами проверяется круговорот «прочитал — записал».
Код 1 — только ошибки чтения (или записи при --reemit); замечания и ошибки проверки
модели код не меняют.
gui_shot — снимки и самопроверки интерфейса
gui_shot <файл.png> [ширина=1400] [высота=880] [режим] [ключи]
Собирается из исходников src/gui (с теми же стилями и защитой колеса мыши, что
программа), открывает окна настоящим кодом приложения и либо снимает их в PNG, либо
проходит сценарий настоящими событиями мыши и клавиатуры, печатая строки ok /
ПРОВАЛ. Режим определяется наличием слова среди аргументов.
Снимки одного окна:
| Режим | Окно |
|---|---|
issues <файл.tpl> |
замечания по прочитанному заданию |
calc, settings |
калькулятор, настройки |
files [eps\|table] [full] |
мастерская вспомогательных файлов |
port [форма] [filled] [preview] [full] |
окно порта; формы multi ... tab, filled — вход в диэлектрике eps = 4, preview — только график сигнала |
shape [epsfile] [plasma] |
свойства фигуры |
| без режима | главное окно; четвёртый аргумент — start, samples [раздел] [id] или номер раздела 0...4; ключи demo, open <tpl>, reset, hover <x мм> <y мм>, arc, full |
Самопроверки:
| Режим | Что проходит |
|---|---|
selftest |
холст: дуга, приоритет выделенной фигуры, сшивание, выбор нескольких фигур, групповые команды |
samplescheck |
библиотека образцов: карточки, параметры и «Вернуть умолчания», открытие в мастере, «Мои образцы» (во временной папке через TPLD_USER_SAMPLES), поиск, поворот объекта с одним портом |
filescheck |
мастерская файлов: таблица из формы, круговорот «записал — прочитал» для .sig и .eps |
wheelcheck |
колесо над полем без фокуса не меняет значение, а листает страницу |
limitscheck |
потолок 99 частот, ссылки «Взять шаг» и «разложить», память ДН, диаграмма памяти |
import3d <модель> [XY\|YZ\|XZ] [мм] |
импорт среза 3D-модели, четыре снимка шагов |
sigexample |
гребёнка 1...100 ГГц для руководства, пять снимков |
tutorial [movie] |
первый аргумент — папка; проход «Пошагового примера» с кадрами NN_<имя>.png, с movie — непрерывная серия для видео |
Вместе со снимком в stdout печатаются строки REGION<TAB>ключ<TAB>x<TAB>y<TAB>w<TAB>h —
карта областей окна. По ней tools/make_guide_shots.py ставит рамки с номерами на
иллюстрациях руководства, tools/make_guide_video.py склеивает кадры tutorial movie
в видео. Код 1 — снимок не сохранён или есть провалы сценария.
⚠️ Утилита находит виджеты по objectName и тексту кнопок (legend, mergeShapes,
freqRange, shapeXMin, sampleOpen, «Взять из формы», «Вернуть умолчания» и др.):
переименование в src/gui ломает проверку с сообщением «не найдено» (см.
подводные камни интерфейса). Запускать на обычном рабочем столе: с
-platform offscreen шрифты Windows не поднимаются и текст выходит квадратами.
make_models — тестовые 3D-модели
make_models <папка>
make_models --kernel-check <папка>
Моделей у проекта нет — их рисует код, поэтому срез каждой известен заранее. Первый
режим пишет набор в data/models (его читают тесты импорта через TPLD_MODELS_DIR),
все размеры в мм:
| Файл | Формат | Модель |
|---|---|---|
waveguide_iris.stl |
STL текстом | волновод 60 x 30 мм длиной 200 мм, индуктивная диафрагма (окно 20 мм), невыпуклая вставка PTFE (буква Г) |
horn.obj + horn.mtl |
OBJ + MTL | секториальный рупор в H-плоскости |
patch.obj + patch.mtl |
OBJ + MTL | патч-антенна: земля, подложка FR-4, патч, линия питания |
tokamak.stl |
STL текстом | камера токамака (тор-оболочка), соленоид, катушка PF1; 96 сегментов |
tokamak_fine_binary.stl |
двоичный STL | то же, 360 сегментов; имён тел формат не хранит |
waveguide_iris.step, waveguide_iris_in_meters.step, tokamak.step |
STEP | только в сборке с OpenCASCADE (make_models_step.cpp): имена, цвета и материалы тел; второй файл — в метрах, после чтения обязан совпасть с миллиметровым |
Режим --kernel-check пишет четыре задания split_rect, split_poly, split_horiz,
split_diag: одна и та же вставка eps 2.1 в волноводе — целая и разрезанная на
выпуклые куски. Импорт режет невыпуклое сечение, и на общем крае два блока ложатся в
одни узлы; прогон ядром показывает, складывает ли ядро веса узлов (разрез невидим)
или затирает их (на крае выйдет другая среда). См. импорт 3D-моделей.
make_icon — значок программы
make_icon <out.ico>
make_icon --icns <out.icns>
make_icon --png <папка>
Значок рисуется кодом, а не хранится картинкой: мелкие размеры (16 и 20 пикселей) требуют своей толщины линий, а палитра обязана совпадать с палитрой окна. Все три формата получают один рисунок (подложка, сетка, стенки волновода, волна, точки портов; сетка — от 48 пикселей, точки — от 32):
- ICO — 16, 20, 24, 32, 40, 48, 64, 128, 256 пикселей, кладётся в
src/gui/resources/app.ico; - ICNS — десять изображений 16...1024 пикселя с retina-вариантами, для пакета
.app; - PNG —
tpl-designer-<N>.pngдля темы hicolor Linux, N = 16...512.
Контейнеры ICO и ICNS собираются вручную: плагины Qt для их записи есть не во всех сборках.
make_pdf — HTML в PDF
make_pdf <вход.html> <выход.pdf> [заголовок]
Печатает HTML (UTF-8) с картинками в PDF A4 через QTextDocument и QPdfWriter (поля
14/12 мм, 150 точек на дюйм) — без внешних конвертеров. QTextDocument понимает только
подмножество HTML и CSS, поэтому разметку готовит tools/make_guide_pdf.py: он
разворачивает Markdown руководства в простые теги и задаёт ширину картинок в пикселях.
Без дисплея — с QT_QPA_PLATFORM=offscreen.
Скрипты Python
| Скрипт | Назначение |
|---|---|
bake_samples.py |
run <папка> — прогоняет ядрами задания из sample_gen (перед прогоном удаляет целевые .s) и пишет results.json; cpp — собирает src/core/samples/baked.cpp; show, recpp — просмотр и пересборка без ядер |
check_physics.py |
инварианты по results.json: баланс мощности по столбцу S-матрицы, |Sij| <= 1, ожидаемое поведение по типу задачи |
check_theory.py |
сверка чисел ядра с независимо написанными формулами учебников |
make_guide_shots.py, make_guide_pdf.py, make_guide_video.py |
снимки руководства с рамками (через gui_shot), PDF (через make_pdf), видео и GIF прохода |
toolchain-osxcross.cmake |
файл кросс-сборки для macOS на Linux (вызывается из scripts/build-macos-dmg.sh) |
TPL Designer task editor
Purpose and place in the package
TPL Designer is a graphical editor of .tpl task files for the package's compute kernels:
planarrt_h (H-polarization) and planarrt_x (E-polarization with magnetized plasma).
The user draws the geometry with the mouse and fills in the fields for ports, signals and output, and
the program writes a task file that the kernel is guaranteed to accept and to compute exactly as
drawn. The .tpl language (text with a C-style preprocessor) is full of traps: the file holds
the increment eps-1, not eps itself; INPUT_X is a port with its aperture along the Y axis; a line continuation
in a macro is exactly two backslashes; the kernel's evaluator does not understand exponents. Each
such trap is closed by the generator code, and whatever cannot be closed by code is caught by validation
before the file is written.
Place in the package pipeline (see the theory overview):
TPL Designer (drawing, fields) ← this module
│ validate() → emitMono / emitMacro / emitChunks → writeTask (CP1251, CRLF)
▼
<name>.tpl [+ <name>_step.h, .sig, .eps, batch files]
│ prepr preprocessor → TMCIndan parser
▼
kernel planarrt_h / planarrt_x → .s, .t, .tt, fields, RP → viewers
The reverse path exists as well: readTplFile opens a ready task file — its own or one
written by hand — and returns it to the editor model.
The full reference of the task language is the user manual
docs/user-manual/tpl-guide.md (in the package root). The kernel preprocessor is described on the page of the
prepr library, the kernel's task parsing on the page of the
TMCIndan library, and the file formats on the
file formats page.
Subproject architecture
The subproject lives in src/tpl_designer and consists of two layers with a strict boundary:
| Layer | Directory | Depends on | Role |
|---|---|---|---|
| Generator core | src/core (static library tpl_core) |
Qt6::Core only (+ OpenCASCADE for STEP) | task model, validation, emitter, .tpl reading, grid and placement, 3D import, .eps and .sig files, memory estimate, CP1251, translation, sample catalogue |
| User interface | src/gui |
tpl_core, Qt6::Widgets |
wizard, canvas, dialogs, sample library, kernel launching |
| Tests and utilities | tests, tools |
tpl_core |
unit tests of the core, sample export, window snapshots |
The boundary is enforced in src/core/CMakeLists.txt: Qt6::Widgets must not be linked to the core.
Hence all the generation logic is tested without opening any windows, and the user interface only
assembles a Project and calls the core functions. The link with the package's kernels is purely file-based:
the editor links nothing from the computational libraries; it writes text and launches the kernels
as separate processes.
All functions of the generator core are pure: they take the model by reference and return values (text, a list of diagnostics, an estimate). There is no shared mutable data except the translation tables and the sample catalogue, which are built for the current language (see translation).
Core contents
| File | Role |
|---|---|
project.h/.cpp |
the task model Project and its helpers: units, rectangle sides, point coverage by a shape, port rules, sweep |
emitter.h/.cpp |
validate, mono task, macro version, angular sweep, pipeline; writing numbers without an exponent |
tplreader.h/.cpp |
a preprocessor following the kernel's rules and reading a .tpl back into the model |
taskfiles.h/.cpp |
writeTask — the only path for writing a task file to disk; names of accompanying files |
expr.h/.cpp |
the expression evaluator ExprProgram (formulas for eps, signals, coordinates) |
placement.h/.cpp |
checks of shape placement on the grid, pickup windows, the RP contour, the B rectangle |
physics.h |
reference formulas: cutoffs, plasma and cyclotron frequencies |
sigfile.h/.cpp |
incident-wave waveforms, the .sig file, signal band and support |
epsfile.h/.cpp |
writing and reading the .eps distribution file |
ramestimate.h/.cpp |
estimate of the kernel's RAM usage |
cp1251.h/.cpp |
CP1251 encoding and reading of task text files |
lang.h/.cpp |
language selection and the translation function tpl::tr |
mesh3d, meshio, meshslice, convexsplit, meshgen, meshimport, materialmap |
3D model import: reading STL/OBJ, slicing with a plane, convex decomposition, conversion into shapes |
stepio.h, stepio_occt.cpp, stepio_none.cpp |
reading STEP via OpenCASCADE; a stub for builds without it |
samples/* |
catalogue of sample tasks: recipes, tables of standards, data sheets |
Task model
The model is described in project.h and stores what the person enters, not what is written to
the file. Converting it to the rules of the language is the emitter's job.
Project
├─ name, description, kernel (H | X), unit (input unit; the file always uses mm)
├─ box (computational region, mm), delta (grid step, mm), timeMax (end of computation, ns)
├─ freqs (GHz; one — mono task, more — macro version)
├─ shapes[] Shape: id, name, kind (Rectangle | Circle | Polygon | Polyline),
│ material (Metal | Magnetic | Absorber | Dielectric), eps,
│ edges[4] (rectangle sides), epsProfile, plasma, velocity
├─ ports[] Port: id, side, from..to (aperture), plane, active, mode (H10 | Plane),
│ signal (formula or .sig file), eps / epsAuto (medium in the port cross-section)
├─ output OutputSettings: signal file, topology, fields, SMATRIX, RP, /Time
├─ variants[] geometry variants (disabled shapes), exciters[] excitation queue
├─ sweep AngleSweep: step-by-step rotation of the object
└─ chunking Chunking: splitting the frequency grid across several task files
The main conventions of the model:
- eps itself, not the increment.
Shape::eps,Port::epsand the formulaEpsProfile::formulahold eps; the emitter writeseps-1in exactly one place for each case (fillExpression,epsProfileLines,portLine). - Absolute scene coordinates, mm. The decomposition into "local coordinates +
#LINK_LISTanchor" is done by the emitter. The exception is the circle: aCIRCLE_STATblock has no centre, and the anchor serves as the centre. - A material is a contour, an expression is a region. The kernel applies
Metal,Magnetic,Absorberonly to the perimeter; dielectric, eps profile and plasma are fills (Shape::isContour). - Plasma is one shape with several quantities. N (m^-3), B (T), Y (grid
losses) and sigma (S/m) are separate blocks
*_STAT_N/_B/_Y/_Swith the same geometry in the language; in the model they are fields of onePlasma. Each quantity can be a number, a formula of the coordinates or a file (FILE_N/_B/_Y). See the plasma model and units. - A port sets a direction, not a boundary.
PortSidesays where the incident wave will travel; the port plane may lie inside the region (Port::plane). The kernel derives the direction from the half of the region in which the plane lies (directionForPlane). - By default the port medium is the medium under the port.
Port::epsAuto(on by default): the port eps is taken from the dielectric shape covering the middle of the aperture (portMediumEps); see the W parameter of a port. - Block numbers are shared between shapes and ports; they are arbitrary, but unique and at least 1
(
Project::nextFreeId).
Number of task steps (Project::stepCount): variants x excitations x frequencies; with an angular
sweep — a reference step plus one step per angle. Number of pipeline files — Project::chunkCount.
The "project → validation → emitter → files" pipeline
Project
│ validate(p) → Diagnostics { errors, warnings }
│ errors not empty → writing is forbidden, the list is shown to the person
▼
emitChunks(p) → QVector<TaskChunk> (without a pipeline — one element)
│ for each part: needsMacro ? emitMacro : emitMono
▼
writeTask(...) → <name>.tpl, <name>_step.h (CP1251, CRLF),
.sig, .eps files, batch files <name>_run.bat/.sh
There is one validation rule: an error is only what the kernel will reject or silently compute differently from what is drawn; everything else is a warning that does not prevent writing. The generator must save any task file that the kernel computes.
Only writeTask writes a task file to disk — it is used by the wizard, the sample
library, "My samples" and the service utilities. A separate "side" write in one of those places once
produced a task file without its .sig file, so there is no other path. More details in the section
writing files.
Task validation
validate(const Project&) checks the task in the following order (diagnostic texts are in the
interface language):
- The task as a whole. The name is set and contains no dot; there are frequencies;
DELTA > 0,TIME > 0, the region is not empty. More than 99 frequencies in one task without a pipeline is an error (kMaxFreqs: the limit of.s, of RP tones and of post-processing, see multi-frequency computation); more than 20 ports is a warning. For a multi-frequency RP — a window that is not a multiple of 1/df between the tones (tone leakage), and a memory estimate of 2 GB or more (see memory estimate). - File names for signals, S-matrix and RP: set, without a dot (the kernel appends the extension itself).
- Block numbers: at least 1 and no duplicates.
- Shapes. A polyline has at least two points and is not a fill; a contour has at least three
points; a filled polygon has more than three vertices, a non-convex one gives a warning (the kernel
does not check convexity, and the field will be wrong); for a circle
rMax > rMin, for a sector the end angle is greater than the start angle; a rectangle has positive dimensions and at least one side; a shape entirely outside the region gives a warning. Plasma: X kernel only; not on a moving block; file names of the quantities without a dot and in Latin characters; N <= 0 gives a warning (the plasma branch will not be enabled); B without an overlapping N gives a warning (the magnetization will be lost). eps profile: the formula parses and yields a number at the check points (epsSamplePoints), the file name has no dot and is in Latin characters, not on a moving shape, not together with plasma. - Ports. The aperture is non-zero; the port eps is strictly greater than zero — otherwise the kernel
rejects the file (
eps = W + 1 <= 0); the port plane is inside the region and in the same half as the direction (otherwise the kernel silently reverses the wave); an aperture closer than2*DELTAto the edge gives a warning (the kernel will shrink it); the window of a passive port does not extend beyond the computation. A port with a signal from a file is checked bycheckFileSignal(see incident wave from a file). - Wide band. Two ports do not write their wave to the same file; the matching frequency
(
FREQ) is near the signal band; plasma with a wideband signal gives a warning (the X kernel computes the plasma increment once, fromFREQ). - Pipeline, variants, excitations. From 1 to 99 frequencies per part; a pipeline is
incompatible with an angular sweep; variants have unique file labels without a dot,
the disabled shapes exist; two profiles do not write the same
.eps; the ports of the excitation queue exist and are not repeated; the S-matrix window is not beyond the end of the computation. - Angular sweep (see below).
- Placement on the grid —
checkPlacement(see placement). - Description without characters outside CP1251.
- Warnings at the end: no active port; several active ports
while taking
.s(this is no longer a scattering matrix); an incomplete excitation queue (S columns will remain empty); more than 60 steps (time estimate); fields at every sweep step.
The following are deliberately not checked: single-mode operation of a single-frequency port, the opacity band of the plasma, negative eps outside the port, the "pulse shape": these are not errors of the task but its physics, and such checks would declare working task files erroneous. The H10/H20 cutoffs are checked only for a wideband port with a signal from a file: there post-processing restores the matrix under a single-mode assumption, and above the H20 cutoff the result would be silently wrong.
Emitter: mono task
emitMono(p) writes a single file in which every #STEP is written out explicitly. The steps go through
the "variant x excitation" combinations (combos), and within each — through the frequencies. A step is built by
stepLines:
#STEP
#PARM
ANGLE_UNIT radian; FREQ_UNIT GHz; LONG_UNIT mm; TIME_UNIT ns;
DELTA …; TIME 0.; …; X_MIN …; X_MAX …; Y_MIN …; Y_MAX …; FREQ …;
#END_PARM
#TOPOLOGY
BLOCK n; ! name — explanation
<block body>
END_B
…
#END_TOPOLOGY
#LINK_LIST
T n; X0; Y0;
…
#END_LINK
#OUTPUT
FILE <signals>; [TOPOLOGY;] [FIELDS;]
[SMATRIX <file>; <FREQ>; Tmin; Tmax;] [FIELD_DISTRIBUTION_M <file>; <FREQ>; Tmin; Tmax;]
#END_OUTPUT
#END_STEP
How the language rules are handled:
| Language rule / trap | Where it is handled |
|---|---|
The header is always #TMC_RT_H (there is no #TMC_RT_X tag); #EOF is mandatory |
header, end of emitMono/emitMacro |
The units in #PARM are always the same: radians, GHz, mm, ns |
stepLines |
The #TOPOLOGY blocks and the T lines of #LINK_LIST never diverge |
both are built from the same list buildBlocks |
The file receives the increment eps-1; for a profile — (formula)-1 in parentheses (substitution is textual) |
fillExpression, epsProfileLines |
| Rectangle and polygon — absolute coordinates with the anchor (0;0); circle — centre at the anchor | shapeAnchor |
| Different sides of a rectangle cannot be expressed by one block | edgeLines: one polyline per side, free block numbers |
The kernel does not load a POLYGON_STAT with fewer than three L lines |
padToThreePoints: midpoint of the segment |
| A closed material contour is closed by repeating the first point; a fill is traversed clockwise | polygonPoints |
Plasma — up to four blocks _N/_B/_Y/_S with the same geometry; B — a rectangle wider than the plasma by kBMarginCells steps (or exactly matching the plasma with bExact) |
buildBlocks, plasmaBRect |
eps profile: [name] is written only at the first step where the shape appears; a .eps file — only for a rectangle |
epsProfileShapes, createEps |
| Port: 8 parameters, Faza is mandatory with Amp, the eighth is the increment eps-1 of the port medium (vacuum is not written) | portLine, portEps |
| Passive port: window [2TIME; 3TIME] and Amp = 0 | portWindow, portLine |
| The port plane is the port anchor | portAnchor |
Signal from a file — [name] in place of Amp, with no space before the bracket |
portLine |
The SMATRIX label is the step frequency; the window is mandatory, except for a multi-frequency step |
stepLines, stepIsWideband |
RP — only FIELD_DISTRIBUTION_M |
stepLines |
| Numbers never contain an exponent | formatNumber, formatCompact, plainDecimal, plainLiterals |
| The kernel name in the header has no extension — the file is identical on all systems | header |
Numbers. formatCompact writes up to 10 significant digits (six were not enough for the "open —
save" round trip: coordinates drifted) and never in exponential form: 3.1e17 is written as
310000000000000000. formatNumber appends .0 to integers; formatFreq writes
the frequency with one decimal place if it is a multiple of 0.1 GHz, otherwise with all the digits needed.
plainLiterals rewrites numbers with an exponent inside user formulas.
Names of a step's output files. The signal file gets suffixes for the variant (_<tag>),
the excitation (_p<number>) and, with several frequencies, the frequency (_f3p9): a step has
one name, but there are many steps, and without a label each next step would overwrite the previous step's .t.
The S-matrix file is shared by all excitations of one variant (the steps append their
columns to it) and differs between variants. The task header lists all the .s files that
must be deleted before a run: the kernel appends to them rather than overwriting them.
The eps profile is computed once. The step at which the shape with a profile first appears
writes [name] and creates the .eps; the remaining steps write only the formula (the file is
frequency-independent; the kernel applies the frequency coefficient itself).
Emitter: macro version
With several frequencies (or an angular sweep) needsMacro returns true, and
emitMacro writes two files: <name>.tpl and <name>_step.h. The step is described once —
as a macro with parameters, and the number of steps equals the number of invocation lines; the steps
cannot get out of sync.
! <name>_step.h
#define wgstep Freq__; Tfile__; Sfile__; @\\
#STEP\\
#PARM\\
…\\
FREQ Freq__;\\
…\\
BLOCK 1;\\ ! waveguide: bottom wall
…\\
#END_STEP
! <name>.tpl
#TMC_RT_H
! …header…
#include <name>_step.h
wgstep 3.0; wg_f3; wg;
wgstep 3.2; wg_f3p2; wg;
…
#EOF
Macro parameters: Freq__ (frequency), Tfile__ (signal file), Sfile__ (when
taking the S-matrix), Dfile__ (for the RP). Each "variant x excitation" combination gets
its own macro (<name>step1, <name>step2, …; the name is at most 32 characters long), because
their topologies differ.
Preprocessor rules handled by macroText (see
line continuation and #define):
- a continuation is exactly two backslashes
\\at the end of every line except the last; the last line has no continuation — this marks the end of the macro; - the block label (
! name) is placed after the continuation: the preprocessor strips!first, and a comment before\\would take the continuation away with it; #includecomes before the invocations; the include file lies next to the.tpl(the kernel looks for it only in the task folder).
What must happen exactly once (fields only at the first step, saving the eps profile) cannot be expressed in the macro body — there is no "first step" inside a macro. Such a step is written explicitly before the invocations of its combination, and the corresponding invocation line is skipped.
Task pipeline over frequencies
The package fits at most 99 frequencies into one .s file. A denser grid is split by
emitChunks: with Project::chunking the task is split into parts of
freqsPerTask frequencies — <name>_001, <name>_002, … (the number width depends on the number of parts,
so that the files sort in order). Each part has its own names for the signal, .s and RP files (with
the same _001 suffix): .s is appended to, so the common points of different parts would get mixed,
and in a batch run the file would be corrupted by simultaneous writes. The incident-wave
file .sig, on the contrary, is shared — its name is fixed by the original task. The description of each
part is extended with the frequencies it computes. Without a pipeline emitChunks returns
a single task — the caller needs no branching.
A wideband signal from a file does not replace the pipeline: in plasma the X kernel computes
the plasma increment once, from FREQ, and for a wide band in plasma the correct path is
precisely a batch of task files (see multi-frequency computation).
Angular sweep
The language does not allow rotating the source: there are two kinds of ports, and a plane wave travels only
along the axes. Therefore, for scattering at different angles, the object is rotated
(AngleSweep): the selected shapes are rotated from step to step about the axis
sweepPivot (by default — the centre of the object's bounding box; the axis moves with it).
- The coordinates of the rotated shapes are written as expressions of the angle:
x' = cx + dx*cos(a) - dy*sin(a),y' = cy + dx*sin(a) + dy*cos(a), wherea = Ang__*0.0174532925199433(rotX,rotY). The kernel evaluatescos/sinin theLcoordinates and in theTanchors, so the step is described once by the macro<name>rot Ang__; Tfile__; …. - When rotated, a rectangle becomes a polygon of four corners; for a circle the centre (anchor) and the sector opening are rotated.
- The reference step (
referenceStep) is the same scene without the object, written to files with the_refsuffix. - Each angle has its own
.sfile (<name>_a30.s,sweepSFile), labelled with the frequencyFREQ: the kernel does not allow labelling a point of a single-frequencySMATRIXwith anything but the frequency. The angle labelsa30,a12p5,am15(sweepFileTag) contain no dot. - The single port of the queue or the ports with the "active" flag are excited
(
sweepExciter).
The task header carries the service line
! @TPLD-SWEEP blocks=…; pivot=x,y; angles=…; ref=0|1 (sweepHeader). For the kernel it is a
comment, while reading uses it to rotate the shapes back and reassemble the sweep.
Validation forbids (errors): a sweep without shapes or angles; several frequencies; combining it with
variants, a queue of several ports or a pipeline; a repeated angle (two steps to one
file); an eps profile and plasma given by a formula on a rotated shape (the formula's coordinates
would have to be rotated inside someone else's expression); B and Y other than as an axis-aligned rectangle;
moving blocks. A rotated shape leaving the region gives a warning.
For a sweep emitMono writes all steps explicitly (emitSweepMono), emitMacro — as a macro
(emitSweepMacro).
Reading a .tpl
readTplFile(path) / readTplText(text, baseDir) return a ReadResult: the model,
warnings, errors, the macro-version flag, the names of included files and the text after
preprocessing (the same text the kernel puts into <name>.tpl~$Prepr$~). The file encoding
is detected automatically (CP1251 or UTF-8).
Reading is "lenient": whatever the model cannot express is not silently lost but goes into
the warnings with the line number of the original file. An error occurs only when there is nothing
to parse (no #TMC_RT_H, not a single #STEP).
The preprocessor (preprocess) reproduces the prepr library according to its code,
not according to the reference:
!is stripped first, up to the end of the line (which is why!before\\kills the continuation);\\and everything after it up to the end of the line are discarded, and the line is joined with the next one;#includeinserts a file from the task folder (the name is looked up case-insensitively: task files are written on Windows but may be read on Linux and macOS); after each insertion the joining is repeated; at most 64 insertions;#define NAME [par1; par2;] @ bodyare expanded from the last to the first, each one only below its own position; substitution works on whole identifiers[A-Za-z0-9_]; the outer parentheses of an actual parameter are replaced with spaces; the name length and the number of parameters are unlimited. A#defineline is replaced with an empty one — so line numbers in warnings remain the real ones.
Parsing (parseSteps) cuts the flat text into steps and the sections #PARM, #TOPOLOGY,
#LINK_LIST, #OUTPUT. Missing #PARM fields are inherited from the previous step,
as in the kernel; quantities are immediately converted to mm, ns and GHz according to LONG_UNIT, TIME_UNIT,
FREQ_UNIT. Keywords are compared together with the delimiter (TIME_UNIT does not match
TIME), and primitives by a table ordered from longest to shortest (RECT_STAT_N before
RECT_STAT).
Model assembly (buildStep, then readTplText):
- local coordinates + anchor → scene coordinates; increment eps-1 → eps; formula
(X)-1→X; formulas from a file in cm or m are converted to mm; - an extra segment vertex (padding to three points by repetition or by a midpoint) is removed
silently (
dropPaddingPoints); a contour that repeats its first point becomes a closed polygon, without the repetition — a polyline; - plasma blocks of one region are merged into one shape (
mergePlasmaInto); a B block wider than the plasma by at mostkBMarginCellssteps is also considered "the same shape", and one that coincides with the plasma setsPlasma::bExact; - an anchor of an eps profile or plasma that does not coincide with the shape's centre is preserved
(
customOrigin): otherwise the medium would shift on saving; - port: the mode from the first parameter, the direction from the half of the region, the plane from
the anchor; the signal is recognized by the form of Amp (Gaussian — by the expression, file — by
[name], in which case the waveform is restored from the@TPLD-SIGservice line of the.sigfile, and a foreign file is taken as a table); a passive port — a window later than the end of the computation or a zero Amp; the eighth parameter is the eps increment of the port medium; - identical shapes and ports of different steps are merged by keys (
shapeKey,portKey); differing steps are restored as frequencies, an excitation queue and geometry variants; the rotated object of a sweep is rotated back using the service line; - shape names are taken from the comments
BLOCK n; ! name — explanationof the original text (and of the include files), variant names from the comments! variant: …, the description from the header "Task generated by TPL Designer". Both languages are recognized whatever the current one is; - at the end — a cross-check: how many steps writing the model back would produce. A mismatch means that the model cannot express some of the differences between the steps, and a warning says so.
Expressions
Formulas occur everywhere in a task: eps profile and plasma quantities as functions of the coordinates,
the signal waveform a(t), coordinates when reading foreign files. They are evaluated by the editor's own
evaluator ExprProgram (expr.h/.cpp) — the same language as the kernel's evaluator:
- recursive-descent parsing into a tree (
compile— once,eval— as many times as needed); a formula must not be parsed in a loop over the nodes — that is what the compiled program is for; - spaces inside an expression are removed entirely (
6 . 3is a legal way to write a number); - the operators
+ - * /, the power^(right-associative), the functionsabs exp log log10 sqrt sin cos tan sinh cosh tanh asin acos atanin lower case followed by a parenthesis;ANGLE_UNITapplies to trigonometry; - intermediate
infandNaNare allowed (as in C:x/exp(500)gives a legitimate zero); only a non-numeric final result is rejected; evalEps(x, y)— a fast path for medium formulas: substitutesx,y,r = sqrt(x^2+y^2)andf = atan2(y, x). ⚠️fin a medium formula is the polar angle, not the frequency: this is how the kernel substitutes it;scaleCoordinatesrewritesx,y,ras(x*k)— this is how formulas from files in cm or m are converted to mm.
Limits: tree depth 4000, parenthesis nesting 1000.
⚠️ Old builds of the kernel's evaluator do not understand exponential notation (1e17):
"1" is a number, and e17 is an unknown function. The emitter never writes it (see
emitter).
Geometry and grid
The language knows three area primitives: an axis-aligned rectangle, a circle (ring, sector) and a
polygon. There are no curves — the editor breaks arcs and circles drawn as lines into polylines with
a step of the order of DELTA. Everything the kernel fills must be convex: the kernel builds the fill
of a polygon as a fan from the first vertex, and a non-convex region silently produces a wrong
field. Therefore the editor cuts an arbitrary region (for example, a cross-section of a 3D model) into
convex pieces (convexPieces, convexsplit.h):
- the region is cut into vertical strips at the abscissas of all vertices;
- in each strip, the edges crossing it are sorted from bottom to top and pairwise form trapezoids;
- a trapezoid is merged with the piece to its left if their common edge coincides and convexity is preserved;
- a triangle gets the midpoint of its longest side added (
padTriangle): a filled polygon must have more than three vertices.
Walls (metal, magnetic wall, absorber) are contours: a closed contour is
written with the first point repeated, a polyline as it is, but with at least three
points. The kernel places the grid nodes with step DELTA from the region boundaries; for how to
position blocks relative to the nodes, see the grid rules.
Placement on the grid
checkPlacement (placement.h/.cpp) is called from validate and checks what the
kernel will compute differently from what is drawn:
- a shape extends beyond the region by more than half a step — warning (the kernel will discard the protruding part);
- a magnetic wall or absorber as a circle or a polygon no larger than
2*DELTA— warning (the wall is thinner than a cell); - plasma (X kernel): the boundary of the B block cuts the plasma; an edge resonance within the computation band
(±2 %) — the upper-hybrid frequency of the edge layer
sqrt(fp^2/2 + fce^2)for a wide B block andsqrt(fp^2/2 + fce^2/4)for B exactly matching the plasma (at the block boundary the kernel halves the values); plasma and eps > 1 at the same nodes; B in a dielectric without N; magnetized plasma next to a magnetic wall; plasma on an absorber; an eps increment within 0.004 of 4 (the kernel shifts it). See plasma frequency, cyclotron frequency, cutoffs and resonances; - S-matrix and RP pickup windows before the steady state — warning; the settling time is estimated from below by the passage of the wave along the diagonal of the region:
- an RP window that the kernel will not close before the end of the computation is an error: the kernel extends the window to a whole number of periods, and when there will be no RP files at all;
- absorber, plasma and port relative to the RP integration contour (10 steps from the edge of the region), see contour in the near zone.
The same file contains two helpers for the emitter and the recipes:
plasmaBRect— the rectangle of the B block: wider than the plasma by two steps on each side (kBMarginCells), clipped to the region; a side is not widened if it would touch another plasma or if the B formula at the edge would stop yielding a number;patternWindowSafeEnd— the end of the RP window no later thanTIME - 1/f_min, rounded down to 0.01 ns and shifted so that the kernel closes the window.
Importing 3D models
The geometry can be taken from a 3D model: the cross-section of a body by a plane is turned into task
shapes (meshio, mesh3d, meshslice, meshimport, materialmap).
STL / OBJ / STEP file ──► Mesh (bodies: triangles, name, material, colour)
weld: vertex welding ──► slicing by a plane ──► closed contours and polylines
──► simplification (Douglas — Peucker) ──► material by name ──► Project shapes
- Reading by extension: a binary STL is recognized by its size
84 + 50*N; in a text STL eachsolid <name>is a separate body; OBJ — a body pero/gobject and perusemtlmaterial, polygonal faces are split into fans, colours are taken from.mtl(Kd). - Vertex welding (
weld) — on a lattice with a step of1e-7of the model diagonal (27 neighbouring cells are checked); degenerate triangles are discarded. - Slicing (
meshslice): a vertex on the plane is considered "above"; a point on an edge is computed in the order of the edge key, so neighbouring triangles get it bit-for-bit identical, and the segments are stitched into chains along shared edges without tolerances. Contour nesting follows the even-odd rule. - Conversion into the task (
buildImportShapes): metal, magnetic wall and absorber become contours (closed or polylines); a dielectric becomes convex pieces (see geometry); an open dielectric contour is not inserted — an explanation says so. Names are cleaned of characters outside CP1251. - Material by name (
materialmap) is guessed with regular expressions from the name of the body or of the material; the first match wins, and the user can reassign it.
meshgen builds test bodies and is used only by the tests and by the
tools/make_models utility.
STEP import
STEP is read via OpenCASCADE (stepio_occt.cpp, interface stepio.h):
- the assembly is traversed with XCAF; names, materials and colours are inherited from parent nodes;
- the result unit is forced to millimetres (
xstep.cascade.unit); - the triangulation tolerance is
1e-3of the model diagonal, but not less than1e-4mm.
Which file goes into the build is decided by src/core/CMakeLists.txt: if
OpenCASCADE is found — stepio_occt.cpp, otherwise the stub stepio_none.cpp, which honestly
answers "this build does not read STEP" (STL and OBJ still work). In the package release
OpenCASCADE is mandatory, and the stub is not included.
Distribution file .eps
An inhomogeneous medium is set by a formula in any shape; the <name>.eps file is written by the kernel itself
for a RECT_STAT [name]expression block (rectangle only), and it is read by a
FILE <name>; x1; x2; y1; y2; block — in that case the kernel does not use the block coordinates; it takes the grid
from the file and positions it by the anchor. The editor can both write such a file itself
(epsFileBytes, following the kernel's writing) and read a foreign one (epsfile.h):
- a text header with CRLF line breaks:
#dDelta,#Xmin,#Ymin— in metres, followed by#nX,#nY,#nPoint,#nAccuracy; - then records "
doublevalue +int32linear index" row by row of the grid,j = iY*nX + iX; - the value is
weight * expression, with node weight 1 inside, 0.5 on an edge, 0.25 at a corner of the rectangle; values are rounded to1e-12so that the file is identical on all systems.
The file is frequency-independent: the kernel applies the frequency coefficient itself at every step.
The file's #dDelta must match the step's DELTA. See
dielectric and stub conductance and
file formats.
Incident wave from a .sig file
By itself the kernel can only do a = Amp(t,f)*sin(2*pi*FREQ*t + Faza(t,f)) — a carrier under
an envelope. Any other waveform (a tone comb, a chirp, a video pulse, a sawtooth, a table of points)
is given by a file: [name] is written in place of Amp, and the <name>.sig file defines the whole a(t)
(see incident wave from a file). The file is written by
sigfile.h/.cpp:
- text, two columns "time in
TIME_UNIT, value"; comments!and#; - the sampling step is half the kernel step
dt = DELTA/(c*sqrt(2))(see time step); at most 400,000 points, otherwise the step is coarsened (validation warns about this); - the interval is the signal support clipped to [0; TIME]; the port window follows it;
- a multitone has the line
#FREQ f1 f2 …(at most 99 tones); the kernel copies it into the.theader, and post-processing takes the tones from there instead of searching the spectrum; - comb: each tone at full amplitude, a smooth ramp-up only over the first 5 % of the burst — the end must not be smoothed: a multitone is processed on the steady-state segment at the end of the computation;
- the
@TPLD-SIGservice line stores the waveform parameters with 17 significant digits — from it reading the task restores the waveform itself rather than a table of points; - the default file name is
<task>_in<N>; the name must not contain a dot (the kernel appends the extension itself only to a name without a dot).
With a signal from a file, FREQ is the port matching frequency; suggestedFreq sets it
to the centre of the band for a comb and a chirp, to the carrier for an RF pulse, and to the repetition frequency for a sawtooth and
a square wave. The kernel computes the SMATRIX of such a step over the whole signal band (see
multi-frequency computation).
Memory estimate
ramEstimate (ramestimate.h/.cpp) estimates the kernel's RAM in advance — so that the
computation does not stop with a memory allocation error after a long grid preparation.
- Nodes: , and likewise .
- Grid: 52 bytes per node for the H kernel, 127 for the X kernel.
- RP over the whole region: bytes per node (
doublenumbers). - RP over strips at the boundary (see boundary strips):
A multitone RP is always computed over strips; a single-frequency one — if the RP over the whole region
would take more than a quarter of the free memory and the grid is at least 32x32 nodes.
* The number of RP tones is limited to 99 (kMaxFreqs).
Validation warns if a multi-frequency RP will need 2 GB or more: this is the limit of a 32-bit kernel.
CP1251 encoding
The kernels read the task file in CP1251, but Qt 6 does not know this encoding: QStringEncoder for
windows-1251 silently returns 0 bytes. Therefore the editor has its own codec (cp1251.h/.cpp):
- writing (
toCp1251): ASCII as is, "А…я" by an offset, everything else by the table of the upper halfkHighTable[128]; look-alike characters are not substituted: everything that is not in CP1251 (Greek letters, arrows, symbols) becomes?and raises thelossyflag. Validation catches such characters in advance — in the task description and in names; - reading (
readTplFileText) detects the encoding by itself: BOM — UTF-8; bytes above 0x7F present and the text valid as UTF-8 — UTF-8; otherwise CP1251; the byte 0x98 (undefined in CP1251) is read as U+FFFD; - the task file is identical on all systems: its own table instead of the system
encoder, line breaks always CRLF, the kernel name in the header without an extension; the write is
atomic, via
QSaveFile.
Only CP1251 characters are allowed in text that goes into a .tpl: instead of ε, λ, →
write eps, lambda, ->.
Translation of the interface and of task files
All texts of the generator core — validation diagnostics, comments and names in the .tpl,
sample titles and data sheets — go through tpl::tr("русский", "English") (lang.h).
The function selects the string by the global language flag on every call, therefore:
- translated text must not be stored in a
static— the language would "freeze" at the first access; tables are built by functions and stored one per language (the sample catalogue, the data sheetbaked.cpp); - the Russian text is unchanged byte for byte: with the Russian language all files are as before;
English strings that go into a
.tplare ASCII only (--instead of—); - reading understands its own files in both languages whatever the current one is: "Задание сгенерировано" / "Task generated", "Ядро:" / "Kernel:", " — " / " -- " in block labels, "вариант" / "variant";
plural()declines numerals: three forms in Russian, two in English.
Shape names are task data and are not translated when the language changes.
Writing the task file to disk
writeTask (taskfiles.h/.cpp) is the only path for writing a task file:
- the pipeline parts (
emitChunks):<name>.tpland, for the macro version,<name>_step.h— in CP1251 with CRLF; - with several parts — the batch files
<name>_run.batand<name>_run.sh; both delete the.sfiles before running each part (the kernel appends to them) and look for the kernel under both names; - the incident-wave files
.sigfor ports with a signal from a file; - accompanying files (sample
companions, for examplelens.eps).
taskFileNames lists the names that will appear — the interface uses them to warn about
overwriting. runFlags gives the kernel launch switches: /Arb or /Arb /Time (the computation
time report is a command-line switch; the task language has no such option, and the .tpl itself does not
change because of it).
Sample catalogue
The sample library (src/core/samples) consists of recipes, not files. A sample
Sample stores an identifier in Latin characters, a section, a title, a line for the tile, a standard,
a help text, the kernel (H or X), a list of parameters Param and a function build: Values -> Build.
A parameter is of one of four kinds — number, integer, choice, check box; all values are passed
as double numbers by key.
Build is the result of a recipe: a ready Project, the "theory" lines of the data sheet (formulas from
rf.cpp), explanations and the accompanying companions files (for example, lens.eps).
How a sample is turned into a task (make(s, v)):
- missing values are taken from the defaults;
- each value is clamped to [min; max];
- integers, choices and check boxes are rounded;
buildis called;- an empty task description is replaced with the sample title.
The task file is written by the same writeTask as in the wizard — together with the companions and the
.sig file. Every recipe with its default values must pass validate() without
errors and without CP1251 losses.
| File | Contents |
|---|---|
sample.h, catalog.cpp |
sample description, a catalogue of five sections (waveguides, antennas, microstrip, media, lessons); the table is built by a function and stored one per language |
kit.h/.cpp |
Builder — task assembly: block numbers from a single counter, shapes, ports, waveguide walls, absorber frame, frequencies, computation time and pickup windows; rules for choosing the grid step |
waveguides.cpp |
9 recipes: H kernel, H10 ports, cross-section according to a standard |
antennas.cpp |
5 recipes: open region with an absorber frame, S11 and RP |
microstrip.cpp, microstrip2.cpp, msplanar.h |
14 recipes on the planar microstrip model (effective width and eps, plane-wave ports with a manually set port eps); two of them with an incident wave from a .sig |
media.cpp |
13 recipes: layer, eps profile, .eps file, Luneburg lens, plasma (X kernel), RCS with geometry variants and an angular sweep |
standards.cpp |
22 EIA/IEC cross-sections (band from the standard), 24 GOST 20900-75 cross-sections (design band 1.25–1.9 fc), 9 substrates |
rf.cpp |
data-sheet formulas: guided wavelength, iris, post, layer, filter prototypes, microstrip, RCS of a cylinder and of a strip |
baked.cpp |
numbers computed by the kernel with the default values; generated by the script tools/bake_samples.py (the cpp command), never edited by hand |
usersamples.h/.cpp |
"My samples": Documents/TPL Designer/Мои образцы/<title>/ with the task file and sample.json |
lessons.cpp, lessons.qrc |
lessons: 7 of the author's task files from a resource, read by the same readTplText |
Builder rules that the recipes rely on:
- the grid step (
chooseDelta) is no larger than lambda/20 and a quarter of the smallest detail, taken from the "round" series 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 8 (times a power of ten); the detail size fits into a whole number of cells (deltaFitting), see the grid rules; - the computation time is rounded up to 5 ns; the S-matrix pickup window is the last 25 % of the computation, but not less than 3 ns; the end of the RP window is trimmed so that the kernel closes it;
- recipes do not enable fields and topology — otherwise test runs take tens of minutes;
- a wall polyline is written with three points (a
POLYGON_STATwith fewer than threeLlines is not loaded).
The baked.cpp data sheet is shown on a card only with the default values
(isDefault): the numbers were computed exactly for them.
⚠️ A Shape& or Port& reference obtained from Builder becomes invalid after
the next addition: the vector reallocates. Recipes first add all ports and
shapes, and then edit them by index.
Pitfalls
- An error forbids writing. Therefore only what the kernel will reject counts as an error; a new diagnostic about "physical meaning" must not be added to the errors — working task files would stop being saved.
.sis appended to. The task header and the batch files name all the.sfiles that must be deleted before a run; without this, old points get mixed in with the new ones.- References into the model's vectors. A
Shape&orPort&must not be held across the addition of the next element:QVectorreallocates. - File names in
src/coremust not coincide with standard headers (the directory is in the include search path; a filesignal.hwould shadow the system<signal.h>). - Line numbers in reading warnings come from the original file: the preprocessor
leaves an empty line in place of
#define. - The letter case of file names (
#include,.sig) is ignored when reading: task files are written on Windows but are read on Linux and macOS as well. - The "write — read" round trip must return the same model: numbers are written with
10 significant digits, segment padding is removed on reading, the formula
(X)-1is parsed back intoX, and the rotated rectangle of a sweep becomes a rectangle again.
User interface
The user interface (src/gui, the executable TplDesigner) is a thin layer over the generator core.
It only assembles the model tpl::Project from the drawing and the fields and calls the core functions:
validation validate, the emitters emitMono / emitMacro / emitChunks, reading
readTplFile, writing writeTask, the memory estimate ramEstimate, the .sig and .eps files,
3D import. The windows know nothing of the .tpl syntax: not a single line of a task file is assembled in
src/gui. There are no platform branches in the user-interface code except two places "for the human" —
the kernel name in a hint (kernelnames.h) and the query of the amount of memory (sysmemory.cpp); they
do not affect the contents of the task file.
Build: src/gui/CMakeLists.txt; the target TplDesigner is linked with tpl_core, the package's common
styling library tmc_ui_base (gui_common: fonts, About dialog,
translation — see common user interface) and Qt6::Widgets. All windows work in
a single thread — the GUI thread; the user interface has no background threads.
User-interface contents
| File | Role |
|---|---|
main.cpp |
entry point: application, settings storage, fonts, language, style sheet, wheel guard, the QMainWindow shell with a short menu and a page stack, re-creation of the pages on a language change, opening a file from the command line |
startwindow.* |
StartWindow — the start window: four cards "Create", "Open", "Take a sample", "Auxiliary files" |
mainwindow.* |
MainWindow — the task wizard: five sections, canvas, validation, undo, reading and writing of the task file |
geometryview.* |
GeometryView — the geometry canvas (QGraphicsView): drawing, selection, snapping, handles, layers, picture mode for samples |
propertypanel.* |
PropertyPanel — the property panel of the selected object next to the canvas |
runplanpage.* |
RunPlanPage — the "What to compute" section: excitation queue, geometry variants, angular sweep |
shapedialog.* |
ShapeDialog — the full form of a shape |
portdialog.* |
PortDialog — the full form of a port: placement, port medium, signal |
signalgallery.*, signalpreview.* |
gallery of signal waveforms and a preview of a(t) with its spectrum |
filemaker.* |
FileMakerDialog — the workshop for the auxiliary files .sig and .eps |
import3ddialog.*, meshview.* |
import of a 3D-model cross-section: the plane selection window and the model view |
samplespage.* |
SamplesPage — the sample library and "My samples" |
calculatordialog.* |
CalculatorDialog — reference calculator for media and waveguides |
issuedialog.* |
IssueDialog — scrollable window of diagnostics, collapseIssues |
memorydonut.*, sysmemory.* |
donut chart of memory and the query of system RAM |
settings.*, settingsdialog.* |
view settings and the settings window |
dtheme.* |
colours and style sheet, fitToScreen |
wheelguard.* |
WheelGuard — the mouse wheel does not change fields that have no focus |
kernelnames.h |
kernel name and launch command on the current system |
app.rc, app.manifest, resources.qrc, resources/ |
.exe icon and Windows manifest, Qt resources (window icon, spin-box arrows), icons for macOS and Linux |
Windows and pages
The program is a single top-level window. main.cpp creates a QMainWindow whose centre
holds a QStackedWidget of three pages:
QMainWindow (menus: "Config" → Language / Язык; "Help" → "About TPL Designer...")
└─ QStackedWidget
├─ StartWindow — start window
├─ MainWindow — task wizard (owns tpl::Project)
└─ SamplesPage — sample library
The menu is deliberately short, as in the other programs of the package: "Config" (language selection —
tmci18n::addLanguageMenu) and "Help" (the single About dialog tmcabout::show from
gui_common). There is no "File" menu: creating and opening a task are handled by the start window and the
wizard, and writing by the "Create task file" button in the "Check" section.
The pages know nothing of each other: each one only emits signals, and the connections are made by
main.cpp.
| Action | Signal | What main.cpp does |
|---|---|---|
| "Create" | StartWindow::createRequested |
if there is work in the wizard (MainWindow::hasContent), asks "Start new / Back to current task"; then resetProject and a switch to the wizard |
| "Open" | StartWindow::openRequested |
a .tpl selection dialog, MainWindow::loadFromFile; on failure it stays on the start page |
| "Take a sample" | StartWindow::samplesRequested |
shows SamplesPage |
| "Auxiliary files" | StartWindow::filesRequested |
a modal FileMakerDialog over the start page (with the wizard's project) |
| "Open sample" | SamplesPage::openRequested(project, companions) |
if there is work in progress, asks for confirmation, then MainWindow::openSample |
| "Back" in the library | SamplesPage::backRequested |
return to the start page |
| "Home" in the wizard | MainWindow::backToStartRequested |
return to the start page; the task in the wizard is kept |
A task file can be passed as the first command-line argument (TplDesigner task.tpl;
an argument starting with - is not treated as a file) — this is how the Linux shortcut
Exec=TplDesigner %f works. The window size is at least 1280x820 and at least what the
layout asks for (minimumSizeHint): with fonts wider than Segoe UI the window would otherwise open narrower than
its contents.
User workflow
- Start. The user chooses "Create", "Open", a sample or an auxiliary file.
- Wizard (
MainWindow). On the left — a tree of five sections, on the right — the page of the section, below it — the list of validation diagnostics, at the bottom "Back" / "Next". The sections are accessible in any order; "Next" simply goes through them one by one:
| No. | Section | Page | What is specified |
|---|---|---|---|
| 1 | Calculation | buildSetupPage |
file name, kernel H or X, ruler units, computational region, DELTA, TIME, a single frequency or a range, task pipeline |
| 2 | Geometry | buildGeometryPage |
shapes and ports on the canvas, properties in the panel, object list |
| 3 | What to compute | RunPlanPage |
excitation queue, geometry variants, angular sweep |
| 4 | Output | buildOutputPage |
signal file, topology, fields, S-matrix and its window, RP and its window, timing |
| 5 | Check | buildSummaryPage |
summary, memory chart, file text, "Create task file", "Save as sample…" |
On the left under the tree — "Medium calculator" (CalculatorDialog), "Auxiliary
files" (FileMakerDialog) and "Home": they are needed at any step.
3. Validation at every step. After any edit MainWindow::refreshAll calls
tpl::validate and fills the list of diagnostics under the page (errors in red,
warnings in yellow, repetitions collapsed by collapseIssues). An error is visible where it
was made, not at the end of the wizard.
4. Writing (MainWindow::onGenerate): validate again — on errors the
IssueDialog window and a refusal; folder selection (by default — the folder of the opened file); a question about
overwriting an existing .tpl (if enabled in the settings; it is stated separately when
the very file that is open is being overwritten); tpl::writeTask writes .tpl, _step.h,
the pipeline parts and batch files, .sig, the accompanying .eps. The result lists
the written files, reminds to delete the .s before a run (the kernel appends to it) and to
keep _step.h next to the task file, gives the kernel launch command
(kernelRunCommand(kernel, name, tpl::runFlags(p))) or the name of the pipeline batch
file, and warns if some characters did not fit into CP1251. Then it offers
"Home" or "Stay in the task".
The wizard does not launch the kernels: it writes the files and says what to compute them with. The launch is done with
the command from the result or with the pipeline batch file <name>_run.bat / <name>_run.sh.
Wizard and project
MainWindow owns the single instance of tpl::Project (m_project). The canvas,
the property panel and the "What to compute" page receive a pointer to it (setProject)
and edit it in place. Therefore the wizard sections do not lose state when switching:
they all share one task.
Two directions of synchronization:
- fields of the "Calculation" and "Output" sections → project:
pullFromForm(on every field change). Frequencies are collected bycollectFreqs: a single frequency or a "from — to — step" grid with a tolerance of half a step for the last point; - project → fields:
pushToForm(when opening a file or a sample, on undo). Them_loadingflag prevents these writes from coming back into the project.
After any edit refreshAll updates everything that depends on it: the captions about the kind of file (one
frequency — an ordinary .tpl; several — the macro version <name>.tpl + <name>_step.h; more than
tpl::kMaxFreqs = 99 — an error with two exit links: "take a step"
stepForMaxFreqs or "split" into a pipeline), the RP memory estimate, the canvas, the property
panel, the object list, the summary and the diagnostics.
The pickup windows follow the computation time (followTimeWindow). The S-matrix window and the RP window
live in "Output", while TIME lives in "Calculation". If after an edit of TIME a window no longer
fits into the computation, it is placed on the last quarter of the computation, but not shorter than 3 ns; a window
set manually inside the computation is not touched. An RP window that the kernel will not close before
TIME (it extends the window to a whole number of periods) is trimmed by
tpl::patternWindowSafeEnd.
Undo and redo. The history consists of snapshots of the whole project (m_undo, m_redo, depth
kUndoDepth = 120): the task is small, and a copy is cheaper than describing each edit as a
command. The canvas, the property panel and the "What to compute" page emit
aboutToEdit before an edit — the wizard takes a snapshot (snapshot); after the edit they emit projectEdited /
edited, and the wizard calls refreshAll. A 3D import and an accepted full object form are
one edit and one undo. The fields of the "Calculation" and "Output" sections do not go into
the history.
Opening a file (loadFromFile): tpl::readTplFile; on failure — an error window and
the previous state. Otherwise the project is replaced, the folder and the name are remembered (for
"save to the same place" and for an honest "you will overwrite the original"), and the .eps files
of FILE blocks are picked up from the task folder (m_companions, written next to it on every save).
Then comes a numeric summary (shapes, ports, frequencies, variants, whether it was a macro version and what
was included by #include) and a single IssueDialog window if reading produced warnings or
validation produced errors.
A sample (openSample) is opened as a new task without a source folder; its
accompanying files (for example, lens.eps) are placed next to it on every save.
"Save as sample…" (onSaveAsSample) puts a task without validation errors into "My
samples" (samples::saveUserSample) with a title and a description.
Full forms. A double click on an object or "All properties..." → onEditRequested:
ShapeDialog for a shape, PortDialog for a port. The accepted form replaces the object
in one undo step. After a PortDialog with a signal from a file, the task frequency (with a single
frequency) is set to PortDialog::wantedFreq() — the port matching frequency
(tpl::suggestedFreq), and the hint line says so: a FREQ that has drifted away silently
spoils the matching.
Geometry view
GeometryView is a descendant of QGraphicsView. The scene is empty: shapes are not stored as
QGraphicsItem elements; everything is redrawn from tpl::Project in
drawBackground / drawForeground. This way the model has a single source of truth, and the picture
cannot diverge from what the emitter will write. Scene coordinates are millimetres, with the Y axis
pointing up (as in the task file).
Model and signals. The canvas receives a pointer to the project (setProject) and edits it
itself. It reports edits with signals: aboutToEdit (before an edit — for undo),
projectEdited (after), selectionChanged, toolChanged, cursorMoved (coordinates
after snapping, mm — for the line under the canvas), hintChanged (the "what to do
next" hint for the tool), editRequested (double click — full form),
mergeRequested (the "Join" item of the context menu).
Tools (enum class Tool, labelled buttons to the left of the canvas and letter
keys that work only when the canvas has focus):
| Tool | How it is drawn | What it produces |
|---|---|---|
Select |
click, drag, handles | selection, dragging, resizing, rotation |
Rect |
drag | rectangle (RECT_STAT) |
Line |
click after click, double click or Enter to finish | polyline (material POLYGON_STAT, not closed) |
Contour |
the same | closed contour |
Circle |
drag from the centre | circle |
Arc |
centre → radius → opening | ring sector |
ArcLine |
start → end → bulge | an arc as a line (curved wall): a circle through three points, broken into links with step DELTA; three collinear points give a segment |
Port |
drag | port: aperture and direction of the incident wave |
A polyline, a contour and an arc are completed in finishChain (double click or Enter;
repeated points are removed). Shift makes the direction of a link a multiple of 45°, and rotation by
a handle a multiple of 15°. A new shape gets the material "metal" and a name according to its kind
("Line N"). A port gets its side from the drag direction (sideForDrag) or from the
nearest side of the region (nearestSide).
The task language knows nothing of curves (POLYGON_STAT is just a list of vertices), so arcs,
rounding (filletSelected) and stitching pieces into one shape (mergeShapes) are done by the
editor: otherwise such geometry would have to be prepared in a third-party program.
Snapping (findSnap). The tolerance is given in screen pixels (kSnapPx = 11) and
is converted to millimetres at the current zoom. The order, from the strongest target to the weakest:
- characteristic points of what has been drawn — vertices, centres, side midpoints — and the corners of the computational region;
- any point on the lines of shapes and on circles;
- a grid node with the task's DELTA step (
gridStep; 1 mm if the step is not set).
A marker of "what we snapped to" is shown next to the cursor. When dragging a selection, snapping goes only to the grid, and the dragged shape itself is excluded from the targets. Snapping and the grid are toggled by buttons above the canvas; the initial states come from the settings. The grid nodes are the nodes of the kernel's computational grid: the kernel computes a block on the nodes with boundaries that are multiples of the step exactly (see the grid rules and placement on the grid).
⚠️ Since the tolerance is in pixels, fitting the view (zoomToFit) only makes sense after
the widget has been given its size (after returning to the event loop): with a zero size
the zoom comes out tiny, and snapping pulls points by tens of millimetres.
Hit testing (pick), tolerance kPickPx = 7 pixels:
- port markers (radius
kPortMarkerPx+ 2 pixels) and aperture lines; - the selected shape — while a shape is selected, a click on it goes to it, whatever lies on top (otherwise a body inside an eps distribution rectangle could not be moved);
- all shapes from top to bottom (the one drawn later is on top).
A hit can land on a whole shape, on a side of a rectangle or on a vertex of a polyline:
Selection stores the kind (ShapeBody, ShapeEdge, ShapeVertex, PortBody), the object
number and the side or vertex number. This is needed to express "magnetic wall
on top only" with the mouse: the emitter splits such sides into separate blocks.
Drawing layers. drawBackground — background, grid, dashed outline of the computational region.
drawForeground — first the area shapes (fills, the eps field from a formula in the selected
palette), then the contour ones (walls) — walls on top of fills, and the edge of a fill as a thin
semi-transparent line: the edge of a region must not read as a wall. Then — the sweep,
the ports (aperture, a direction arrow for the active one), the RP integration contour as a dashed line,
the dimensions of the selected shape, handles, a preview of the shape being drawn, rulers, the eps scale.
The rule: if something on the canvas looks like a wall, it must be a wall in the computation.
Selection and multi-selection. A click selects one object; Ctrl+click adds
several shapes (a repeated click removes one). Selecting several rows of the object list on the
right does the same. A multi-selection is moved, duplicated (duplicateSelected, shifted by 4 grid
steps), deleted (deleteSelected) and joined (mergeShapes) as a whole; "Join" is
available only when at least two lines or contours are selected
(MainWindow::updateMergeButton). The object list and the canvas show the same selection;
when the selection changes, the list is only highlighted (syncLegendSelection), and
it is rebuilt only when the project is edited (refreshLegend) — otherwise a Ctrl-click on a row
would rebuild the list and lose the multi-selection.
Zoom and pan. Wheel — zoom under the cursor (step 1.15); middle button or Alt+left —
pan the canvas; buttons "Fit", "Zoom in", "Zoom out" (step 1.25). Canvas keys: Esc —
cancel drawing or clear the selection, Enter — finish a polyline, Del — delete.
Right button — context menu: "Properties...", "Join into one shape (N)", "Duplicate (N)", "Delete (N)". The scroll bars are hidden. The canvas itself has no undo: it only emits aboutToEdit; the history is kept by the wizard.
Picture mode (setPreview(true)): mouse, focus and keys are disabled; there are no handles,
rulers, dimensions or hints; the scene margin is 3 % instead of 14 % + 5 mm, and the view is fitted
again on every resize. The static GeometryView::render(project, size)
draws a copy of the project into an off-screen image. This way SamplesPage and the 3D import window draw
the task with the same code as the wizard.
Property panel
PropertyPanel sits to the right of the canvas above the object list and shows the properties of
what is selected: a shape, a rectangle side, a vertex or a port. The form rows are created
once (build), and only the relevant ones become visible (updateDerived):
- shape — name, material (metal, magnetic wall, absorber — contour; dielectric — fill), eps with the hint "the file will receive the increment eps-1", the dimensions of the rectangle or circle/sector, the number of vertices;
- in the X kernel — plasma in one shape: N (m^-3), B (T), losses sigma (S/m) and the grid Y,
as a number or a formula; for a rectangle — a quantity from a file (
FILE_N/_B/_Y); the check box "B exactly over the plasma"; a hint with the frequenciesf_p,f_ceand the X-mode cutoffs (tpl::plasmaBands); - rectangle side — "Side exists", the side's own material;
- port — wave direction, port plane, aperture, role (active/passive), wave
type (H10 or plane); the hint gives the single-mode range of the aperture
c/(2a)...c/a.
Every field change is written to the project immediately (pushToProject): aboutToEdit →
edit → edited. Text fields are written when input is finished, and while the panel itself is writing
to the project (m_pushing), the field values are not overwritten — otherwise the cursor would jump while
a number is being typed. The panel brings the port direction into agreement with the half of the region
(tpl::directionForPlane): otherwise the kernel would silently reverse the incident wave. A polyline
that has been assigned a fill is silently closed into a contour — the kernel always treats an eps expression
as a region. The row of buttons at the bottom: "Round off" with a radius, "All properties...",
"Join", "Duplicate", "Delete".
What to compute
RunPlanPage is section 3 of the wizard. It edits Project::exciters (the port excitation queue:
each excitation is its own #STEP and its own S-matrix column),
Project::variants (geometry variants: title, file tag, which shapes are included;
each variant has its own .s) and Project::sweep (step-by-step rotation of the object for RCS:
the object's shapes, the axis, the angles, a reference step without the object). At the bottom the page shows what
will result: the number of steps (Project::stepCount) and the file names. It edits the project through the
pointer with the same pair of signals aboutToEdit / edited. Model details are in the
sections task model and angular sweep.
Windows and dialogs
| Window | Opened by | What it does |
|---|---|---|
ShapeDialog |
double click on a shape, "All properties..." | full form of a shape: type and name, material and eps, eps as a formula checked while typing (tpl::ExprProgram::compile, epsVariables, epsSamplePoints), profile from a .eps file (rectangle only, FILE block) or writing the profile to a file (RECT_STAT only), a custom origin x, y; plasma (X kernel only): N, B, "B exactly over the plasma", sigma, Y and the files FILE_N/_B/_Y; dimensions depending on the kind of shape, a vertex table; velocity Vx, Vy (*_MOVE blocks). Returns a modified copy of tpl::Shape (shape()) |
PortDialog |
double click on a port, "All properties..." | groups "Placement" (side, aperture, port eps — by default the increment of the medium under the port, tpl::portMediumEps), "Excitation" (activity, H10 or plane wave, a signal as a formula or from a .sig file, a custom table of points; sigPlan, waveBand, portWindow, parseSigPoints, parseSigTones, toneCutNotice), "What arrives at the port" (preview SignalPreview). It does not change the task frequency itself: wantedFreq (tpl::suggestedFreq) hands it to the wizard |
CalculatorDialog |
the "Medium calculator" button | reference information without writing into the task; the pairs are converted both ways: waveguide width <-> H10/H20 cutoffs; dielectric — the increment eps-1, the wavelength in vacuum and in the medium; N <-> f_p (plasmaFreqGHz, concentrationForFreqGHz), B <-> f_ce (cyclotronFreqGHz, fieldForFreqGHz), X-mode cutoffs f_L, f_R (plasmaBands). See plasma frequency and cyclotron frequency |
FileMakerDialog |
a card on the start page, a button in the wizard | file workshop, see below |
Import3DDialog |
"Import from 3D…" on the tool palette | 3D-model cross-section, see below |
SettingsDialog |
"Settings…" above the canvas | canvas view, see settings |
IssueDialog |
writing, reading, saving a sample | list of errors and warnings |
IssueDialog replaces QMessageBox for any list of diagnostics: QMessageBox does not
scroll, and on a large foreign task it grew beyond the edge of the screen together with its
"OK" button. Here the text is in a scrollable area, the buttons are outside it, and the window is shrunk to the screen
(dtheme::fitToScreen) before being shown. Repetitions are collapsed by collapseIssues: diagnostics
that differ only by the prefix "строка N:" / "line N:" are merged into one with the suffix
"— and k more time(s) the same further in the file"; the line number of the first one remains.
Port signals
SignalGallery — selection of the signal waveform with icon tiles (waveformIcon; the curve
is drawn by paintWaveform from representative waveform parameters demoWaveshape) and an
explanation of the selected waveform (tpl::waveformHint); changing the tile emits the signal
currentChanged. SignalPreview shows the port signal the way the kernel will compute it:
- the a(t) trace over the whole computation time [0; TIME] with the boundaries of the port window
(
tpl::portWindow); the values come fromtpl::waveValueor from the kernel formula (sampleAt); - the amplitude spectrum below it: from 4096 to 65536 samples (at least four per
period of the upper frequency), radix-2 FFT with twofold zero padding,
256 bars (each holding the maximum magnitude over the samples that fall into it); the top of the scale is
2*FREQ or 1.3 times the upper frequency of the band, but not above the Nyquist frequency. The spectrum shows
the single-mode range of the aperture H10...H20 and the
FREQline: one can see whether the band of a signal from a file falls into the single-mode range.
Theory — signal at a port and
incident wave from a file; format — .sig file.
Auxiliary files
FileMakerDialog is a modal window with two tabs: "Signal file (.sig)" and "Distribution
file (.eps)". It is opened by a card of the start window and by a button of the wizard; the task
passed to the constructor provides only defaults (DELTA, TIME). The window has no write path of its
own — it writes with the same core functions as the wizard.
- The
.sigtab: the waveform gallerySignalGallery, the waveform fields (the set comes fromtpl::waveFields), a table of points andSignalPreview; the summarytpl::sigPlan(sampling step, number of points, time clipping),waveBand,suggestedFreq. The file is written withtpl::sigFileText+toCp1251; if CP1251 characters are lost, it is not written. The table can be typed by hand or taken from any waveform (20 points per period of the upper frequency, from 400 to 50000). A ready.sigcan be opened: if it was written by this program (the service line@TPLD-SIG), the waveform itself with all its parameters is restored; otherwise the points and tones (parseSigPoints,parseSigTones) go into the "Custom table" waveform; more than 99 tones gives the warningtoneCutNotice. - The
.epstab: the formula eps(x, y, r, f), the check box "Origin at the center of the domain", the mapEpsMapViewfromtpl::epsValues(it shows the increment eps-1), writing withtpl::epsFileBytes. A foreign.epscan be read (readEpsHeader,readEpsValues), and the map shows its numbers by node — a file that has been read has no formula.
3D import
"Import from 3D…" on the tool palette (MainWindow::onImport3D) asks for a model
file (STL, OBJ, and STEP when built with OpenCASCADE; filter tpl::meshFileFilter) and
opens Import3DDialog with a copy of the project. The window's flow:
loadFile->tpl::readMeshFile. STEP units are taken from the file; for STL and OBJ the person chooses them;rescalescales and welds the mesh (Mesh::scale,Mesh::weld).- Table of bodies: the material of each body is a remembered choice (
QSettings,import3d/materials/<name>) or a guess from the name (tpl::guessMaterial). - The XY, YZ or XZ plane — by a button or by clicking the model in 3D (
MeshView::planeClicked: a ray from the eye to the nearest plane); the position — with a slider or a field, mm. updateSlice:tpl::sliceMesh->tpl::simplifySlice(tolerance DELTA/2) -> with "to the centre of the region"tpl::centeringShift->tpl::buildImportShapes(rotation by 90°, mirroring, shift, block numbers fromnextFreeId). If the slice does not fit, a check box makes the region expand with a margin of 10 DELTA. The "What goes into the task" preview is aGeometryViewon a task holding the slice shapes.- The wizard takes
result(), the new region (resultBox,boxChanged) and the provenance line (provenance,tpl::sliceProvenance) and inserts the shapes as one edit (MainWindow::insertImport): a single undo removes the whole import, the provenance is appended to the task description, and the new shapes are selected.
MeshView is a QOpenGLWidget (GLSL 1.10 shaders): the bodies (opaque first, then
semi-transparent) and semi-transparent planes; frames, labels and the slice line are drawn on a
transparent child widget on top (QPainter inside paintGL is not visible on all
systems). Orbit camera: left button — rotation, wheel — zoom, middle button
or Alt+left — pan. The slicing and its conversion into shapes are done by the generator core —
see importing 3D models and STEP import.
Sample library
SamplesPage is a stack page with three columns:
- on the left — sections ("All", the catalogue sections
tpl::samples::sections, "My samples") and a search for all words across the whole library; - in the middle — sample tiles (
TileDelegate); the pictures are drawn by the staticGeometryView::renderon a timer, two per event-loop pass, so that the page does not freeze; - on the right — the card: a sketch (
GeometryViewinsetPreviewmode), the recipe parametersParam(number, integer, choice, check box; after an edit the task is rebuilt after 120 ms), the result oftpl::validate, the data sheet — "theory" (Build::theory) and "computed by the kernel" (tpl::samples::baked, only with the default values,isDefault), explanations, accompanying files, help text.
The task is built by buildFor: make(sample, values) for a built-in recipe or
loadUserSample for a user's own one. "Open in editor" and a double click on a tile emit
openRequested(project, companions) — then main.cpp and MainWindow::openSample take over.
"Write" writes the task directly from the library: validation, folder selection (remembered in
QSettings, samples/lastDir), a question about overwriting based on tpl::taskFileNames, writing with
tpl::writeTask, the launch command kernelRunLine. "My samples" are read by
userSamples (the list is re-read every time the page is shown) and deleted by
removeUserSample; the wizard puts them there ("Save as sample…"). See the sample
catalogue.
Memory
The "Check" section shows whether the computation will fit into the memory of this computer.
MainWindow::updateMemoryChart gets the total and free RAM from the system
(sysmem::query: Windows — GlobalMemoryStatusEx, macOS — sysctl and
host_statistics64, Linux — MemAvailable from /proc/meminfo) and the memory estimate of the
task tpl::ramEstimate(project, available) — the free memory is passed to it because
the kernel itself uses it to decide whether to accumulate the RP over the whole region or along the edge, and the picture
must decide the same way. MemoryDonut draws a ring of the whole RAM: a solid "used"
sector, hatched "kernel grid" and "RP" sectors, and when memory is short — red sectors and a red
overrun arc; a sector smaller than 1.5° is widened to 1.5° to remain visible. The caption says:
it will fit, it is tight (more than 80 % of the free memory) or it may not fit; from 2 GB on —
a reminder about the limit of a 32-bit kernel. Polling — every 3 s, only while the page is on
screen. This is information only: the task can be written in any case — it may be computed
on another machine. See the memory estimate.
Interface translation and language switching
All window strings are obtained via tpl::tr("русский", "English") (core/lang.h) — the same
function as for the texts of the generator core (see translation). The language is common
to the package: main.cpp calls tmci18n::install() and sets
tpl::setEnglish(!tmci18n::russian()). The menu names are translated by the package dictionary
(gui_common/i18n), and the "About TPL Designer…" item has its own pair of strings
(tmci18n::setOwnText).
tpl::tr selects the string at the time of the call, while windows read their texts when they are built. Therefore
on a language change the pages are re-created (main.cpp):
- the
QMenu::triggeredsignal of the language menu; the check is deferred withQTimer::singleShot(0)until the return to the event loop — by then the menu handler has already changed the selection; - if the language has really changed —
tpl::setEnglish; the open page, the wizard's project and thehasContentflag are remembered; - the three pages are removed from the stack (
deleteLater) and rebuilt by thebuildfunction with all their signal connections; - if there was work in the wizard —
MainWindow::setProject(project); the same page is opened.
Signal handlers access the pages through the Pages structure by reference, so they always
refer to the current pages, not to the deleted ones. The names of shapes and ports are task data and are not
translated when the language changes. The undo history is not carried over when the pages are re-created.
Settings
settings::Values holds only view preferences: gradient fill of a formula eps,
the eps colour scale, the eps value under the cursor, the palette (Viridis, heat, grey),
the grid, snapping, dimensions of the selected shape, the question before overwriting a .tpl. Nothing
that affects the contents of a .tpl is in the settings: the task file depends only on what has been
drawn and entered. Storage — the INI file %APPDATA%/TMC_Suite_Qt/TPL Designer.ini
on Windows (settings::installStorage also points the default QSettings there and
migrates the registry keys of earlier versions once), QSettings("TMC", "TplDesigner")
on Linux and macOS. The values are read on first access (settings::values) and
written immediately (settings::setValues).
SettingsDialog applies changes immediately, on every check box — the result is visible
on the canvas behind the window; there is no "Cancel" button, only "Restore defaults". The
settingsChanged signal redraws the canvas. The eps scale, the grid and snapping can also be toggled
with the buttons above the canvas without opening the window.
Styling
The styling matches the programs of the package: a dark palette and the fonts Inter (interface) and
JetBrains Mono (task text in the preview). main.cpp declares the program
(theme::setProgram("tpldesigner")) and loads the fonts (theme::uiFontFamily) from
gui_common, but sets its own style sheet — dtheme::styleSheet(). The common elements in
it have the same values as in the programs of the package (styling);
in addition there are the editor's widget properties: accent (accent button), tool
(canvas tool button; turquoise when pressed), card (card of the start window and of the
library), hline (separator), dim, mute, h1, h2 (label styles). The palette colours
(dtheme::bg() … dtheme::warn()) are also needed by the canvas: it draws them itself, so
the style sheet and the canvas do not diverge. dtheme::fitToScreen shrinks dialogs to 95 %
of the screen width and 88 % of its height — a window whose buttons are not visible does not work.
The window icon is :/icons/resources/app.ico; the .exe icon in Explorer is the Windows resource
app.rc (these are different things, and both are needed).
Mouse wheel
WheelGuard is installed once for the whole application (qApp->installEventFilter), so
it also applies to windows created later. Spin boxes, combo boxes and sliders (except
scroll bars) change their value with the wheel only when the field already has focus:
- on
QEvent::Polishthe focus policyQt::WheelFocusis changed toQt::StrongFocus— focus only by click and Tab, otherwise the wheel would give focus to the field before the check; - on
QEvent::Wheelfor a field without focus the event is rejected (ignore) and swallowed; Qt passes a rejected event to the parent — the scroll area of the page — and the page scrolls.
This way, when the page is scrolled towards "Next", the frequency or the grid step whose fields the pointer passes over do not change.
User-interface pitfalls
- Only
tpl::writeTaskwrites the task file. The windows have no file writing of their own — neither the wizard, nor the library, nor the file workshop. - Long lists of diagnostics — only
IssueDialog, notQMessageBox. - Do not store translated text in a
staticand do not build it in advance: the pages are re-created on a language change, andtpl::tris evaluated at the time of the call. - Pointer to the project. The canvas, the panel and "What to compute" hold the wizard's
tpl::Project*. Afterundo/redoandsetProjectthe wizard hands it out again; pointers to individual shapes and ports (PropertyPanel::shape,port) are valid only until the set of shapes changes. - Do not rebuild the object list on selection — only highlight it
(
syncLegendSelection); rebuild it on a project edit (refreshLegend). - The snap tolerance is in pixels:
zoomToFitbefore the widget has received its size gives a wrong zoom and a "sticky" snap. - Widget object names (
shapeXMin,mergeShapes,btnNext,fileMaker,memoryDonutetc.) are needed by the service snapshot utilitygui_shot, which walks through the user manual with real events; they must not be renamed without changing the utility.
Tests and tools
The generator logic lives in the tpl_core library without windows, so almost everything the
editor promises ("the kernel will accept the task and compute it as drawn") is checked by
Qt Test unit tests without starting the user interface. The tests are ten programs in the
tests directory (about 190 test slots); each is linked with tpl_core and Qt6::Test and
registered in CTest. The user interface is checked separately by the
gui_shot utility, and the fact that a task file really computes is checked by running the
kernels on the task files from sample_gen, sig_gen and
gen_lr2.
Most tests are guards against specific traps of the .tpl language or against errors already
found by runs: the slot name names the property (twoPointLineGetsThirdPoint,
noExponentReachesTheKernel), and the comment on the slot in the code names the error it catches.
A failure of such a test means that the emitter output or the reading has gone wrong exactly at this
place.
Running
The tests are built by the common package build (build/build_win.sh); the executables are in
build/obj/bin. Running all editor tests:
cd build/obj/src/tpl_designer
ctest --output-on-failure
A single suite — ctest -R test_emitter, or directly build/obj/bin/test_emitter.exe;
a single slot — test_emitter.exe macroHasTwoBackslashesAndNoComments (the standard
Qt Test switches, for example -v2 for verbose output). The tests open no windows and do not
start the kernels; files they need to write are written to temporary folders.
Run them after any change to src/core (emitter, validation, reading, grid, samples),
before a release and after a Qt update: some of the guards catch precisely the differences between Qt and the
standard library on different systems.
Reference data
Most suites build projects in memory and need no files. External references
are connected via paths that CMake passes as macros (tests/CMakeLists.txt):
| Macro | Default folder | What is there | Used by |
|---|---|---|---|
TMC_SAMPLES_DIR |
the package's samples/TEST |
LR1 and LR2 task files verified by kernel runs | test_cp1251, test_tplreader |
TMC_IVTAN_DIR |
the package's samples/IVTAN |
full09.tpl — #include, dozens of #define, CIRCLE_STAT, ABSORBER |
test_tplreader |
TMC_ERROR_DIR |
TMC_Suite_Mac/samples/error (neighbouring project) |
mini_file.TPL — a task file with a FILE block |
test_tplreader |
TPLD_MODELS_DIR |
src/tpl_designer/data/models |
3D models produced by make_models |
test_mesh (STEP) |
The paths can be overridden with CMake cache variables of the same names. If a reference is missing from
its place, the slot (or a data row) is skipped via QSKIP — the suite does not fail,
but the check is not performed either: in the CTest output this shows up as SKIP.
test_cp1251 — encoding
13 slots. Tests the editor's own CP1251 codec (see CP1251 encoding):
ASCII passes byte for byte, Cyrillic and "ё/Ё" (0xB8/0xA8) are encoded correctly,
an unrepresentable character (including Greek letters) becomes ? and raises the
lossy flag, while clean text does not raise the flag. Writing with writeCp1251File produces only CRLF and
preserves \\; reading distinguishes UTF-8, UTF-8 with BOM and CP1251. The data are embedded in the test;
matchesGoldenFileBytes compares against LR2_1_wg_p1.tpl from TMC_SAMPLES_DIR.
Main guards:
wholeTableMatchesWindowsCodepage— all 256 bytes both ways against the Windows code page 1251 (0x98 -> U+FFFD): only this guarantees an identical file on all systems;qtOwnEncoderIsBrokenForCp1251— records that the Qt encoder for windows-1251 silently returns nothing; if it works in a build (ICU), its bytes must match the table.
test_emitter — writing the task file
40 slots, no external data: the projects are built in memory (waveguide 240 x 80 mm, step 1 mm, 4 GHz, ports 7 and 12). Covers the mono task and the macro version:
- the
#TMC_RT_Hheader,#EOF, theTlines in#LINK_LIST(one per block), the port side from the anchor, a port inside the region, the circle centre at the anchor; - the increment eps-1 instead of eps, material keywords, the eps profile and the
FILEblock, port eps (increment, eps strictly greater than 0); - X-kernel plasma:
_N/_B/_Y, a B block 2 steps wider than the plasma,CIRCLE_STAT_Y,FILE_N/_B; - polygons: contour closing, a third point for a segment, clockwise traversal, splitting of a rectangle into sides;
- signals: the window of a passive port, a Gaussian without the
^operator; - excitation queue and geometry variants (their own
.s, names in the header); - macro version: a
#defineper combination, exactly\\in a continuation, labels only after the continuation,FIELDSat the first step.
Main guards: generatedFileDoesNotDependOnTheSystem (kernel name without .exe/.app,
CP1251 without losses, CRLF, no BOM), twoPointLineGetsThirdPoint,
macroHasTwoBackslashesAndNoComments, portCanStandInsideTheArea (a port whose side does not
match the half of the box is an error), cutoffIsJudgedByPortAperture.
test_epsfile — eps distribution file
8 slots, no external data. Tests the .eps format: the header in metres
(headerIsInMetres — an error by a factor of 1000), node weights 1 / 0.5 / 0.25 inside, on an edge and
at a corner (nodeWeightsMatchTheKernel — otherwise a double increment on a shared edge), traversal
row by row j = iY*nX + iX (nodeNumbersGoRowByRow), reading the header back, rejection of a
foreign file, the formula variables (r, f — polar angle, not frequency), an error on
an unknown name and rounding of the values to 1e-12 so that the file does not depend on the system's maths
library.
test_expr — expression evaluator
13 slots, no external data. Tests the editor's evaluator: numbers (including
ones with an exponent — they are legal in the editor), arithmetic and rejection of division by 0,
operator precedence and the right associativity of ^, functions and their domains,
angle units (ANGLE_UNIT), spaces inside numbers as in the kernel (2 3 = 23), rejection of
unknown names and garbage, the trap of a macro without parentheses (38+12/2 = 44, not 25),
expressions from samples/IVTAN/TOPOLOGY.H (the constants are written into the test), scaleCoordinates
(replaces only the whole names x, y). The guard hugeExpressionDoesNotCrash: 200,000
terms or 100,000 parentheses give a rejection, not a stack overflow.
test_mesh — 3D import
13 slots. Tests 3D model import: reading STL (text and binary)
and OBJ (bodies, materials, a broken face — warning), the slice sliceMesh (cube, tube,
torus, a plane through a face), contour simplification within the tolerance, convex
decomposition without loss of area, guessing the material from the name (metals, eps of dielectrics,
absorber, air) and the full path "model -> shapes -> validate -> emitMono". The bodies
are built by meshgen in memory; two STEP slots read models from TPLD_MODELS_DIR and
are skipped in a build without OpenCASCADE or without the models. The guard
unweldedMeshDoesNotClose: without vertex welding the slice contours do not close.
test_placement — placement and X-kernel checks
21 slots, no external data: a scene with plasma (X kernel, region 240 x 80 mm,
N = 1e17 m^-3) and an embedded .tpl text. Three groups:
- writing — units first in
#PARM; theSMATRIXlabel equalsFREQ; with a signal from a file,SMATRIXhas no window; a B block 2 steps wider than the plasma that does not extend into the neighbouring plasma, thebExactmode; the*_STAT_S/_Ytags for a circle,FILE_N/_Yblocks; the port eps increment follows the medium (portEpsFollowsTheMedium); - validation — the RP window closes before
TIME(patternWindowMustCloseBeforeTime: otherwise there are no RP files), pickup windows after the steady state, RP contour rules, the plasma edge resonance (edgeLayerResonanceIsWarned), plasma next to a magnetic wall and on an absorber, a block outside the region; - reading — sigma, a file and a wide B come back as one shape;
torfin the port W; the "eps from the medium" mode.
See placement on the grid and task validation.
test_samples — sample library
9 slots iterate over all recipes of the catalogue; there are no references, and files are written to temporary folders:
catalogIsConsistent— catalogue integrity: at least 30 samples, unique identifiers, existing sections, non-empty descriptions, defaults within ranges,baked.cppnumbers only for existing samples;everySampleIsValidByDefault— every sample with its defaults has no validation errors, no CP1251 losses and no fields or topology (otherwise test runs take hours);everySampleSurvivesParameterExtremes,everyWaveguideStandardBuilds— the ends of the parameter ranges and all the cross-sections of the standards;savedSampleReadsBackUnchanged,englishSamplesAreValidAndReadBack— write -> read -> the same text, in both languages;epsFileHasKernelFormat—lens.eps: the step in metres equalsDELTA, 12 bytes per node;formulasGiveKnownValues— reference values of the data-sheet formulas (WR-90 cutoff 6.557 GHz, Chebyshev and Butterworth prototypes, a 50 Ohm microstrip, Bessel functions, the Mie series);userSamplesRoundTrip— "My samples" viaTPLD_USER_SAMPLES.
test_sigfile — incident wave from a file
20 slots, no external data: a 60 mm waveguide and a comb of 10 tones 3...4.8 GHz.
Covers the .sig file, the task pipeline and the
memory estimate:
continuousSignalKeepsAmplitudeAtTheEnd— for a multitone only the beginning is smoothed (smoothing the end produced an error of 1.9 dB with an outwardly correct task file);freqLineOnlyForMultiTone,stepIsFinerThanTheKernel(the.sigstep is half the kernel step),portLineCarriesFileNameInBrackets(no space before[),markerRoundTripsExactly,writeTaskPutsSignalFileNextToTask(CP1251, CRLF);- reading: waveform from the file, a foreign file as a table, a missing file;
- pipeline:
chunkingSplitsGridAndNamesFilesApart(each part has its own.s, a shared.sig,_run.batand_run.sh),runFlagsCarryTimingKey(the/Timeswitch does not change the.tpl); - the limit of 99 frequencies:
toneListIsCappedAt99,foreignFileKeepsItsFreqLine,moreThan99FreqsIsAnError; memory of a multi-frequency RP —patternMemoryGrowsWithTones.
test_sweep — angular sweep
15 slots, no external data: a scattering scene (a plate and a rod in a region of 300 x 300 mm, angles 0/30/60 degrees and a reference step). Covers the angular sweep:
- labels and file names:
labelNeverZero,fileTagHasNoDot,freqKeepsItsDigits(9.35 is not rounded to 9.4); - the mono version writes its own
.sfor each angle with a label equal to the frequency (monoWritesReferenceAndAngles); the rotated geometry is expressions ofAng__; the macro version describes the step once (macroDescribesStepOnce, exactly\\); validationCatchesWhatCannotRotate— several frequencies, variants, B and an eps profile on a rotated shape give an error, not silent corruption;- round trip of the mono and macro versions,
pivotFollowsTheObject,singleExciterIsJustTheActivePort,descriptionSurvivesRoundTrip; noExponentReachesTheKernel(the kernel's evaluator does not understand notation like1e17),frequencyMacroKeepsNames.
test_tplreader — reading the task file
39 slots (2 of them data-driven _data tables), four groups. Covers reading a .tpl:
- preprocessor (8) —
!is stripped before joining at\\,#definesubstitution is textual,includeIsFoundRegardlessOfCase(letter case of names on macOS and Linux),warningLineMatchesTheSourceFile(the line number in a warning comes from the original file); - round trip (16) — an eps profile as a formula, from a
FILE, with a shifted origin, in a circle; plasma N and B come back as one shape; a plasma profile and unit conversion; macro version; - references (6) —
goldenSurvivesReEmit(reference -> model -> emitter -> model),goldenMacroMatchesGoldenPlain(the macro and the plain versions of LR2 give the same model); data —TMC_SAMPLES_DIR(LR1, LR2, LR2 with plasma),full09.tplfromTMC_IVTAN_DIR,mini_file.TPLfromTMC_ERROR_DIR; without the file —QSKIP; - the unclear (5) — segment padding is removed without diagnostics, shape names are taken from comments, the text does not change on repeated saves, the excitation queue does not make all ports active.
Tools: overview
The tools directory holds service console programs in C++ (built together with the package,
not included in the release) and Python scripts. The programs are linked with tpl_core and work with the same
Project model as the editor: a task file produced by a utility is exactly the
file the wizard would have written. The build is common (build/build_win.sh); the executables
are in build/obj/bin. All programs write their report to stdout in Russian.
| Program | What it does | When to run it |
|---|---|---|
sample_gen |
exports the library samples as task files + manifest.txt |
when editing recipes; before updating the data sheets |
sig_gen |
task files with an incident wave from a .sig for each waveform, pipeline, macro, reference |
after changes to sigfile/the emitter; when checking new kernel builds |
gen_lr2 |
LR2 task files and emitter test cases | after changes to the emitter — check by a kernel run |
tpl_dump |
prints what the parser understood in a .tpl; emits it back through the emitter |
debugging task reading without windows |
gui_shot |
window snapshots to PNG and self-tests of the interface with real events | after changes to src/gui; for snapshots and videos for the manual |
make_models |
test 3D models (STL, OBJ, STEP) and task files checking a cut dielectric | when changing the 3D import or the data/models set of models |
make_icon |
the program icon for Windows, macOS, Linux | when changing the icon drawing or palette |
make_pdf |
printing HTML to PDF with Qt | from make_guide_pdf.py when releasing the manual |
The exit codes of all programs have the same meaning: 0 — success, 1 — runtime
error (a file was not written, a task did not pass validation), 2 — invalid command
line (a usage hint is printed). The exception is sig_gen: an error of an individual task file
is printed, but the exit code remains 0.
sample_gen — exporting samples
sample_gen <folder> [--no-fields] [id ...] [--set key=value ...]
Builds every sample of the library (samples::all()) with the default parameters,
checks it with validate() and writes it with the common tpl::writeTask into <folder>/<id>/ —
the .tpl task file (for a sweep also _step.h) in CP1251 and the accompanying files (.sig, .eps).
--no-fields— turns off fields and topology, including in the author's task files of the "Lessons" section: a test run with them takes tens of minutes instead of seconds.id ...— export only the listed samples.--set key=value— override a recipe parameter with a number (to check with a kernel run a branch that is enabled by a choice, for example the computation method of a band-stop filter). If the sample has no such parameter, a notice is printed.
Next to them, manifest.txt is written — one line per sample:
id h|x name.tpl s-files... | problem statement in words | tag=name;;tag=name. From it the script
bake_samples.py runs the kernels and collects the data-sheet numbers.
Code 1 — at least one sample has a validation error, a loss of CP1251 characters or a write failure: every recipe with its defaults must be clean. The order of updating the data sheets (sample catalogue):
sample_gen <folder> --no-fields
python tools/bake_samples.py run <folder>
python tools/bake_samples.py cpp <folder> src/core/samples/baked.cpp
sig_gen — task files with an incident wave from a file
sig_gen <folder> [--forms] [--pipeline] [--macro] [--ref]
Proves by an H-kernel run that the generator produces a computable file for every
signal waveform. The device is the same in all task files — a 60 mm waveguide with an insert of eps = 2
and a length of 60 mm (region 200 x 84 mm, DELTA 1 mm, TIME 40 ns), as in the package's reference
samples/MULTIFREQ/wg_wide.tpl, so that the numbers can be compared with an already verified
result. Without switches all sets are executed:
| Switch | Task files | What it checks |
|---|---|---|
--forms |
sig_multi, sig_chirp, sig_burst, sig_grf, sig_gvid, sig_mono, sig_trap, sig_saw, sig_tri, sig_sq, sig_expr, sig_tab |
each of the 12 waveforms; FREQ is the matching frequency suggested by the waveform (suggestedFreq) |
--pipeline |
pipe_001...pipe_004 + batch files |
pipeline: 40 frequencies 3.00...4.95 GHz, 10 per task file |
--macro |
mac.tpl + mac_step.h |
a file name in square brackets inside a macro body — the kernel preprocessor |
--ref |
ref |
reference sweep over 10 frequencies 3.0...4.8 GHz for comparison |
For each waveform the number of points and the .sig step (sigPlan) are printed. More on the format
and the rules — section incident wave from a file.
gen_lr2 — emitter test task files
gen_lr2 [folder]
Assembles a set of task files on the Project model and writes them in CP1251 (by default — to
the current folder). Each project passes validate(); at the first error the program
stops with code 1.
| Task file | Contents |
|---|---|
wg_p1, wg_p2 |
LR2: empty waveguide (X kernel, 4 GHz), port 1 / port 2 active; the shared wg.s gives the full 2 x 2 matrix |
pl_p1, pl_p2 |
the same with magnetized plasma: N = 3.1e17 m^-3, B = 0.071 T |
sweep |
sweep 3.0...5.0 GHz (21 points) — macro version |
wide |
sweep 1.0...5.0 GHz (41 points); the lower part is below the H10 cutoff — validation must warn but not forbid |
pulse |
Gaussian pulse at the port (centre 20 ns, duration 5 ns) |
edges |
a waveguide as one rectangle without end sides and a polyline iris (H kernel) |
ultra |
2 geometry variants x 2 excitations = 4 steps in one file |
plshapes |
plasma as a circle (N + B) and as a rectangle (N + Y) |
tpl_dump — what the parser understood
tpl_dump <file.tpl> [--expanded] [--reemit [folder]]
Reads a task file with the same readTplFile as the "Open existing" command and prints the model:
name, kernel, version (plain or macro), included files, region, DELTA, TIME,
frequencies, shapes (material, eps or profile, plasma, motion, geometry), ports,
excitation queue, variants, output. Then — what was not read completely, and
the errors and warnings of validate() for the model that was read.
--expanded— additionally the text after preprocessing (expanded#includefiles and macros): shows what the task file expanded into.--reemit— emit the model that was read back through the emitter: without a folder — the.tpltext to stdout, with a folder — the files<name>.tpl(and<name>_step.h) in CP1251. This is how the "read — write" round trip is checked by eye.
Code 1 — only for read errors (or write errors with --reemit); diagnostics and validation errors of the
model do not change the code.
gui_shot — snapshots and self-tests of the interface
gui_shot <file.png> [width=1400] [height=880] [mode] [switches]
It is built from the src/gui sources (with the same styles and mouse-wheel guard as the
program), opens the windows with the real application code and either takes PNG snapshots of them or
walks through a scenario with real mouse and keyboard events, printing ok /
ПРОВАЛ (fail) lines. The mode is determined by the presence of a word among the arguments.
Snapshots of a single window:
| Mode | Window |
|---|---|
issues <file.tpl> |
diagnostics for a task file that was read |
calc, settings |
calculator, settings |
files [eps\|table] [full] |
auxiliary file workshop |
port [waveform] [filled] [preview] [full] |
port window; waveforms multi ... tab, filled — a port in a dielectric of eps = 4, preview — only the signal plot |
shape [epsfile] [plasma] |
shape properties |
| no mode | main window; the fourth argument is start, samples [section] [id] or a section number 0...4; switches demo, open <tpl>, reset, hover <x mm> <y mm>, arc, full |
Self-tests:
| Mode | What it walks through |
|---|---|
selftest |
canvas: arc, priority of the selected shape, stitching, selection of several shapes, group commands |
samplescheck |
sample library: cards, parameters and "Restore defaults", opening in the wizard, "My samples" (in a temporary folder via TPLD_USER_SAMPLES), search, rotating an object with one port |
filescheck |
file workshop: a table from a waveform, the "write — read" round trip for .sig and .eps |
wheelcheck |
the wheel over a field without focus does not change the value but scrolls the page |
limitscheck |
the 99-frequency limit, the "take a step" and "split" links, RP memory, memory chart |
import3d <model> [XY\|YZ\|XZ] [mm] |
import of a 3D-model slice, four snapshots of the steps |
sigexample |
a 1...100 GHz comb for the manual, five snapshots |
tutorial [movie] |
the first argument is a folder; a walk through the "Step-by-step example" with frames NN_<name>.png, with movie — a continuous series for a video |
Together with the snapshot, lines REGION<TAB>key<TAB>x<TAB>y<TAB>w<TAB>h are printed to stdout —
a map of the window regions. From it tools/make_guide_shots.py places numbered frames on
the manual's illustrations, and tools/make_guide_video.py joins the tutorial movie frames
into a video. Code 1 — the snapshot was not saved or there are scenario failures.
⚠️ The utility finds widgets by objectName and by button text (legend, mergeShapes,
freqRange, shapeXMin, sampleOpen, "Take from waveform", "Restore defaults" etc.):
renaming in src/gui breaks the check with a "not found" message (see
user-interface pitfalls). Run it on an ordinary desktop: with
-platform offscreen the Windows fonts are not loaded and the text comes out as boxes.
make_models — test 3D models
make_models <folder>
make_models --kernel-check <folder>
The project has no model files — the models are drawn by code, so the slice of each one is known in advance. The first
mode writes the set into data/models (the import tests read it via TPLD_MODELS_DIR);
all dimensions are in mm:
| File | Format | Model |
|---|---|---|
waveguide_iris.stl |
text STL | a 60 x 30 mm waveguide 200 mm long, an inductive iris (20 mm window), a non-convex PTFE insert (L-shaped) |
horn.obj + horn.mtl |
OBJ + MTL | H-plane sectoral horn |
patch.obj + patch.mtl |
OBJ + MTL | patch antenna: ground, FR-4 substrate, patch, feed line |
tokamak.stl |
text STL | tokamak vessel (toroidal shell), solenoid, PF1 coil; 96 segments |
tokamak_fine_binary.stl |
binary STL | the same, 360 segments; the format does not store body names |
waveguide_iris.step, waveguide_iris_in_meters.step, tokamak.step |
STEP | only in a build with OpenCASCADE (make_models_step.cpp): names, colours and materials of the bodies; the second file is in metres and after reading must match the millimetre one |
The --kernel-check mode writes four task files split_rect, split_poly, split_horiz,
split_diag: one and the same insert of eps 2.1 in a waveguide — whole and cut into
convex pieces. The import cuts a non-convex cross-section, and on the common edge two blocks fall on
the same nodes; a kernel run shows whether the kernel adds up the node weights (the cut is invisible)
or overwrites them (a different medium will appear on the edge). See importing 3D models.
make_icon — program icon
make_icon <out.ico>
make_icon --icns <out.icns>
make_icon --png <folder>
The icon is drawn by code rather than stored as an image: small sizes (16 and 20 pixels) need their own line thickness, and the palette must match the window palette. All three formats get the same drawing (background, grid, waveguide walls, wave, port dots; the grid from 48 pixels up, the dots from 32 up):
- ICO — 16, 20, 24, 32, 40, 48, 64, 128, 256 pixels, placed into
src/gui/resources/app.ico; - ICNS — ten images of 16...1024 pixels with retina variants, for the
.appbundle; - PNG —
tpl-designer-<N>.pngfor the Linux hicolor theme, N = 16...512.
The ICO and ICNS containers are assembled by hand: Qt plugins for writing them are not present in all builds.
make_pdf — HTML to PDF
make_pdf <input.html> <output.pdf> [title]
Prints HTML (UTF-8) with images to an A4 PDF via QTextDocument and QPdfWriter (margins
14/12 mm, 150 dots per inch) — without external converters. QTextDocument understands only
a subset of HTML and CSS, so the markup is prepared by tools/make_guide_pdf.py: it
turns the manual's Markdown into simple tags and sets image widths in pixels.
Without a display — with QT_QPA_PLATFORM=offscreen.
Python scripts
| Script | Purpose |
|---|---|
bake_samples.py |
run <folder> — runs the kernels on the task files from sample_gen (deletes the target .s before the run) and writes results.json; cpp — assembles src/core/samples/baked.cpp; show, recpp — viewing and rebuilding without the kernels |
check_physics.py |
invariants over results.json: power balance over an S-matrix column, |Sij| <= 1, expected behaviour by problem type |
check_theory.py |
comparison of the kernel's numbers with independently written textbook formulas |
make_guide_shots.py, make_guide_pdf.py, make_guide_video.py |
manual snapshots with frames (via gui_shot), PDF (via make_pdf), video and GIF of the walk-through |
toolchain-osxcross.cmake |
cross-build file for macOS on Linux (called from scripts/build-macos-dmg.sh) |