From 08fcd58893b5ea754ebddbf63b2745dde34d4830 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sun, 8 Nov 2026 05:11:35 +0300 Subject: publish --- .envrc | 20 + .gitignore | 3 + README.org | 48 +++ UNLICENSE | 24 ++ build.sh | 11 + doc/biblio.bib | 13 + doc/gost/gost-7-32-bibliography.sty | 57 +++ doc/gost/gost-7-32-captions.sty | 23 ++ doc/gost/gost-7-32-counters.sty | 44 +++ doc/gost/gost-7-32-headings.sty | 114 ++++++ doc/gost/gost-7-32-lists.sty | 17 + doc/gost/gost-7-32-tables.sty | 29 ++ doc/gost/gost-7-32-toc.sty | 34 ++ doc/gost/gost-7-32.cls | 62 +++ doc/its.plt | 40 ++ doc/ox-init.el | 31 ++ doc/report.org | 735 ++++++++++++++++++++++++++++++++++++ doc/setup.org | 30 ++ doc/spbstu-report.cls | 74 ++++ doc/task.org | 14 + src/bitarray.c | 33 ++ src/bitarray.h | 18 + src/board.c | 36 ++ src/board.h | 19 + src/cellular-automaton.c | 49 +++ src/cellular-automaton.h | 19 + src/config.h | 52 +++ src/dynamic-array.h | 59 +++ src/main.c | 576 ++++++++++++++++++++++++++++ src/utils.h | 65 ++++ 30 files changed, 2349 insertions(+) create mode 100644 .envrc create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 doc/biblio.bib create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/its.plt create mode 100644 doc/ox-init.el create mode 100644 doc/report.org create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 doc/task.org create mode 100644 src/bitarray.c create mode 100644 src/bitarray.h create mode 100644 src/board.c create mode 100644 src/board.h create mode 100644 src/cellular-automaton.c create mode 100644 src/cellular-automaton.h create mode 100644 src/config.h create mode 100644 src/dynamic-array.h create mode 100644 src/main.c create mode 100644 src/utils.h diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..003f58a --- /dev/null +++ b/.envrc @@ -0,0 +1,20 @@ +CHANNELS=./etc/channels-lock.scm +MANIFEST=./etc/manifest.scm +LOAD_PATH=./lib +ROOT=./.guix-shell + +TIME_MACHINE_FLAGS+=" --channels=$CHANNELS" +SHELL_FLAGS+=" --manifest=$MANIFEST" +SHELL_FLAGS+=" --search-paths" +SHELL_FLAGS+=" --root=$ROOT" +SHELL_FLAGS+=" --load-path=$LOAD_PATH" + +use_guix_shell() { + test -d "$ROOT" && unlink "$ROOT" + eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")" +} + +use guix_shell +export TEXINPUTS=${TEXINPUTS}:./:./gost/ +export LD_LIBRARY_PATH=${PWD}/.guix-shell/lib/:${LIBRARY_PATH} +export LIBRARY_PATH=${PWD}/.guix-shell/lib/:${LIBRARY_PATH} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a7aea74 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.html +*.pdf +/main \ No newline at end of file diff --git a/README.org b/README.org new file mode 100644 index 0000000..7bac321 --- /dev/null +++ b/README.org @@ -0,0 +1,48 @@ +#+title: 2D cellular automaton +#+date: 2024H2 + +* Task +:PROPERTIES: +:CUSTOM_ID: task +:END: +Implement a two‑dimensional cellular automaton with a von Neumann +neighborhood and it's visualization. The automaton’s functionality +should include: +1. The ability to generate a random state. +2. The ability to manually configure the state. +3. The ability to set the field size. +4. The ability to determine the number of iterations. + +The automaton function: *7931880* (=0x007907E8=) + +* Documentation +:PROPERTIES: +:CUSTOM_ID: documentation +:END: +The exported report can be found at [[https://git.michalec.dev/files/uni/term-05/automata-theory/lab-01/report.pdf][this link]]. + +* Showcase +:PROPERTIES: +:CUSTOM_ID: showcase +:END: +#+caption: Help +#+attr_html: :width 75% +[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/help.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/help.png]] + +#+caption: Making cells live in while the automaton runs +#+attr_html: :width 75% +[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/sierpinsky.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/sierpinsky.png]] + +#+caption: Sample initial state +#+attr_html: :width 75% +[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu0.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu0.png]] + +#+caption: Sample state after 30 iterations +#+attr_html: :width 75% +[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu30.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu30.png]] + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..976f5aa --- /dev/null +++ b/build.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +set -xe + +gcc -O3 -ggdb3 -std=gnu99 \ + `pkg-config --libs --cflags raylib` -lm \ + -o ./main \ + src/main.c \ + src/cellular-automaton.c \ + src/board.c \ + src/bitarray.c diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..cc53e65 --- /dev/null +++ b/doc/biblio.bib @@ -0,0 +1,13 @@ +@book{WOLFRAM2002, +author = {Стивен Вольфрам}, +title = {Наука нового типа}, +publisher = {Wolfram Media}, +year = {2002}, +pages = {1197} +} +@online{VOSTROV2024, +author = {Востров А. В}, +title = {Теория алгоритмов}, +url = {https://tema.spbstu.ru/algorithm/}, +urldate = {2024-12-01} +} diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty @@ -0,0 +1,57 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\makeatother diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..43447d5 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,23 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, justification=centering, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=above} + +\addto\captionsrussian{\renewcommand{\figurename}{Рис.}} +% \addto\captionsrussian{\renewcommand{\mintedname}{Рис.}} +\addto\captionsrussian{\captionsetup[listing]{name=Рис.}} diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..ee95480 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,44 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother + +% Increment figure counter when using lstlisting +% \let\oldlstlisting\lstlisting +% \renewcommand{\lstlisting}[1][]{% +% \refstepcounter{figure} +% \oldlstlisting[#1] +% } diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..cb2a7f0 --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty @@ -0,0 +1,114 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +\setcounter{secnumdepth}{5} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\centering\Large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing*{\section}{0cm}{0cm}{0.5cm} +\newcommand{\sectionbreak}{\clearpage} + +\titleformat{\subsection}[block]{\Large\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.25cm} + +\titleformat{\subsubsection}[block]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{} +\titlespacing{\subsubsection}{0cm}{0.5em}{0.25cm} + +\titleformat{\paragraph}[block]{\normalsize\bfseries}{\theparagraph}{0.5em}{} +\titlespacing*{\paragraph}{0cm}{0.5em}{0.25cm} + +\titleformat{\subparagraph}[block]{\normalsize\bfseries}{\thesubparagraph}{0.5em}{} +\titlespacing{\subparagraph}{0cm}{0.5em}{0.25cm} + +\makeatletter +\let\oldsection\section +\newcommand{\@sectionnostar}[1]{\oldsection*{#1}\addcontentsline{toc}{section}{#1}} +\newcommand{\@sectionstar}[1]{\oldsection{#1}} +\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} +\makeatother + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..6f41980 --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,17 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} +\setlist[itemize, 3]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} +\setlist[3]{wide=2\parindent} diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..750ab75 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty @@ -0,0 +1,29 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tabularx} + +% +% Center-aligned column with automatic width +% +\newcolumntype{Y}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{Z}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\newcommand{\designation}[2]{#1 &---& #2. \\} diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..328079d --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty @@ -0,0 +1,34 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black, + hidelinks +]{hyperref} + +% +% Set custom font styles +% +\renewcommand{\cftsecfont}{\normalfont} +\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsecpagefont}{\normalsize} +\renewcommand{\cftaftertoctitle}{\hfill\hfill} +\renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +\setlength{\cftbeforesecskip}{0cm} +\setlength{\cftbeforesubsecskip}{0cm} +\setlength{\cftbeforesubsubsecskip}{0cm} +\setlength{\cftbeforeparaskip}{0cm} diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..c13b00e --- /dev/null +++ b/doc/gost/gost-7-32.cls @@ -0,0 +1,62 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\spacing{1.5} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/its.plt b/doc/its.plt new file mode 100644 index 0000000..944674e --- /dev/null +++ b/doc/its.plt @@ -0,0 +1,40 @@ +# -*- Gnuplot -*- +# its.plt --- Plot... + +set term cairolatex pdf input \ + blacktext notransparent nocrop \ + size 12cm,6cm \ + noheader + +set size ratio 0.5 +set lmargin at screen 0.1 +set rmargin at screen 0.9 +set bmargin at screen 0.1 +set tmargin at screen 0.95 + +set output "./res/its.tex" + +set x2label "Номер итерации" +set y2label "Количество «живых» клеток" +unset key +unset grid +# set grid x mx y my +# set grid linestyle 1 palette +# set tics out +# set xtics .5/3**(n), 1./3**(n - 1), 1 - .5/3**(n) +# set ytics .5/3**(n), 1./3**(n - 1), 1 - .5/3**(n) +# set mxtics 3 +# set mytics 3 +# set format x "" +# set format y "" +set xrange [1:400] +set yrange [120:200] + +plot for [i=2:11] "./res/its.dat" using 1:i \ + with lines \ + linetype 1 linewidth 1 linecolor i + +set output "./res/avg.tex" +plot "./res/avg.dat" using 1:2 \ + with lines \ + linetype 1 linewidth 1 linecolor 8 diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..671adce --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,31 @@ +;;; ox-init.el --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +(org-babel-do-load-languages + 'org-babel-load-languages + '((latex . t) + (C . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(setq org-latex-src-block-backend 'minted) + +(require 'oc-bibtex) +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-latex-caption-above '(table src-block)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..bf5439e --- /dev/null +++ b/doc/report.org @@ -0,0 +1,735 @@ +#+title: Двумерный клеточный автомат +#+author: Михалец М. +#+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №1} +#+latex_header: \subject{по дисциплине «Теория алгоритмов»} +#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} +#+latex_header: \institute{Институт компьютерных наук и кибербезопасности} +#+latex_header: \school{Высшая школа технологии искусственного интеллекта} +#+latex_header: \direction{02.03.01 Математика и компьютерные науки} +#+latex_header: \reviewertitle{}\reviewer{Востров А.В.} +#+latex_header: \city{Санкт-Петербург} +#+date: 2024 + +#+latex_header: \newcommand{\overbar}[1]{\mkern1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu} + +#+latex_header: \newcommand{\cellboard}[3]{ +#+latex_header: \begin{tikzpicture}[scale=#2] +#+latex_header: \foreach \x in {0,...,#1} { +#+latex_header: \foreach \y in {0,...,#1} { +#+latex_header: \fill[black] (\x,\y) rectangle (\x+1,\y+1); +#+latex_header: } +#+latex_header: } +#+latex_header: \foreach \x/\y in {#3} { +#+latex_header: \fill[white] (\x,\y) rectangle (\x+1,\y+1); +#+latex_header: } +#+latex_header: \draw[step=1cm, color=gray] (0,0) grid (#1+1,#1+1); +#+latex_header: \end{tikzpicture} +#+latex_header: } + +#+setupfile: setup.org +#+latex: \sloppy + +* ВВЕДЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +Данный отчёт содержит в себе описание лабораторной работы №1 по +дисциплине «Теория Алгоритмов». В задание входили реализация +двумерного клеточного автомата с окрестностью фон Неймана и его +визуализация. В функционале автомата должны присутствовать: +1. Возможность генерации случайного состояния. +2. Возможность ручной настройки состояния. +3. Возможность задания размеров поля. +4. Возможность определения количества итерации. + +Функция рассмотрена в данной работе: *7931880* (=0x007907E8=) + +* Математическое описание +** Клеточный автомат +/Клеточный автомат/ --- это регулярная структура динамических объектов +(клеток), функционирующих синхронно. Клеточные автоматы моделируют +процессы, разворачивающиеся в дискретном пространстве и в дискретном +времени. + +Клеточный автомат имеет состояние, определяемое как набор (вектор или +матрица) состояний компонентных автоматов. Каждый автомат +функционирует как автомат Мура, т.е. это автомат без выхода, выходом +является его состояние. Вход на каждом шаге клеточного автомата +состояния его соседей. На следующем шаге (в следующем такте) новое +состояние каждого автомата определяется как функция его текущего +состояния и текущих состояний его соседей. + +Обычно правила изменения состояний всех автоматов (кроме граничных) +идентичны (однородность системы), множество состояний каждого автомата +--- конечно. Изменение состояния системы во всех клетках происходит +синхронно: состояния клеток меняются одновременно на каждом такте. + +*** Описание функции и тип реализованного клеточного автомата +Для данного варианта была задана функция обновления автомата на новой +итерации: 7931880 (вариант 15) в десятичной системе счисления, +007907E8 в шестнадцатеричной и 0000 0000 0111 1001 0000 0111 1110 1000 +в двоичной. Для получения функции обновления клеточного автомата на +новой итерации была построена таблица истинности, где переменными +являются значения клеток из окрестности фон Неймана. Полученная +таблица истинности приведена в таблице [[truth-table]]. Будем считать, +что значение 1 -- клетка жива, 0 -- клетка мертва. Тогда для +получения состояния клетки на следующей итерации можно воспользоваться +формулой: + +#+begin_export latex +\begin{aligned} + F_{+1} =\,&(\overbar{s_{0}}\overbar{s_{1}}\overbar{s_{2}}s_{3}s_{4}) \lor + (\overbar{s_{0}}\overbar{s_{1}}s_{2}\overbar{s_{3}}s_{4}) \lor + (\overbar{s_{0}}\overbar{s_{1}}s_{2}s_{3}\overbar{s_{4}}) \lor + (\overbar{s_{0}}\overbar{s_{1}}s_{2}s_{3}s_{4})\,\lor\\ + \lor\,&(\overbar{s_{0}}s_{1}\overbar{s_{2}}\overbar{s_{3}}\overbar{s_{4}}) \lor + (\overbar{s_{0}}s_{1}\overbar{s_{2}}\overbar{s_{3}}s_{4}) \lor + (\overbar{s_{0}}s_{1}\overbar{s_{2}}s_{3}\overbar{s_{4}}) \lor + (s_{0}\overbar{s_{1}}\overbar{s_{2}}\overbar{s_{3}}\overbar{s_{4}})\,\lor\\ + \lor\,&(s_{0}\overbar{s_{1}}\overbar{s_{2}}s_{3}s_{4})\,\lor + (s_{0}\overbar{s_{1}}s_{2}\overbar{s_{3}}\overbar{s_{4}}) \lor + (s_{0}\overbar{s_{1}}s_{2}\overbar{s_{3}}s_{4}) \lor + (s_{0}\overbar{s_{1}}s_{2}s_{3}\overbar{s_{4}})\\ +\end{aligned} +#+end_export + +Где: +- $F_{+1}$ --- состояние клетки на следующей итерации +- $s_{0}, s_{1}, s_{2}, s_{3}, s_{4}$ --- состояния клеток из + окрестности фон Неймана на текущей итерации. + +#+name: truth-table +#+caption: Таблица истинности реализованного леточного автомата +#+attr_latex: :align |r|ccccc|c| +|----+---------+---------+---------+---------+---------+----------| +| № | $s_{0}$ | *$s_{1}$* | *$s_{2}$* | *$s_{3}$* | *$s_{4}$* | *$F_{+1}$* | +|----+---------+---------+---------+---------+---------+----------| +| 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| 1 | 0 | 0 | 0 | 0 | 1 | 0 | +| 2 | 0 | 0 | 0 | 1 | 0 | 0 | +|----+---------+---------+---------+---------+---------+----------| +| *3* | *0* | *0* | *0* | *1* | *1* | *1* | +|----+---------+---------+---------+---------+---------+----------| +| 4 | 0 | 0 | 1 | 0 | 0 | 0 | +|----+---------+---------+---------+---------+---------+----------| +| *5* | *0* | *0* | *1* | *0* | *1* | *1* | +| *6* | *0* | *0* | *1* | *1* | *0* | *1* | +| *7* | *0* | *0* | *1* | *1* | *1* | *1* | +| *8* | *0* | *1* | *0* | *0* | *0* | *1* | +| *9* | *0* | *1* | *0* | *0* | *1* | *1* | +| *10* | *0* | *1* | *0* | *1* | *0* | *1* | +|----+---------+---------+---------+---------+---------+----------| +| 11 | 0 | 1 | 0 | 1 | 1 | 0 | +| 12 | 0 | 1 | 1 | 0 | 0 | 0 | +| 13 | 0 | 1 | 1 | 0 | 1 | 0 | +| 14 | 0 | 1 | 1 | 1 | 0 | 0 | +| 15 | 0 | 1 | 1 | 1 | 1 | 0 | +|----+---------+---------+---------+---------+---------+----------| +| *16* | *1* | *0* | *0* | *0* | *0* | *1* | +|----+---------+---------+---------+---------+---------+----------| +| 17 | 1 | 0 | 0 | 0 | 1 | 0 | +| 18 | 1 | 0 | 0 | 1 | 0 | 0 | +|----+---------+---------+---------+---------+---------+----------| +| *19* | *1* | *0* | *0* | *1* | *1* | *1* | +| *20* | *1* | *0* | *1* | *0* | *0* | *1* | +| *21* | *1* | *0* | *1* | *0* | *1* | *1* | +| *22* | *1* | *0* | *1* | *1* | *0* | *1* | +|----+---------+---------+---------+---------+---------+----------| +| 23 | 1 | 0 | 1 | 1 | 1 | 0 | +| 24 | 1 | 1 | 0 | 0 | 0 | 0 | +| 25 | 1 | 1 | 0 | 0 | 1 | 0 | +| 26 | 1 | 1 | 0 | 1 | 0 | 0 | +| 27 | 1 | 1 | 0 | 1 | 1 | 0 | +| 28 | 1 | 1 | 1 | 0 | 0 | 0 | +| 29 | 1 | 1 | 1 | 0 | 1 | 0 | +| 30 | 1 | 1 | 1 | 1 | 0 | 0 | +| 31 | 1 | 1 | 1 | 1 | 1 | 0 | +|----+---------+---------+---------+---------+---------+----------| + +/Окрестность фон Неймана порядка $r$/ --- множество клеток, +манхэттенское расстояние до которых от данной клетки не превышает $r$ +Окрестность фон Неймана порядка $r$ имеет форму ромба и включает в +себя $C_{4,r+1}$ клеток, где $C_{4,n} = n^2 + (n - 1)^2$ --- n-е +центрированное квадратное число. + +В данной работе рассматривается окрестность размера $r = 1$ в +двумерном пространстве. Окрестность фон Неймана порядка $r = 1$ и +расположение переменных функции изображены на рисунке +[[von-neumann-neighborhood]]. + +#+name: von-neumann-neighborhood +#+caption: Окрестность фон Неймана +#+begin_figure +\centering +\begin{tikzpicture} + % Highlight the central cells + \fill[yellow!50] (2, 2) rectangle (3, 3); % s0 + \fill[green!50] (2, 3) rectangle (3, 4); % s1 + \fill[green!50] (2, 1) rectangle (3, 2); % s2 + \fill[green!50] (1, 2) rectangle (2, 3); % s3 + \fill[green!50] (3, 2) rectangle (4, 3); % s4 + + % Draw the grid + \draw[step=1cm, black, thin] (0, 0) grid (5, 5); + + % Add labels to the cells + \node at (2.5, 2.5) {$s_{0}$}; + \node at (2.5, 3.5) {$s_{1}$}; + \node at (2.5, 1.5) {$s_{2}$}; + \node at (1.5, 2.5) {$s_{3}$}; + \node at (3.5, 2.5) {$s_{4}$}; +\end{tikzpicture} +#+end_figure + +Для получения информации о состоянии клеток на следующей итерации из +таблицы истинности берутся значения переменных при значениях функции +равных 1 (выделено жирно в таблице [[truth-table]]) и согласно окрестности +фон Неймана анализируется текущее состояние поля клегочного автомата. +Так, например, для 10-ой строки таблицы истинности данного варианта на +следующей итерации клетка будет жить если: +1. центральная клетка была мертва +2. клетка сверху была жива +3. клетка снизу была мертва +4. клетка слева была жива +5. клетка справа была мертва + +Это одно из условий жизни клетки перечисленных в порождающей функции. +В данном варианте клетка будет жить всего при 12 различных условиях её +окрестности фон Неймана. В остальных 20 случаях клетка на следующей +итерации будет мёртвой. + +Для разрешения граничных случаев было выбрано тороидальное граничное +условие. При этом условии значения выходящие за границы поля берутся +с противоположного границ поля, образуя цикл или «тор». Для +определения значения клеток в граничных условиях можно использовать +формулу: + +#+begin_export latex +\begin{displaymath} + C_{\textrm{тор}}(i, j) = C(i \bmod m, j \bmod n) +\end{displaymath} +#+end_export +где: +- $C_{\textrm{тор}}$ --- состояние клетки на тороидальной плоскости; +- $C(i, j)$ --- состояние клетки с координатами $i,j$; +- $i$ --- индекс строки, $0 \le i < m$; +- $i$ --- индекс столбца, $0 \le i < n$; +- $m$ --- количество клеток в каждом столбце клеточного автомата; +- $n$ --- количество клеток в каждой строке клеточного автомата. + +* Особенности реализации +Проекта реализован тремя основными абстракциями: битовый массив --- +предоставляет интерфейс для работы с отдельными битами массива байтов; +доска --- предоставляет интерфейс для работы с битами битового массива +как будто бы они были расположены на тороидальной плоскости; конечный +автомат --- предоставляет интерфейс продвижения доски к следующему её +состоянию. + +Обработка событий пользователя как и визуализация реализованы подходом +немедленного режима по следующему алгоритму: +1. Инициализация +2. Если приложение должно закрыться, переход к шагу 7. +3. Обработка действий пользователя +4. Обновление собственного состояния +5. Отрисовка кадра +6. Переход к шагу 2. +7. Деинициализация + +Такой вид реализации позволяет симулировать полноэкранную доску +(294000 клеток при разрешений 1366x768) при 20 кадрах (итерациях +автомата) в секунду на процессоре выпущенном в 2012 год (Intel +i5-3320M (4) @ 3.300GHz). + +** Абстракции +*** Битовый массив +~bitarray~ --- абстракция предоставляющая интерфейс для работы с +отдельными битами массива байтов. В ней хранятся: +- ~uint8_t *bytes~ --- указатель на массив байтов; +- ~size_t size~ --- размер выделенной памяти под массив байтов. + +**** Интерфейс +#+begin_src C +struct bitarray { + uint8_t *bytes; + size_t size; +}; + +void bitarray_init (struct bitarray *, size_t bit_count); +void bitarray_free (struct bitarray *); +void bitarray_set (struct bitarray *, size_t index, bool); +bool bitarray_get (struct bitarray *, size_t index); +#+end_src + +**** Функция инициализации +- Вход: :: указатель на структуру битового массива и количество битов + -- его размер. +- Выход: :: инициализированная структура битового массива с выделенной + памятью под хранение указанного количества битов. +#+begin_src C +void +bitarray_init (struct bitarray *bitarray, size_t bit_count) +{ + bitarray->size = CEIL_INT_DIV (bit_count, 8); + bitarray->bytes = calloc (bitarray->size, 1); +} +#+end_src + +**** Функция установки значения бита +- Вход: :: указатель на структуру битового массива, индекс бита и его + требуемое значение. +- Выход: :: изменена структура битового массива с указанным значением + установленным на указанном индексе. +#+begin_src C +void +bitarray_set (struct bitarray *bitarray, size_t index, bool value) +{ + ASSERT (bitarray); + ASSERT (bitarray->bytes); + ASSERT (index >> 3 < bitarray->size); + setbit (bitarray->bytes, index, value); +} +#+end_src +где функция ~setbit~ определена следующим образом: +- Вход: :: указатель на массив байтов, индекс бита и его требуемое + значение. +- Выход: :: изменена массив байтов с указанным значением установленным + на указанном индексе. +#+begin_src C +inline void +setbit (uint8_t *bytes, size_t index, bool value) +{ + uint8_t *byte = &bytes[index >> 3]; + uint8_t offset = index & ((1 << 3) - 1); + uint8_t mask = ~(1 << offset); + ,*byte = *byte & mask | value << offset; +} +#+end_src + +**** Функция получения значения бита +- Вход: :: указатель на структуру битового массива и индекс бита. +- Выход: :: значение бита битового массива на указанном индексе. +#+begin_src C +bool +bitarray_get (struct bitarray *bitarray, size_t index) +{ + ASSERT (bitarray); + ASSERT (bitarray->bytes); + ASSERT (index >> 3 < bitarray->size); + return getbit (bitarray->bytes, index); +} +#+end_src +где функция ~getbit~ определена следующим образом: +- Вход: :: указатель на массив байтов и индекс бита. +- Выход: :: значение бита массива байтом на указанном индексе. +#+begin_src C +inline bool +getbit (uint8_t *bytes, size_t index) +{ + uint8_t byte = bytes[index >> 3]; + uint8_t offset = index & ((1 << 3) - 1); + uint8_t mask = 1 << offset; + return (byte & mask) >> offset; +} +#+end_src + +**** Функция освобождения памяти +- Вход: :: указатель на структуру битового массива. +- Выход: :: структура битовой массив без выделенной памяти. +#+begin_src C +void +bitarray_free (struct bitarray *bitarray) +{ + FREE (bitarray->bytes); +} +#+end_src + +*** Доска +~board~ --- абстракция предоставляющая интерфейс для работы с битами +битового массива как будто бы это были клетки расположены на +тороидальной плоскости. В ней хранятся: +- ~struct bitarray cells~ --- битовый массив хранящий состояния клеток доски; +- ~uint32_t rows~ --- количество строк доски; +- ~uint32_t cols~ --- количество столбцов доски. + +**** Интерфейс +#+begin_src C +struct board { + struct bitarray cells; + uint32_t rows; + uint32_t cols; +}; + +void board_init (struct board *, uint32_t rows, uint32_t cols); +void board_free (struct board *); +void board_set (struct board *, int32_t row, int32_t col, bool); +bool board_get (struct board *, int32_t row, int32_t col); +#+end_src + +**** Функция инициализации +- Вход: :: указатель на структуру доски, количество строк и столбцов. +- Выход: :: инициализированная доска с выделенной памятью под указанное + количество строк и столбцов. +#+begin_src C +void +board_init (struct board *board, uint32_t rows, uint32_t cols) +{ + bitarray_init (&board->cells, rows*cols); + board->rows = rows; + board->cols = cols; +} +#+end_src + +**** Функция установления значения клетки +- Вход: :: указатель на структуру доски, индексы строки и столбца + клетки, и устанавливаемое значение. +- Выход: :: структура доски с установленным указанным значением в + указанной клетке. +#+begin_src C +void +board_set (struct board *board, int32_t row, int32_t col, bool value) +{ + ASSERT (board); + + row = MOD (row, (int32_t) board->rows); + col = MOD (col, (int32_t) board->cols); + bitarray_set (&board->cells, row*board->cols + col, value); +} +#+end_src + +**** Функция извлечения значения клетки +- Вход: :: указатель на структуру доски, индексы строки и столбца + клетки. +- Выход: :: значение указанной клетки. +#+begin_src C +bool +board_get (struct board *board, int32_t row, int32_t col) +{ + ASSERT (board); + + row = MOD (row, (int32_t) board->rows); + col = MOD (col, (int32_t) board->cols); + return bitarray_get (&board->cells, row*board->cols + col); +} +#+end_src + +**** Функция освобождения памяти +- Вход: :: указатель на структуру доски. +- Выход: :: структура доски без выделенной памяти. +#+begin_src C +void +board_free (struct board *board) +{ + bitarray_free (&board->cells); +} +#+end_src + +*** Клеточный автомат +~cellular_automaton~ --- абстракция предоставляющая интерфейс +продвижения доски к следующему её состоянию. В ней хранятся: +- ~struct board board~ --- доска; +- ~uint8_t *back_board_bitarray~ --- фоновая память для хранения + промежуточного результата при переходе к следующему состоянию; +- ~uint32_t function~ --- функция перехода к следующему состоянию, + представлена в виде 32 битовой строки. + +**** Интерфейс +#+begin_src C +struct cellular_automaton { + struct board board; + uint8_t *back_board_bitarray; + uint32_t function; +}; + +void cellular_automaton_init (struct cellular_automaton *, + uint32_t function, + uint32_t rows, uint32_t cols); +void cellular_automaton_free (struct cellular_automaton *); +void cellular_automaton_progress (struct cellular_automaton *); +#+end_src + +**** Функция инициализации +- Вход: :: указатель на структуру клеточного автомата, функция , + количество строк и столбцов. +- Выход: :: инициализированная доска с выделенной памятью под указанное + количество строк и столбцов. +#+begin_src C +void +cellular_automaton_init (struct cellular_automaton *cellular_automaton, + uint32_t function, uint32_t rows, uint32_t cols) +{ + board_init (&cellular_automaton->board, rows, cols); + cellular_automaton->back_board_bitarray = + malloc (cellular_automaton->board.bitarray.size); + cellular_automaton->function = function; +} +#+end_src + +**** Функция освобождения памяти +- Вход: :: указатель на структуру клеточного автомата. +- Выход: :: структура клеточного автомата без выделенной памяти. +#+begin_src C +void +cellular_automaton_free (struct cellular_automaton *cellular_automaton) +{ + board_free (&cellular_automaton->board); + FREE (cellular_automaton->back_board_bitarray); +} +#+end_src + +**** Функция перехода к следующему состоянию +- Вход: :: указатель на структуру клеточного автомата. +- Выход: :: структура клеточного автомата со значениями клеток доски + продвинутыми к их следующим состояниям. +#+begin_src C +void +cellular_automaton_progress (struct cellular_automaton *cellular_automaton) +{ + for (int32_t row = 0; row < cellular_automaton->board.rows; ++row) { + for (int32_t col = 0; col < cellular_automaton->board.cols; ++col) { + struct board *board = &cellular_automaton->board; + uint8_t state = + board_get (board, row - 1, col + 0) << 1 | + board_get (board, row + 0, col - 1) << 3 | + board_get (board, row + 0, col + 0) << 4 | + board_get (board, row + 0, col + 1) << 2 | + board_get (board, row + 1, col + 0) << 0; + + setbit (cellular_automaton->back_board_bitarray, + row*board->cols + col, + cellular_automaton->function >> state & 1); + } + } + + SWAP (cellular_automaton->back_board_bitarray, + cellular_automaton->board.bitarray.cells); +} +#+end_src + +** Обработка действий пользователя и отрисовки кадра +Из-за громоздкости функции выполнения обработки действий пользователя, +отрисовки экрана и прочих функции (например инициализации и +деинициализации окна) и их сравнительно незначимому отношению к данной +работе, приводится лишь их исходный код в приложении [[*ПРИЛОЖЕНИЕ А][А]]. + +* Результаты работы программы +На рис. [[open]]-[[gnu30]] представлены снимки окна работы программы +клеточного автомата с полем $620 \times 400$ клеток. + +При открытий сразу получаете заполненную случайным образом доску и на +экран выводятся справочная информация о доступных горячих клавишах +(см. Рис. [[open]]). + +#+name: open +#+caption: Вид программы при запуска +[[./res/open.png]] + +Дальше можно закрыть окно со справочной информацией, нажав на клавишу +=h=, и запустить симуляцию нажав на клавишу =SPC= (см. Рис. [[rand-it100]]). +По умолчанию будет программа переходить к следующему состоянию +периодически каждых 0.5с, этот параметр можно настроить кр учением +колечка мыши. Сверху также отображается рабочая итерация и количество +сохраненных состояний, между которыми можно передвигаться при +остановленной симуляции (повторно нажав =SPC=) используя клавиши =LEFT= и +=RIGHT=. В любой момент можно курсоров рисовать на доске -- при нажатой +левой (правой) кнопке мыши клетка становится живой (мёртвой) +(см. Рис. [[cool]]). Доску можно очистить нажав на клавишу =c=. Размер +доски и также используемую функцию перехода к следующему состоянию +можно изменить интуитивно, нажав на нужное поле на верхней панели и +набрав нужное значение. + +#+name: rand-it100 +#+caption: 100-ое состояние при доске заполеной случайно, используя нормальное распределение +[[./res/rand-it100.png]] + +#+name: cool +#+caption: Пример изменения состояния клеток доски пользователем в реальном времени +[[./res/cool.png]] + +#+name: gnu +#+caption: Пример состояния установленного пользователем +#+begin_figure +\centering +#+name: gnu0 +#+caption: Начальное состояние +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure +\centering +[[./res/gnu0.png]] +#+end_subfigure + +\vskip 1cm + +#+name: gnu30 +#+caption: 30-ое состояние +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure +\centering +[[./res/gnu30.png]] +#+end_subfigure +#+end_figure + +* Анализ работы клеточного автомата +** Паттерны +В ходе анализа клеточного автомата был обнаружено явно выраженный +вертикальный паттерн горизонтального сечения треугольника Серпинского. +Вручную изменяя доску во времени можно получить друг за другом +последовательные его сечения, если между столбцами удерживать +расстояние в 2 клетки, иначе паттерн превратится в псевдо-случайный +шум (см. Рис. [[cool]]). + +** Классификация по типам поведения +Проанализировав работу данного клеточного автомата можно прийти к +выводу, что он относится к типу *псевдо-случайных* или к *классу 3* +[cite:см. @WOLFRAM2002 с. 1197]. Результатом эволюции почти всех +начальных условий являются псевдо-случайные, хаотические +последовательности. Любые стабильные структуры, которые возникают +почти сразу же уничтожаются окружающим их шумом. Локальные изменения +в начальных условиях оказывают неопределяемое влияние на ход эволюции +системы. + +На Рис. [[it0]]-[[it5]] представлены состояния доски последовательной эволюции +клеточного автомата. По изображениям видно, что после нескольких +итераций изначальная картина так и остается псвевдо-случайной. + +Было проведено 20 экспериментов с размером доски $20 \times 20$ и 400 +интерациями для проверки и демонстрации псевдо-случайности, построены +график изменения количества «живых» клеток (равных единице) +относительно номера итерации для каждого эксперимента Рис. [[itsc]] и +график апроксимирующей функции данных экспериментов Рис. [[avgc]]. + +#+name: figs +#+caption: Графики изменения количества «живых» клеток относительно итерации +#+attr_latex: :options [h!] +#+begin_figure +\centering +#+name: itsc +#+caption: Графики 20 экспериментов +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure +\centering +\input{./res/its.tex} +#+end_subfigure + +#+name: avgc +#+caption: График среднего значения при 20 экспериментах +#+attr_latex: :options [b]{\textwidth} +#+begin_subfigure +\centering +\input{./res/avg.tex} +#+end_subfigure +#+end_figure + +#+name: its +#+caption: Последовательные итерации работы клеточного автомата +#+begin_figure +#+name: it0 +#+caption: Исходное состояние +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/0, 0/1, 0/2, 0/5, 1/0, 1/3, 2/1, 2/2, 2/4, 2/5, 3/0, 3/3, 3/5, 3/6, 4/3, 4/5, 5/3, 6/3, 6/5, 6/6} +#+end_subfigure +#+name: it1 +#+caption: Состояние после 1-ой итерации +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/0, 0/1, 0/2, 0/5, 1/0, 2/1, 2/2, 2/4, 2/5, 3/0, 3/1, 3/6, 4/0, 4/4, 4/5, 4/6, 5/6, 6/1, 6/2, 6/3, 6/4, 6/5, 6/6} +#+end_subfigure + +#+name: it2 +#+caption: Состояние после 2-ой итерации +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/0, 0/3, 0/5, 1/0, 1/4, 2/1, 2/2, 2/3, 2/4, 2/5, 3/2, 3/6, 4/1, 4/4, 4/5, 5/0, 5/1, 5/2, 5/3, 6/0, 6/1, 6/3, 6/4} +#+end_subfigure +#+name: it3 +#+caption: Состояние после 3-ой итерации +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/1, 0/3, 0/6, 1/0, 1/2, 2/1, 2/3, 2/5, 3/2, 3/3, 4/0, 4/3, 4/4, 4/5, 4/6, 5/0, 5/2, 5/3, 5/5, 6/4} +#+end_subfigure + +#+name: it4 +#+caption: Состояние после 4-ой итерации +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/0, 0/2, 0/4, 1/5, 2/4, 3/0, 3/2, 3/6, 4/0, 4/4, 4/6, 5/0, 5/1, 5/2, 5/5, 6/0, 6/1, 6/2, 6/5, 6/6} +#+end_subfigure +#+name: it5 +#+caption: Состояние после 5-ой итерации +#+attr_latex: :options [b]{.5\textwidth} +#+begin_subfigure +\centering +\cellboard{6}{1}{0/0, 0/2, 0/3, 1/0, 1/2, 2/0, 2/2, 2/5, 2/6, 3/0, 3/1, 3/6, 4/5, 5/2, 6/4, 6/6} +#+end_subfigure +#+end_figure + +** Сходимость +С графиков эксперимента представленного на Рис. [[figs]] также видно, что +при случайном начальном заполнений и размером доски $20 \times 20$ +количество «живых» клеток варирует около $165 \pm 10$. + +* ЗАКЛЮЧЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +В результате работы был реализован и визуализирован клеточный автомат +с окрестностью фон Неймана обеспечивающий: +1. Возможность генерации случайного состояния. +2. Возможность ручной настройки состояния. +3. Возможность задания размеров поля. +4. Возможность определения количества итерации. + +Клеточный автомат реализованный в данной работе принадлежит к типу +*псевдо-случайных* или к *классу 3* [cite:@WOLFRAM2002]. Были выбраны +тороидальные граничные условия. + +Код лабораторной работы был написан в продвинутом, расширяемом, +настраиваемом и самодокументирующемся редакторе --- GNU/Emacs 29.4, на +языке программирования Си (=gnu99=), используя библиотеку Raylib 5.0 для +управления окном. + +*Достоинства:* +- Высокая производительность реализации (см. п. [[*Особенности + реализации]]). +- Графическая реализация проекта. +- Интуитивное и оперативное управление, позволяющее быстро и + занимательно находить интересные узоры. + +*Недостатки:* +- Параметры программы настраиваются макросами в заголовочном файле во + время сборки, а не загружаются во время работы программы (напр. из + аргументов командной строки). +- Отсутствие выбора окрестности и граничных условий. + +*Масштабируемость:* +- Можно расширить возможности кисти, добавить горячие клавиши, + распределения для случайного заполнения доски и т.д. для улучшения + развлекательного фактора. +- Можно реализовать систему загрузочных модулей, для удобного + расширения программы пользователями, например для сохранения + состоянии автомата в файл в нестандартном формате. + +* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ +:PROPERTIES: +:UNNUMBERED: t +:END: +#+latex: \nocite{VOSTROV2024} +#+print_bibliography: :heading none + +* ПРИЛОЖЕНИЕ А +:PROPERTIES: +:UNNUMBERED: t +:END: +#+attr_latex: +#+include: "../src/main.c" src C + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..247ca4b --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,30 @@ +#+options: ':nil *:t -:t ::t <:t H:4 \n:nil ^:{} arch:headline +#+options: author:t broken-links:nil c:nil creator:nil +#+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+options: timestamp:nil title:t toc:t todo:t |:t + +#+select_tags: export +#+exclude_tags: noexport + +#+bibliography: biblio.bib +#+cite_export: biblatex + +#+latex_compiler: xelatex +#+latex_class: spbstu-report +# #+latex_class_options: [draft] + +#+latex_header: \usepackage{enumitem} + +#+latex_header: \usepackage[newfloat]{minted} +#+latex_header: \usemintedstyle{bw} +#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors} + +#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} + +#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+latex_header: \setmainfont{Times New Roman} +#+latex_header: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff] + +#+latex_header: \usepackage{tikz} +#+latex_header: \usepackage{pgfplots} diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..7ae6b05 --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,74 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{adjustbox} +\RequirePackage{setspace} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} +\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} +\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} +\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{\@university} + + \vspace{0.5cm} + \normalsize{\@institute} + + \normalsize{\@school} + + \normalsize{Направление \@direction} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20102 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{\@city, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/doc/task.org b/doc/task.org new file mode 100644 index 0000000..2b9dec8 --- /dev/null +++ b/doc/task.org @@ -0,0 +1,14 @@ +#+title: Лабораторная работа 1 + +Реализовать двумерный клеточный автомат с окрестностью фон Неймана в +соответствии с полученным номером №. Граничный условия предложить +самостоятельно (торроидальные, нулевые, единичные). Пользователь +определяет ширину поля и количество итераций. Необходимо учесть +возможность ввода различных начальных условий (как вручную, так и +случайным образом) по выбору пользователя. Реализация возможна в +консоли или в графике. В итоге необходимо проанализировать свой +клеточный автомат в отчете (его поведение, паттерны, "сходимость" и +т.д.). + +№ = номер варианта * 11 * год рождения * день * месяц = src_elisp{(* +15 11 2003 12 2)} {{{results(=7931880=)}}} diff --git a/src/bitarray.c b/src/bitarray.c new file mode 100644 index 0000000..5d7c1e3 --- /dev/null +++ b/src/bitarray.c @@ -0,0 +1,33 @@ +#include "board.h" +#include "utils.h" + +void +bitarray_init (struct bitarray *bitarray, size_t bit_count) +{ + bitarray->size = (bit_count + 7)/8; + bitarray->bytes = calloc (bitarray->size, 1); +} + +void +bitarray_set (struct bitarray *bitarray, size_t index, bool value) +{ + ASSERT (bitarray); + ASSERT (bitarray->bytes); + ASSERT (index >> 3 < bitarray->size); + setbit (bitarray->bytes, index, value); +} + +bool +bitarray_get (struct bitarray *bitarray, size_t index) +{ + ASSERT (bitarray); + ASSERT (bitarray->bytes); + ASSERT (index >> 3 < bitarray->size); + return getbit (bitarray->bytes, index); +} + +void +bitarray_free (struct bitarray *bitarray) +{ + FREE (bitarray->bytes); +} diff --git a/src/bitarray.h b/src/bitarray.h new file mode 100644 index 0000000..934b84e --- /dev/null +++ b/src/bitarray.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_BITARRAY_H +#define INCLUDED_BITARRAY_H + +#include +#include +#include + +struct bitarray { + uint8_t *bytes; + size_t size; +}; + +void bitarray_init (struct bitarray *, size_t bit_count); +void bitarray_free (struct bitarray *); +void bitarray_set (struct bitarray *, size_t index, bool); +bool bitarray_get (struct bitarray *, size_t index); + +#endif diff --git a/src/board.c b/src/board.c new file mode 100644 index 0000000..fe798f7 --- /dev/null +++ b/src/board.c @@ -0,0 +1,36 @@ +#include "board.h" +#include "utils.h" + +void +board_init (struct board *board, uint32_t rows, uint32_t cols) +{ + bitarray_init (&board->bitarray, rows*cols); + board->rows = rows; + board->cols = cols; +} + +void +board_set (struct board *board, int32_t row, int32_t col, bool value) +{ + ASSERT (board); + + row = MOD (row, (int32_t) board->rows); + col = MOD (col, (int32_t) board->cols); + bitarray_set (&board->bitarray, row*board->cols + col, value); +} + +bool +board_get (struct board *board, int32_t row, int32_t col) +{ + ASSERT (board); + + row = MOD (row, (int32_t) board->rows); + col = MOD (col, (int32_t) board->cols); + return bitarray_get (&board->bitarray, row*board->cols + col); +} + +void +board_free (struct board *board) +{ + bitarray_free (&board->bitarray); +} diff --git a/src/board.h b/src/board.h new file mode 100644 index 0000000..7ce113e --- /dev/null +++ b/src/board.h @@ -0,0 +1,19 @@ +#ifndef INCLUDED_BOARD_H +#define INCLUDED_BOARD_H + +#include +#include +#include "bitarray.h" + +struct board { + struct bitarray bitarray; + uint32_t rows; + uint32_t cols; +}; + +void board_init (struct board *, uint32_t rows, uint32_t cols); +void board_free (struct board *); +void board_set (struct board *, int32_t row, int32_t col, bool); +bool board_get (struct board *, int32_t row, int32_t col); + +#endif diff --git a/src/cellular-automaton.c b/src/cellular-automaton.c new file mode 100644 index 0000000..183684a --- /dev/null +++ b/src/cellular-automaton.c @@ -0,0 +1,49 @@ +#include +#include "cellular-automaton.h" +#include "utils.h" + +void +cellular_automaton_init (struct cellular_automaton *cellular_automaton, + uint32_t function, uint32_t rows, uint32_t cols) +{ + board_init (&cellular_automaton->board, rows, cols); + cellular_automaton->back_board_bitarray = + malloc (cellular_automaton->board.bitarray.size); + cellular_automaton->function = function; +} + +void +cellular_automaton_progress (struct cellular_automaton *cellular_automaton) +{ + // uint32_t alive = 0; + for (int32_t row = 0; row < cellular_automaton->board.rows; ++row) { + for (int32_t col = 0; col < cellular_automaton->board.cols; ++col) { + struct board *board = &cellular_automaton->board; + uint8_t state = + board_get (board, row - 1, col + 0) << 3 | + board_get (board, row + 0, col - 1) << 1 | + board_get (board, row + 0, col + 0) << 0 | + board_get (board, row + 0, col + 1) << 2 | + board_get (board, row + 1, col + 0) << 4; + + // if (board_get (board, row, col)) { + // // printf ("%d/%d, ", row, col); + // ++alive; + // } + + setbit (cellular_automaton->back_board_bitarray, + row*board->cols + col, + cellular_automaton->function >> state & 1); + } + } // printf ("%u\n", alive); + + SWAP (cellular_automaton->back_board_bitarray, + cellular_automaton->board.bitarray.bytes); +} + +void +cellular_automaton_free (struct cellular_automaton *cellular_automaton) +{ + board_free (&cellular_automaton->board); + free (cellular_automaton->back_board_bitarray); +} diff --git a/src/cellular-automaton.h b/src/cellular-automaton.h new file mode 100644 index 0000000..8be8951 --- /dev/null +++ b/src/cellular-automaton.h @@ -0,0 +1,19 @@ +#ifndef INCLUDED_CELLULAR_AUTOMATON_H +#define INCLUDED_CELLULAR_AUTOMATON_H + +#include +#include "board.h" + +struct cellular_automaton { + struct board board; + uint8_t *back_board_bitarray; + uint32_t function; +}; + +void cellular_automaton_init (struct cellular_automaton *, + uint32_t function, + uint32_t rows, uint32_t cols); +void cellular_automaton_free (struct cellular_automaton *); +void cellular_automaton_progress (struct cellular_automaton *); + +#endif diff --git a/src/config.h b/src/config.h new file mode 100644 index 0000000..e93a9d4 --- /dev/null +++ b/src/config.h @@ -0,0 +1,52 @@ +#ifndef INCLUDED_CONFIG_H +#define INCLUDED_CONFIG_H + +#define INITIAL_WINDOW_WIDTH 900 +#define INITIAL_WINDOW_HEIGHT 600 +#define INITIAL_WINDOW_TITLE "Двумерный клеточный автомат с окрестностью фон Неймана" + +#define INITIAL_CELLULAR_AUTOMATON_FUNCTION ((uint32_t) 0x7907E8) +#define INITIAL_CELLULAR_AUTOMATON_BOARD_COLS 735 +#define INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS 400 +// #define INITIAL_CELLULAR_AUTOMATON_BOARD_COLS 620 +// #define INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS 400 + +#define INITIAL_IS_RANDOM true + +#define INITIAL_TICK_RATE 0 //1./2 +#define TICK_RATE_CHANGE_SPEED 1./100 +#define TICK_RATE_CHANGE_SPEED_MULTIPLIER 10 + +#define BACKGROUND_COLOR BLACK + +#define INITIAL_IS_PAUSED true +#define INITIAL_IS_GRID_SHOWN false +#define INITIAL_IS_HELP_SHOWN true + +#define AFTER_CLEAR_IS_PAUSED true + +#define GRID_THICKNESS 1 +#define GRID_COLOR GRAY + +#define CELL_COLOR_ALIVE WHITE +#define CELL_COLOR_DEAD BACKGROUND_COLOR + +#define TEXT_SPACING 2 + +#define INFOBAR_FONT_SIZE 20 +#define INFOBAR_HEIGHT 20 +#define INFOBAR_COLOR_TEXT WHITE +#define INFOBAR_COLOR_TEXT_EDITING RED +#define INFOBAR_COLOR_BACKGROUND DARKBLUE +#define INFOBAR_COLOR_OUTLINE BLUE +#define INFOBAR_TEXT_PAUSED "*PAUSED*" + +#define HELP_TITLE "HELP" +#define HELP_FONT_SIZE_HEADING 28 +#define HELP_FONT_SIZE_POINT 22 +#define HELP_PADDING 20 +#define HELP_COLOR_TEXT ((Color) { 0xDF, 0x00, 0x00, 0xFF }) +#define HELP_COLOR_BACKGROUND ((Color) { 0x2F, 0x00, 0x00, 0xDF }) +#define HELP_COLOR_OUTLINE ((Color) { 0xFF, 0x00, 0x00, 0xFF }) + +#endif diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..726fcce --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,59 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..89741da --- /dev/null +++ b/src/main.c @@ -0,0 +1,576 @@ +// src/main.c --- entry point and window management +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "dynamic-array.h" +#include "cellular-automaton.h" + +static struct cellular_automaton cellular_automaton; + +static float cell_size = 0; +static Rectangle board_bounding_box = {0}; +static Font font; + +static float tick_rate = INITIAL_TICK_RATE; +static float time_from_last_udpate = 0; + +static bool is_paused = INITIAL_IS_PAUSED; +static bool is_grid_shown = INITIAL_IS_GRID_SHOWN; +static bool is_help_shown = INITIAL_IS_HELP_SHOWN; + +static uint8_t *transient_iteration_bytes; +static size_t iteration; +static struct { + uint8_t *items; + uint32_t count; + uint32_t capacity; +} iterations = {0}; + +#define TEXT_SIZE_FUNCTION 9 +static char text_function[TEXT_SIZE_FUNCTION]; +static bool text_function_is_editing = false; + +#define TEXT_SIZE_COLS 4 +static char text_cols[TEXT_SIZE_COLS]; +static bool text_cols_is_editing = false; + +#define TEXT_SIZE_ROWS 4 +static char text_rows[TEXT_SIZE_ROWS]; +static bool text_rows_is_editing = false; + +static void +init (void) +{ + srand (time (NULL)); + + cellular_automaton_init (&cellular_automaton, + INITIAL_CELLULAR_AUTOMATON_FUNCTION, + INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS, + INITIAL_CELLULAR_AUTOMATON_BOARD_COLS); + if (INITIAL_IS_RANDOM) { + for (uint32_t row = 0; row < cellular_automaton.board.rows; ++row) { + for (uint32_t col = 0; col < cellular_automaton.board.cols; ++col) { + board_set (&cellular_automaton.board, row, col, rand () % 2); + } + } + } + + DYNAMIC_ARRAY_APPEND_MANY (iterations, + cellular_automaton.board.bitarray.bytes, + cellular_automaton.board.bitarray.size); + iteration = 0; + if (INITIAL_IS_PAUSED) + transient_iteration_bytes = cellular_automaton.board.bitarray.bytes; + + SetConfigFlags (FLAG_MSAA_4X_HINT | + FLAG_WINDOW_RESIZABLE | + FLAG_FULLSCREEN_MODE | + FLAG_VSYNC_HINT); + + // InitWindow (INITIAL_WINDOW_WIDTH, + // INITIAL_WINDOW_HEIGHT, + // INITIAL_WINDOW_TITLE); + InitWindow (0, 0, INITIAL_WINDOW_TITLE); + + font = GetFontDefault (); + + snprintf (text_function, TEXT_SIZE_FUNCTION, "%08X", cellular_automaton.function); + snprintf (text_cols, TEXT_SIZE_COLS, "%u", cellular_automaton.board.cols); + snprintf (text_rows, TEXT_SIZE_ROWS, "%u", cellular_automaton.board.rows); +} + +static void +deinit (void) +{ + CloseWindow (); + cellular_automaton_free (&cellular_automaton); +} + +static void +handel_input (void) +{ + if (IsKeyPressed (KEY_SPACE)) { + if (is_paused) { + is_paused = false; + cellular_automaton.board.bitarray.bytes = transient_iteration_bytes; + memcpy (cellular_automaton.board.bitarray.bytes, + &iterations.items[iteration*cellular_automaton.board.bitarray.size], + cellular_automaton.board.bitarray.size); + iterations.count = (iteration + 1)*cellular_automaton.board.bitarray.size; + } else { + is_paused = true; + transient_iteration_bytes = cellular_automaton.board.bitarray.bytes; + memcpy (&iterations.items[iteration*cellular_automaton.board.bitarray.size], + cellular_automaton.board.bitarray.bytes, + cellular_automaton.board.bitarray.size); + } + } + + if (IsKeyPressed (KEY_F1) || IsKeyPressed (KEY_H)) + is_help_shown = !is_help_shown; + + if (is_help_shown && IsKeyPressed (KEY_Q)) + is_help_shown = false; + + if (IsKeyPressed (KEY_G)) + is_grid_shown = !is_grid_shown; + + if (IsKeyPressed (KEY_C) && !text_function_is_editing) { + if (is_paused) + cellular_automaton.board.bitarray.bytes = transient_iteration_bytes; + memset (cellular_automaton.board.bitarray.bytes, 0, + cellular_automaton.board.bitarray.size); + DYNAMIC_ARRAY_RESET (iterations); + DYNAMIC_ARRAY_APPEND_MANY (iterations, + cellular_automaton.board.bitarray.bytes, + cellular_automaton.board.bitarray.size); + iteration = 0; + is_paused = AFTER_CLEAR_IS_PAUSED; + if (is_paused) + transient_iteration_bytes = cellular_automaton.board.bitarray.bytes; + } + + if (is_paused) { + int change = 0; + change += GetMouseWheelMove () > 0 || + IsKeyPressed (KEY_N) || IsKeyPressed (KEY_RIGHT) || + IsKeyDown (KEY_LEFT_SHIFT) && (IsKeyDown (KEY_N) || + IsKeyDown (KEY_RIGHT)); + change -= GetMouseWheelMove () < 0 || + IsKeyPressed (KEY_P) || IsKeyPressed (KEY_LEFT) || + IsKeyDown (KEY_LEFT_SHIFT) && (IsKeyDown (KEY_P) || + IsKeyDown (KEY_LEFT)); + if (change < 0 && iteration >= -change || + change > 0 && (iteration + change <= + (iterations.count - 1) / + cellular_automaton.board.bitarray.size)) + iteration += change; + cellular_automaton.board.bitarray.bytes = + &iterations.items[iteration*cellular_automaton.board.bitarray.size]; + } else { + tick_rate = fmaxf (tick_rate + + TICK_RATE_CHANGE_SPEED*GetMouseWheelMove () * + (1 + (TICK_RATE_CHANGE_SPEED_MULTIPLIER - 1) * + IsKeyDown (KEY_LEFT_SHIFT)), 0); + } + + enum cell_action { + CELL_ACTION_NONE = 0b00, + CELL_ACTION_KILL = 0b01, + CELL_ACTION_RESURRECT = 0b10, + } cell_action = CELL_ACTION_NONE; + + if (!text_function_is_editing && + !text_cols_is_editing && + !text_rows_is_editing) { + if (IsMouseButtonDown (MOUSE_LEFT_BUTTON)) + cell_action = CELL_ACTION_RESURRECT; + else if (IsMouseButtonDown (MOUSE_RIGHT_BUTTON)) + cell_action = CELL_ACTION_KILL; + } + + if (cell_action) { + Vector2 mouse = GetMousePosition (); + if (CheckCollisionPointRec (mouse, board_bounding_box)) { + uint32_t row = (mouse.y - board_bounding_box.y)/cell_size; + uint32_t col = (mouse.x - board_bounding_box.x)/cell_size; + board_set (&cellular_automaton.board, row, col, cell_action >> 1 & 1); + } + } +} + +static void +update (void) +{ + cell_size = fminf ( + (GetScreenHeight () - INFOBAR_HEIGHT)/(float) cellular_automaton.board.rows, + (GetScreenWidth () )/(float) cellular_automaton.board.cols); + board_bounding_box.width = cell_size*cellular_automaton.board.cols; + board_bounding_box.height = cell_size*cellular_automaton.board.rows; + board_bounding_box.x = (GetScreenWidth () - board_bounding_box.width )/2.; + board_bounding_box.y = (GetScreenHeight () - board_bounding_box.height + INFOBAR_HEIGHT)/2.; + + time_from_last_udpate += GetFrameTime (); + if (!is_paused && time_from_last_udpate >= tick_rate) { + time_from_last_udpate = 0; + + cellular_automaton_progress (&cellular_automaton); + DYNAMIC_ARRAY_APPEND_MANY (iterations, + cellular_automaton.board.bitarray.bytes, + cellular_automaton.board.bitarray.size); + iteration += 1; + } +} + +static void +draw_fps (int x, int y, float font_size) +{ + DrawTextEx (font, TextFormat ("%2i FPS", GetFPS ()), (Vector2) { x, y }, + font_size, TEXT_SPACING, INFOBAR_COLOR_TEXT); +} + +static void +draw_infobar (void) +{ + DrawRectangle (0, 0, GetScreenWidth (), INFOBAR_HEIGHT, INFOBAR_COLOR_BACKGROUND); + DrawRectangleLines (0, 0, GetScreenWidth (), INFOBAR_HEIGHT, INFOBAR_COLOR_OUTLINE); + + draw_fps (3, 1, INFOBAR_FONT_SIZE); + + if (is_paused) { + Vector2 text_center = Vector2Scale (MeasureTextEx ( + font, INFOBAR_TEXT_PAUSED, + INFOBAR_FONT_SIZE, TEXT_SPACING), .5); + text_center.y -= 1; + Vector2 infobar_center = { GetScreenWidth ()/2., INFOBAR_HEIGHT/2. }; + DrawTextEx (font, INFOBAR_TEXT_PAUSED, Vector2Subtract (infobar_center, text_center), + INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT); + } + + { + Vector2 head = { GetScreenWidth () - 3, 1 }; + { + Vector2 text_size = MeasureTextEx (font, text_function, INFOBAR_FONT_SIZE, TEXT_SPACING); + head.x -= text_size.x; + if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) || + IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) { + Rectangle bounding_box = { + .x = head.x, + .y = head.y, + .width = text_size.x, + .height = text_size.y, + }; + if (CheckCollisionPointRec (GetMousePosition (), bounding_box)) + text_function_is_editing = true; + else + text_function_is_editing = false; + sscanf (text_function, "%X", &cellular_automaton.function); + } + + if (text_function_is_editing) { + if (IsKeyPressed (KEY_ENTER)) { + text_function_is_editing = false; + sscanf (text_function, "%X", &cellular_automaton.function); + } else { + int key; + while (text_function[0] == '0' && + (key = toupper (GetCharPressed ()))) { + if ('0' <= key && key <= '9' || + 'A' <= key && key <= 'F') { + char last_char; + for (int i = 0; i < TEXT_SIZE_FUNCTION - 2; ++i) { + last_char = text_function[i]; + text_function[i] = text_function[i + 1]; + } text_function[TEXT_SIZE_FUNCTION - 2] = key; + } + } + + if (IsKeyPressed (KEY_BACKSPACE)) { + if (IsKeyDown (KEY_CAPS_LOCK)) { + memset (text_function, '0', TEXT_SIZE_FUNCTION - 1); + } else { + char last_char = '0'; + for (int i = 0; i < TEXT_SIZE_FUNCTION - 1; ++i) { + char tmp = text_function[i]; + text_function[i] = last_char; + last_char = tmp; + } + } + } + } + } + + DrawTextEx (font, text_function, head, INFOBAR_FONT_SIZE, TEXT_SPACING, + text_function_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT); + } + head.x -= MeasureTextEx (font, " | 0x", INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING; + DrawTextEx (font, " | 0x", head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT); + + bool resize = false; + if ((text_cols_is_editing || text_rows_is_editing) && + IsKeyPressed (KEY_TAB)) { + text_cols_is_editing = !text_cols_is_editing; + text_rows_is_editing = !text_rows_is_editing; + } + + { + Vector2 text_size = MeasureTextEx (font, text_rows, INFOBAR_FONT_SIZE, TEXT_SPACING); + head.x -= text_size.x; + if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) || + IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) { + Rectangle bounding_box = { + .x = head.x, + .y = head.y, + .width = text_size.x, + .height = text_size.y, + }; + if (CheckCollisionPointRec (GetMousePosition (), bounding_box)) + text_rows_is_editing = true; + else { + if (text_rows_is_editing) { + resize = true; + text_rows_is_editing = false; + } + } + } + + if (text_rows_is_editing) { + if (IsKeyPressed (KEY_ENTER)) { + text_rows_is_editing = false; + resize = true; + } else { + int key; + size_t len; + while ((len = strlen (text_rows)) < TEXT_SIZE_ROWS - 1 && + (key = GetCharPressed ())) { + if ('0' <= key && key <= '9') { + if (text_rows[0] == '0') { + text_rows[0] = key; + } else { + text_rows[len] = key; + text_rows[len + 1] = '\0'; + } + } + } + + if (IsKeyPressed (KEY_BACKSPACE)) { + if (IsKeyDown (KEY_CAPS_LOCK) || len == 1) { + text_rows[0] = '0'; + text_rows[1] = '\0'; + } else { + text_rows[len - 1] = '\0'; + } + } + } + } + + DrawTextEx (font, text_rows, head, INFOBAR_FONT_SIZE, TEXT_SPACING, + text_rows_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT); + } + head.x -= MeasureTextEx (font, "x", INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING; + DrawTextEx (font, "x", head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT); + { + Vector2 text_size = MeasureTextEx (font, text_cols, INFOBAR_FONT_SIZE, TEXT_SPACING); + head.x -= text_size.x + TEXT_SPACING; + if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) || + IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) { + Rectangle bounding_box = { + .x = head.x, + .y = head.y, + .width = text_size.x, + .height = text_size.y, + }; + if (CheckCollisionPointRec (GetMousePosition (), bounding_box)) + text_cols_is_editing = true; + else { + if (text_cols_is_editing) { + resize = true; + text_cols_is_editing = false; + } + } + } + + if (text_cols_is_editing) { + if (IsKeyPressed (KEY_ENTER)) { + text_cols_is_editing = false; + resize = true; + } else { + int key; + size_t len; + while ((len = strlen (text_cols)) < TEXT_SIZE_COLS - 1 && + (key = GetCharPressed ())) { + if ('0' <= key && key <= '9') { + if (text_cols[0] == '0') { + text_cols[0] = key; + } else { + text_cols[len] = key; + text_cols[len + 1] = '\0'; + } + } + } + + if (IsKeyPressed (KEY_BACKSPACE)) { + if (IsKeyDown (KEY_CAPS_LOCK) || len == 1) { + text_cols[0] = '0'; + text_cols[1] = '\0'; + } else { + text_cols[len - 1] = '\0'; + } + } + } + } + + DrawTextEx (font, text_cols, head, INFOBAR_FONT_SIZE, TEXT_SPACING, + text_cols_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT); + } + + if (resize) { + uint32_t rows, cols; + sscanf (text_rows, "%u", &rows); + sscanf (text_cols, "%u", &cols); + + if (rows != cellular_automaton.board.rows || + cols != cellular_automaton.board.cols) { + if (is_paused) + cellular_automaton.board.bitarray.bytes = transient_iteration_bytes; + board_free (&cellular_automaton.board); + board_init (&cellular_automaton.board, rows, cols); + DYNAMIC_ARRAY_RESET (iterations); + DYNAMIC_ARRAY_APPEND_MANY (iterations, + cellular_automaton.board.bitarray.bytes, + cellular_automaton.board.bitarray.size); + iteration = 0; + is_paused = INITIAL_IS_PAUSED; + if (is_paused) + transient_iteration_bytes = cellular_automaton.board.bitarray.bytes; + } + } + + const char *text_rest = TextFormat ( + "%u/%u | %.2fs | ", + iteration + 1, iterations.count/cellular_automaton.board.bitarray.size, + tick_rate, + cellular_automaton.board.rows); + head.x -= MeasureTextEx (font, text_rest, INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING; + DrawTextEx (font, text_rest, head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT); + } +} + +static void +draw_heading (Vector2 *head, const char *heading) +{ + DrawTextEx (font, heading, *head, + HELP_FONT_SIZE_HEADING, TEXT_SPACING, HELP_COLOR_TEXT); + head->y += HELP_FONT_SIZE_HEADING; +} + +static void +draw_point (Vector2 *head, const char *lhs, const char *rhs) +{ + DrawTextEx (font, lhs, Vector2Add (*head, (Vector2) { 1*HELP_PADDING, 0 }), + HELP_FONT_SIZE_POINT, TEXT_SPACING, HELP_COLOR_TEXT); + DrawTextEx (font, rhs, Vector2Add (*head, (Vector2) { 7*HELP_FONT_SIZE_POINT, 0 }), + HELP_FONT_SIZE_POINT, TEXT_SPACING, HELP_COLOR_TEXT); + head->y += HELP_FONT_SIZE_POINT; +} + +static void +draw_help (void) +{ + Rectangle bounding_box = { + .x = .1*GetScreenWidth (), + .y = .1*GetScreenHeight () + INFOBAR_HEIGHT, + .width = .8*GetScreenWidth (), + .height = .8*(GetScreenHeight () - INFOBAR_HEIGHT), + }; + + DrawRectangleRec (bounding_box, HELP_COLOR_BACKGROUND); + DrawRectangleLinesEx (bounding_box, 1, HELP_COLOR_OUTLINE); + + Vector2 head = { bounding_box.x + HELP_PADDING, + bounding_box.y + HELP_PADDING - 3 }; + Vector2 offset_point = { 1*HELP_PADDING, 0 }; + Vector2 offset_description = { 7*HELP_FONT_SIZE_POINT, 0 }; + draw_heading (&head, "General:"); + draw_point (&head, "- F1, H", "Show this help window."); + draw_point (&head, "- Q", "Quit any transient window."); + draw_point (&head, "- SPC", "Pause/Unpause."); + draw_point (&head, "- G", "Toggle grid display."); + draw_point (&head, "- C", "Clear automaton's state."); + draw_point (&head, "- LMB", "Make cell under cursor alive."); + draw_point (&head, "- RMB", "Make cell under cursor dead."); + draw_point (&head, "- SHIFT", "Make adjustments faster."); + head.y += HELP_FONT_SIZE_HEADING; + draw_heading (&head, "Running:"); + draw_point (&head, "- SCROLL", "Adjust tick rate."); + head.y += HELP_FONT_SIZE_HEADING; + draw_heading (&head, "Paused:"); + draw_point (&head, "- SCROLL", "Move between states."); + draw_point (&head, "- P, LEFT", "Move to previous state."); + draw_point (&head, "- N, RIGHT", "Move to next state."); +} + +static void +draw (void) +{ + BeginDrawing (); { + ClearBackground (BACKGROUND_COLOR); + + draw_infobar (); + + Rectangle rec = { + .x = board_bounding_box.x, + .y = board_bounding_box.y, + .width = cell_size, + .height = cell_size, + }; + for (uint32_t row = 0; row < cellular_automaton.board.rows; ++row) { + for (uint32_t col = 0; col < cellular_automaton.board.cols; ++col) { + DrawRectangleRec (rec, + board_get (&cellular_automaton.board, row, col) + ? CELL_COLOR_ALIVE + : CELL_COLOR_DEAD); + rec.x += cell_size; + } + rec.x = board_bounding_box.x; + rec.y += cell_size; + } + + DrawRectangleLinesEx (board_bounding_box, GRID_THICKNESS, GRID_COLOR); + if (is_grid_shown) { + Vector2 line_begin; + Vector2 line_end; + + line_begin = (Vector2) { + board_bounding_box.x, + board_bounding_box.y + cell_size, + }; + line_end = (Vector2) { + board_bounding_box.x + board_bounding_box.width, + board_bounding_box.y + cell_size, + }; + for (uint32_t i = 0; i < cellular_automaton.board.rows - 1; ++i) { + DrawLineEx (line_begin, line_end, GRID_THICKNESS, GRID_COLOR); + line_begin.y += cell_size; + line_end.y += cell_size; + } + + line_begin = (Vector2) { + board_bounding_box.x + cell_size, + board_bounding_box.y, + }; + line_end = (Vector2) { + board_bounding_box.x + cell_size, + board_bounding_box.y + board_bounding_box.height, + }; + for (uint32_t i = 0; i < cellular_automaton.board.cols - 1; ++i) { + DrawLineEx (line_begin, line_end, GRID_THICKNESS, GRID_COLOR); + line_begin.x += cell_size; + line_end.x += cell_size; + } + } + + if (is_help_shown) draw_help (); + } EndDrawing (); +} + +int +main (int argc, char *argv[]) +{ + init (); + while (!WindowShouldClose ()) { + handel_input (); + update (); + draw (); + } deinit (); + return EXIT_SUCCESS; +} diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..d5a1242 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,65 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#ifdef DEBUG +#define FREE(PTR) ({free (PTR); PTR = NULL;}) +#define ASSERT assert +#else +#define FREE free +#define ASSERT +#endif + +#define CEIL_INT_DIV(A, B) ((A + (B - 1))/B) +// #define CEIL_INT_DIV(A, B) (1 + (A - 1)/B) // A != 0 + +#define MOD(A, B) (((A % B) + B) % B) + +#define SWAP(A, B) \ + ({ \ + typeof (A) tmp = A; \ + A = B; \ + B = tmp; \ + }) + +#define MIN(A, B) \ + ({ \ + typeof (A) a = A; \ + typeof (B) b = B; \ + a < b ? a : b; \ + }) \ + +inline void +setbit (uint8_t *bytes, size_t index, bool value) +{ + uint8_t *byte = &bytes[index >> 3]; + uint8_t offset = index & ((1 << 3) - 1); + uint8_t mask = ~(1 << offset); + *byte = *byte & mask | value << offset; +} + +inline bool +getbit (uint8_t *bytes, size_t index) +{ + uint8_t byte = bytes[index >> 3]; + uint8_t offset = index & ((1 << 3) - 1); + uint8_t mask = 1 << offset; + return (byte & mask) >> offset; +} + +inline void +prompt (char *label, char *fmt, void *where) +{ + printf ("%s: ", label); + scanf (fmt, where); + while (getchar () != '\n'); +} + +#endif -- cgit v1.3.1