Архитектура Qt6-версии

Раздел описывает исходный код Qt6-версии пакета TMC Suite: из каких частей он состоит, как части связаны, откуда начинать чтение. Подробности о каждом модуле — на страницах модулей (меню слева), справочник по классам и функциям — в справочнике API, физика и формулы — в разделе Теория метода.

Состав пакета

Программа Исполняемый файл Что делает Исходники
TPL Designer TplDesigner.exe редактор заданий: геометрия, материалы, порты, сигналы → файл .tpl apps/tpl_designer
PlanarRT_H planarrt_h.exe счётное ядро для волн H-поляризации src/kernels/planarrt_h + apps/planarrt_common, apps/planarrt_h
PlanarRT_X planarrt_x.exe счётное ядро для волн E-поляризации (X-мода) с подмагниченной плазмой src/kernels/planarrt_x + apps/planarrt_common, apps/planarrt_x
TMCGROUT tmcgrout.exe графики S-параметров по частоте src/viewers/tmcgrout + apps/tmcgrout
TMCROS tmcros.exe сигналы во времени, восстановление S-матрицы по сигналам src/viewers/tmcrtout + apps/tmcros
TMC_DN tmc_dn.exe диаграммы направленности, КНД, КИП, решётки src/viewers/dianapgr, src/viewers/dianapr + apps/tmc_dn
FieldView fieldview.exe распределение поля и топология сетки (Qt RHI: Direct3D 11 / OpenGL) apps/fieldview_rhi

Главный принцип: расчёт не переписывается

Раздел описывает только Qt6-версию 5.1 с новым графическим интерфейсом. Прежняя MFC-версия пакета — отдельная программа со своими исходниками; здесь она не описывается.

Расчётная часть Qt6-версии — ядра, библиотеки, чтение заданий, форматы файлов — перенесена из прежней версии пакета и компилируется без изменений (каталог src/libs, src/kernels, src/viewers). Этот код изначально писался на MFC и обращается к её классам (окна, диалоги, потоки), поэтому Qt6-версия содержит собственный слой совместимости src/compat: он реализует нужные классы на Qt 6. Самой библиотеки MFC в Qt6-версии нет. Новыми написаны интерфейс на Qt 6 и этот слой. Благодаря неизменному расчётному коду числа в выходных файлах Qt6-версии совпадают с прежней версией пакета побайтно.

Для побайтного совпадения сборка принимает три меры:

  • -ffp-contract=off — компилятору запрещено объединять умножение и сложение в одну операцию FMA (MSVC так не делает, результат различался бы в последних битах);
  • compat/ucrt_libm_win.cpp — sin, cos, exp и другие функции берутся из ucrtbase.dll, как у программ, собранных MSVC;
  • однобайтовая сборка (_MBCS, без UNICODE), как у Windows-версии.

Слои

 ┌───────────────────────────────────────────────────────────────────────────┐
 │ apps/*            Qt-оболочки программ: главное окно, меню, панели,      │
 │                   диалоги из ресурсов .rc, тестовые программы            │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ gui_common        тема, «О программе», цвет, печать, последние файлы,    │
 │  ├ i18n           перевод интерфейса ru/en                               │
 │  └ compute        расчёт на видеокарте (OpenCL): проверка, настройки     │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ compat            слой совместимости: классы MFC (CWnd, CDocument, CView,│
 │                   CDialog …) реализованы на Qt 6: GDI→QPainter, QThread  │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ libs, kernels     код Windows-версии без изменений:                      │
 │  ├ libs           6 библиотек (разбор задания, S-файлы, выражения …)     │
 │  ├ kernels        счётные ядра H и X                                     │
 │  ├ viewers        документы и виды вьюверов                              │
 │  └ include        общие заголовки                                        │
 └───────────────────────────────────────────────────────────────────────────┘
   apps/fieldview_rhi и apps/tpl_designer — чистый Qt, слой совместимости им не нужен.
  • src/libs, src/kernels, src/viewers — то, что считает и читает/пишет файлы. Комментарии в этом коде описывают алгоритмы и ссылаются на теорию.
  • compat — подменяет MFC: исходники src/libs, src/kernels, src/viewers включают <afxwin.h>, а получают реализацию классов MFC на Qt (Слой совместимости). Под Windows системный API (windows.h) настоящий, под Linux — заглушки из compat/include_posix. Файл compat/include/tmc_win_prelude.h подставляется компилятором в начало каждого файла src/libs, src/kernels, src/viewers (ключ -include): он даёт то, что MSVC давал неявно.
  • gui_common — общие для всех программ компоненты интерфейса (Общие компоненты) и расчёт на видеокарте (GPU).
  • apps — оболочки программ. У каждой программы три уровня библиотек: <программа>_core (код src/libs, src/kernels, src/viewers, ни строчки Qt), <программа>_view (вид, рисование), <программа>_gui (главное окно на Qt), и исполняемый файл.

Библиотеки

Цель CMake Каталог Назначение Зависит от
complex src/libs/complex комплексная арифметика старого кода —
sfile95 src/libs/sfile95 чтение и запись файлов S-параметров —
exprint src/libs/expr, src/libs/inter вычисление выражений и интерполяция —
TMCLibError src/libs/tmcliberror объект ошибки, общий для всех модулей —
prepr src/libs/prepr препроцессор файлов задания (#include, макросы) TMCLibError
TMCIndan src/libs/tmcindan разбор задания ядра, топология, интегрирование поля для ДН prepr, exprint, TMCLibError

Состав каждой библиотеки взят из проекта Windows-версии (.vcxproj): функция tmc_add_library в src/CMakeLists.txt компилирует только перечисленные файлы. Остальные файлы каталогов — вне сборки.

Поток данных

 TPL Designer ──► задание .tpl (+ .h с макросами, .eps, .sig)
                     │
                     ▼
 PlanarRT_H / PlanarRT_X
   1. prepr      — разворачивает #include и макросы
   2. TMCIndan   — разбирает блоки, порты, параметры сетки, выходные файлы
   3. ядро       — строит узлы сетки и ведёт расчёт во времени (CPU или GPU)
   4. вывод      — сигналы на портах, S-матрица, ДН, поля, топология
                     │
        ┌────────────┼──────────────┬──────────────┐
        ▼            ▼              ▼              ▼
    TMCGROUT      TMCROS         TMC_DN        FieldView
   S(f), .s     сигналы .t,     ДН .AMP/.FAZ/  поле и
                S по сигналам   .DAT, КНД      топология

Расширения и устройство файлов — Форматы файлов.

Потоки выполнения

Счётные ядра считают в отдельном потоке: класс потока MFC (CWinThread, AfxBeginThread) реализован в слое совместимости поверх QThread. Интерфейс получает ход расчёта через строку состояния и прогресс-бар; остановка — через флаг, который расчётный поток проверяет на каждом шаге. Подробно — Оболочка ядер.

Сборка

Windows: MinGW 13.1 + Qt 6.11.3, OpenCASCADE 7.9 (импорт STEP в TPL Designer). Одна команда собирает все библиотеки, программы и TPL Designer:

sh build/build_win.sh            # лог — build-win.log
sh build/package_win.sh    # поставка в dist/

Ядра и вьюверы компилируются с ключами -fpermissive -w: код Windows-версии писался под старые версии MSVC, и предупреждения в нём не исправляются, чтобы не менять код.

С чего начать чтение

  1. Теория метода → Обзор — что считает пакет.
  2. Счётное ядро H — основной цикл расчёта: построение узлов и обход во времени (CTmcRTHNodeDiel, CTmcRTHRectNode).
  3. Библиотека TMCIndan — как задание превращается в описание блоков.
  4. Оболочка ядер — как всё это запускается из окна программы.
  5. Счётное ядро X — отличия X-ядра (плазма, четыре подтакта).

Документация в коде

Каждый файл, класс, функция и поле прокомментированы по стандарту комментирования (Doxygen, ///). Комментарий в коде — короткая точка входа; формулы и вывод — на страницах раздела «Теория метода», куда ведут ссылки @see https://www.tamic.ru/docs/.... Справочник API на этом сайте собирается из тех же комментариев.

Architecture of the Qt6 version

This section describes the source code of the Qt6 version of the TMC Suite package: what parts it consists of, how the parts are connected, and where to start reading. Details on each module are on the module pages (menu on the left), the class and function reference is in the API reference, and the physics and formulas are in the Theory of the method section.

Package contents

Program Executable What it does Sources
TPL Designer TplDesigner.exe task editor: geometry, materials, ports, signals → .tpl file apps/tpl_designer
PlanarRT_H planarrt_h.exe compute kernel for H-polarization waves src/kernels/planarrt_h + apps/planarrt_common, apps/planarrt_h
PlanarRT_X planarrt_x.exe compute kernel for E-polarization waves (X-mode) with magnetized plasma src/kernels/planarrt_x + apps/planarrt_common, apps/planarrt_x
TMCGROUT tmcgrout.exe plots of S-parameters versus frequency src/viewers/tmcgrout + apps/tmcgrout
TMCROS tmcros.exe time-domain signals, reconstruction of the S-matrix from signals src/viewers/tmcrtout + apps/tmcros
TMC_DN tmc_dn.exe radiation patterns, directivity, aperture efficiency, arrays src/viewers/dianapgr, src/viewers/dianapr + apps/tmc_dn
FieldView fieldview.exe field distribution and grid topology (Qt RHI: Direct3D 11 / OpenGL) apps/fieldview_rhi

Main principle: the computation is not rewritten

This section describes only the Qt6 version 5.1 with the new graphical interface. The former MFC version of the package is a separate program with its own sources; it is not described here.

The computational part of the Qt6 version — kernels, libraries, task file reading, file formats — has been carried over from the former version of the package and is compiled without changes (the src/libs, src/kernels, src/viewers directory). This code was originally written for MFC and uses its classes (windows, dialogs, threads), so the Qt6 version contains its own compatibility layer src/compat: it implements the required classes on top of Qt 6. The MFC library itself is not present in the Qt6 version. Only the Qt 6 interface and this layer are newly written. Because the computational code is unchanged, the numbers in the output files of the Qt6 version match those of the former version of the package byte for byte.

To achieve byte-for-byte agreement, the build takes three measures:

  • -ffp-contract=off — the compiler is not allowed to fuse a multiplication and an addition into a single FMA operation (MSVC does not do this, and the result would differ in the last bits);
  • compat/ucrt_libm_win.cpp — sin, cos, exp and other functions are taken from ucrtbase.dll, as in programs built with MSVC;
  • single-byte build (_MBCS, without UNICODE), as in the Windows version.

Layers

 ┌───────────────────────────────────────────────────────────────────────────┐
 │ apps/*            Qt shells of the programs: main window, menus, panels,  │
 │                   dialogs from .rc resources, test programs               │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ gui_common        theme, About dialog, color, printing, recent files,     │
 │  ├ i18n           ru/en interface translation                             │
 │  └ compute        GPU computing (OpenCL): checks, settings                │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ compat            compatibility layer: MFC classes (CWnd, CDocument,      │
 │                   CView, CDialog …) on Qt 6: GDI→QPainter, QThread        │
 ├───────────────────────────────────────────────────────────────────────────┤
 │ libs, kernels     code of the Windows version without changes:            │
 │  ├ libs           6 libraries (task parsing, S-files, expressions …)      │
 │  ├ kernels        compute kernels H and X                                 │
 │  ├ viewers        documents and views of the viewers                      │
 │  └ include        common headers                                          │
 └───────────────────────────────────────────────────────────────────────────┘
   apps/fieldview_rhi and apps/tpl_designer are pure Qt and do not need the compatibility layer.
  • src/libs, src/kernels, src/viewers — the code that computes and reads/writes files. Comments in this code describe the algorithms and refer to the theory.
  • compat — substitutes for MFC: the src/libs, src/kernels, src/viewers sources include <afxwin.h> and get an implementation of the MFC classes on Qt (Compatibility layer). Under Windows the system API (windows.h) is the real one, under Linux it is stubs from compat/include_posix. The file compat/include/tmc_win_prelude.h is inserted by the compiler at the beginning of each src/libs, src/kernels, src/viewers file (the -include option): it provides what MSVC provided implicitly.
  • gui_common — interface components shared by all programs (Common components) and GPU computing (GPU).
  • apps — program shells. Each program has three levels of libraries: <program>_core (the src/libs, src/kernels, src/viewers code, not a single line of Qt), <program>_view (the view, drawing), <program>_gui (the main window on Qt), plus the executable.

Libraries

CMake target Directory Purpose Depends on
complex src/libs/complex complex arithmetic of the old code —
sfile95 src/libs/sfile95 reading and writing S-parameter files —
exprint src/libs/expr, src/libs/inter expression evaluation and interpolation —
TMCLibError src/libs/tmcliberror error object shared by all modules —
prepr src/libs/prepr preprocessor of task files (#include, macros) TMCLibError
TMCIndan src/libs/tmcindan parsing the kernel task, topology, field integration for the RP prepr, exprint, TMCLibError

The contents of each library are taken from the Windows version project (.vcxproj): the function tmc_add_library in src/CMakeLists.txt compiles only the listed files. The remaining files of the directories are outside the build.

Data flow

 TPL Designer ──► task file .tpl (+ .h with macros, .eps, .sig)
                     │
                     ▼
 PlanarRT_H / PlanarRT_X
   1. prepr      — expands #include and macros
   2. TMCIndan   — parses blocks, ports, grid parameters, output files
   3. kernel     — builds the grid nodes and runs the time-domain computation (CPU or GPU)
   4. output     — port signals, S-matrix, RP, fields, topology
                     │
        ┌────────────┼──────────────┬──────────────┐
        ▼            ▼              ▼              ▼
    TMCGROUT      TMCROS         TMC_DN        FieldView
   S(f), .s     signals .t,    RP .AMP/.FAZ/  field and
                S from signals .DAT, D        topology

File extensions and structure — File formats.

Threads of execution

The compute kernels run in a separate thread: the MFC thread class (CWinThread, AfxBeginThread) is implemented in the compatibility layer on top of QThread. The interface receives the progress of the computation through the status bar and the progress bar; stopping is done through a flag that the computation thread checks at every step. Details — Kernel shell.

Build

Windows: MinGW 13.1 + Qt 6.11.3, OpenCASCADE 7.9 (STEP import in TPL Designer). A single command builds all libraries, programs and TPL Designer:

sh build/build_win.sh            # log — build-win.log
sh build/package_win.sh    # distribution package into dist/

The kernels and viewers are compiled with the -fpermissive -w options: the Windows version code was written for old versions of MSVC, and its warnings are not fixed so as not to change the code.

Where to start reading

  1. Theory of the method → Overview — what the package computes.
  2. Compute kernel H — the main computation loop: building the nodes and the time stepping (CTmcRTHNodeDiel, CTmcRTHRectNode).
  3. TMCIndan library — how a task file is turned into a description of blocks.
  4. Kernel shell — how all this is started from the program window.
  5. Compute kernel X — differences of the X kernel (plasma, four sub-steps).

Documentation in the code

Every file, class, function and field is commented according to the commenting standard (Doxygen, ///). A comment in the code is a short entry point; formulas and derivations are on the pages of the "Theory of the method" section, reached through links @see https://www.tamic.ru/docs/.... The API reference on this site is built from the same comments.