text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
# Windows ����ڸ� ���� ML-Agents Toolkit ��ġ ��� ML-Agents toolkit�� Windows 10�� �����մϴ�. �ٸ� ������ Windows ���ε� ML-Agents toolkit�� ����� �� ������ �������� �ʾҽ��ϴ�. ����, ML-Agents toolkit�� Windows VM(Bootcamp �Ǵ� ���� ó�� ȯ�� ����)�� ��� ���� �������� �ʾҽ��ϴ� . ML-Agents toolkit�� ����ϱ� ����, �Ʒ��� ����Ȱ� ó�� Python�� �䱸�Ǵ� Python ��Ű���� ��ġ�ؾ� �մϴ�. �� ���̵�� ���� GPU ��� �н�(�����ڸ� ����)�� ���� ���� ����� �ٷ�ϴ�. ����, ML-Agents toolkit�� ���� GPU ��� �н��� �ʿ����� ������ ���� ���� �Ǵ� Ư�� ���׿� �ʿ��� �� �ֽ��ϴ�. ## �ܰ� 1: Anaconda�� ���� Python ��ġ Windows ������ Anaconda�� [�ٿ�ε�](https://www.anaconda.com/download/#windows)�ϰ� ��ġ�Ͻʽÿ�. Anaconda�� ��������ν�, �ٸ� ���� ������ Python�� �и��� ȯ�濡�� ������ �� �ֽ��ϴ�. Python 2�� ���̻� �������� �ʱ� ������ Python 3.10�� �ʿ��մϴ�. �� ���̵忡�� �츮�� Python 3.10.12 ������ Anaconda 5.1 ������ ����� ���Դϴ�. ([64-bit](https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86_64.exe) �Ǵ� [32-bit](https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86.exe) ��ũ). <p align="center"> <img src="images/anaconda_install.PNG" alt="Anaconda Install" width="500" border="10" /> </p> ����Ʈ _advanced installation options_�� �����ϴ� ���� ��õ������ ��Ȳ�� ���� ������ �ɼ��� �����Ͻʽÿ�. <p align="center"> <img src="images/anaconda_default.PNG" alt="Anaconda Install" width="500" border="10" /> </p> ��ġ �Ŀ� �ݵ�� __Anaconda Navigator__ �� ���� ������ �Ϸ��ؾ� �մϴ�. Windows Ž�� â����, _anaconda navigator_ �� Ÿ�����Ͽ� Anaconda Navigator �� �� �� �ֽ��ϴ�. ȯ�� ������ �����Ǿ����� �ʴٸ� `conda` ��ɾ Ÿ�������� �� "conda is not recognized as internal or external command" ��� ������ ���� ���Դϴ�. �̸� �ذ��ϱ� ���� ��Ȯ�� ȯ�� ���� ������ �ʿ��մϴ�. Ž�� â���� `ȯ�� ����`�� Ÿ���� �Ͽ� (������ Ű�� �����ų� ���� �Ʒ� ������ ��ư�� ���� �� �� �ֽ��ϴ�). __�ý��� ȯ�� ���� ����__ �ɼ��� �ҷ��ɴϴ�. <p align="center"> <img src="images/edit_env_var_kr.png" alt="edit env variables" width="250" border="10" /> </p> �� �ɼǿ��� __ȯ�� ����__ ��ư�� Ŭ���ϰ�. �Ʒ� __�ý��� ����__���� "Path" ������ ���� Ŭ���ϰ� __���� �����__�� Ŭ���Ͽ� ���� �� path�� �߰��Ͻʽÿ�. ```console %UserProfile%\Anaconda3\Scripts %UserProfile%\Anaconda3\Scripts\conda.exe %UserProfile%\Anaconda3 %UserProfile%\Anaconda3\python.exe ``` ## �ܰ� 2: ���ο� Conda ȯ�� ���� �� Ȱ��ȭ ML-Agents toolkit�� �Բ� ����� ���ο� [Conda ȯ��](https://conda.io/docs/)�� ���� ���Դϴ�. �� �۾��� ��ġ�� ��� ��Ű���� �� ȯ�濡�� ���ѵȴٴ� ���� �ǹ��մϴ�. �̴� �ٸ� ȯ���̳� �ٸ� ���̽� ��ġ�� ������ ��ġ�� �ʽ��ϴ�. ML-Agents�� ������ ������ �׻� Conda ȯ���� Ȱ��ȭ ���Ѿ� �մϴ�. ���ο� Conda ȯ���� ����� ����, ���ο� Anaconda ������Ʈ(Ž�� â���� _Anaconda Prompt_�� Ŭ��)�� ���� ���� ��ɾ Ÿ���� �Ͻʽÿ�: ```sh conda create -n ml-agents python=3.10.12 ``` �� ��Ű���� ��ġ�ϱ� ���� �޼����� ���� ��� `y`�� Ÿ�����ϰ� ���͸� �����ʽÿ� _(���ͳ��� ����Ǿ��ִ��� Ȯ���Ͻʽÿ�)_. �� �䱸�Ǵ� ��Ű������ �ݵ�� ��ġ�ؾ� �մϴ�. ���ο� Conda ȯ�濡�� Python 3.10.12 ������ ���Ǹ� ml-agents�� ȣ��˴ϴ�. <p align="center"> <img src="images/conda_new.PNG" alt="Anaconda Install" width="500" border="10" /> </p> �ռ� ���� ȯ���� �̿��ϱ� ���� �ݵ�� Ȱ��ȭ�� �ؾ��մϴ�. _(���Ŀ� ���� ��ɾ� ���� ȯ���� ������ �� �ֽ��ϴ�)_. ���� Anaconda ������Ʈ���� ���� ��ɾ Ÿ���� �Ͻʽÿ�: ```sh activate ml-agents ``` Ȱ��ȭ �Ŀ� `(ml-agents)`��� ���ڰ� ������ �� �տ� ��Ÿ���� ���� �� �� �ֽ��ϴ�. ��������, `tensorflow`�� ��ġ�մϴ�. ���̽� ��Ű���� ��ġ�ϱ� ���� ����ϴ� `pip`��� ��Ű�� ���� �ý��۸� ����Ͽ� ��ġ�� �� �ֽ��ϴ�. �ֽ� ������ TensorFlow�� �۵����� ���� �� �����Ƿ�, ��ġ ������ 1.7.1���� Ȯ���ؾ� �մϴ�. ���� Anaconda ������Ʈ â���� ���� ��ɾ Ÿ���� �Ͻʽÿ�._(���ͳ��� ����Ǿ� �ִ��� Ȯ���Ͽ� �ֽʽÿ�)_: ```sh pip install tensorflow==1.7.1 ``` ## �ܰ� 3: �ʼ� ���̽� ��Ű�� ��ġ ML-Agents toolkit�� ���� ���̽� ��Ű���� �������Դϴ�. `pip`�� ����Ͽ� �� ���̽� ���Ӽ����� ��ġ�Ͻʽÿ�. ML-Agents Toolkit ����� ����Ұ� ���� ��ǻ�Ϳ� �����Ǿ����� �ʾҴٸ� �����Ͻʽÿ�. Git�� ([�ٿ�ε�](https://git-scm.com/download/win))�ϰ� �����Ų �� ���� ��ɾ Anaconda ������Ʈâ�� �Է��Ͽ� ������ �� �ֽ��ϴ�. _(���� �� ������Ʈ â�� �����ִٸ� `activate ml-agents`�� Ÿ�����Ͽ� ml-agents Conda ȯ���� Ȱ��ȭ �Ǿ��ִ��� Ȯ���Ͻʽÿ�)_: ```sh git clone https://github.com/Unity-Technologies/ml-agents.git ``` ���� Git�� ����ϰ� ���� �ʴٸ� ������ [��ũ](https://github.com/Unity-Technologies/ml-agents/archive/main.zip)���� ��� ������ �ٿ�ε� �� �� �ֽ��ϴ�. `UnitySDK` ���� ���丮���� ������Ʈ�� �߰��� ����Ƽ �ּ��� ���ԵǾ� �ֽ��ϴ�. ���� �����ϴµ� ������ �Ǵ� ���� [���� ȯ��](Learning-Environment-Examples.md)���� �ֽ��ϴ�. `ml-agents` ���� ���丮���� ����Ƽ ȯ��� �԰� ����ϴ� ���� ��ȭ�н� Ʈ���̳� ���̽� ��Ű���� ���ԵǾ� �ֽ��ϴ�. `ml-agents-envs` ���� ���丮���� `ml-agents` ��Ű���� ���ӵǴ� ����Ƽ�� �������̽��� ���� ���̽� API�� ���ԵǾ� �ֽ��ϴ�. `gym-unity` ���� ���丮���� OpenAI Gym�� �������̽��� ���� ��Ű���� ���ԵǾ� �ֽ��ϴ�. `mlagents-learn`�� ������ �� Ʈ���̳��� ȯ�� ���� ������ �� ���丮 �ȿ� �ʿ��ϹǷ�, ������ �ٿ�ε� �� ���丮�� ��ġ�� ����Ͻʽÿ�. ���ͳ��� ����Ǿ����� Ȯ���ϰ� Anaconda ������Ʈ���� ���� ��ɾ Ÿ���� �Ͻʽÿ�t: ```console pip install mlagents ``` ML-Agents toolkit�� ������ �� �ʿ��� ��� ���̽� ��Ű���� ��ġ�� �Ϸ��� ���Դϴ�. Windows���� ���� pip�� ����Ͽ� Ư�� ���̽� ��Ű���� ��ġ�� �� ��Ű���� ij���� �д� ���� ���� ���� �ֽ��ϴ�. ������ ���� ������ �ذ��� �� �� �ֽ��ϴ�: ```console pip install mlagents --no-cache-dir ``` `--no-cache-dir`�� pip���� ij���� ��Ȱ��ȭ �Ѵٴ� ���Դϴ�. ### ������ ���� ��ġ ���� `ml-agents` �Ǵ� `ml-agents-envs`�� �����ϰ� �ʹٸ�, PyPi�� �ƴ� ������ ����ҷ� ���� ��Ű���� ��ġ�ؾ� �մϴ�. �̸� ����, `ml-agents` �� `ml-agents-envs` �� ���� ��ġ�ؾ� �մϴ�. �������� ������ `C:\Downloads`�� ��ġ�� �ֽ��ϴ�. ������ �����ϰų� �ٿ�ε��� �� Anaconda ������Ʈ���� ml-agents ���丮 ���� ml-agents ���� ���丮�� �����Ͻʽÿ�: ```console cd C:\Downloads\ml-agents ``` ������� ���� ���丮���� ������ �����Ͻʽÿ�: ```console cd ml-agents-envs pip install -e . cd .. cd ml-agents pip install -e . ``` `-e` �÷��׸� ����Ͽ� pip�� ���� �ϸ� ���̽� ������ ���� ������ �� �ְ� `mlagents-learn`�� ������ �� �ݿ��˴ϴ�. `mlagents` ��Ű���� `mlagents_envs`�� �������̰�, �ٸ� ������ ��ġ�ϸ� PyPi�� ���� `mlagents_envs` �� ��ġ�� �� �ֱ� ������ �� ������� ��Ű���� ��ġ�ϴ� ���� �߿��մϴ�. ## (�ɼ�) Step 4: ML-Agents Toolkit�� ����� GPU �н� ML-Agents toolkit�� ���� GPU�� �ʿ����� ������ �н� �߿� PPO �˰��� �ӵ��� ũ�� ������ ���մϴ�(������ ���Ŀ� GPU�� ������ �� �� �ֽ��ϴ�). �� ���̵�� GPU�� ����� �н��� �ϰ� ���� ��� ����ڸ� ���� ���̵� �Դϴ�. ���� GPU�� CUDA�� ȣȯ�Ǵ��� Ȯ���ؾ� �մϴ�. [����](https://developer.nvidia.com/cuda-gpus) Nvidia ���������� Ȯ���� �ֽʽÿ�. ���� ML-Agents toolkit �� CUDA 9.0 ������ cuDNN 7.0.5 ������ �����˴ϴ�. ### Nvidia CUDA toolkit ��ġ Nvidia ��ī�̺꿡�� CUDA ��Ŷ(toolkit) 9.0�� [�ٿ�ε�](https://developer.nvidia.com/cuda-toolkit-archive)�ϰ� ��ġ�Ͻʽÿ�. ML-Agents toolkit�� �����Ű�� ���� CUDA ��Ŷ�� GPU ���� ���̺귯��, �����-����ȭ ����, C/C++(���־� ��Ʃ��� 2017) �����Ϸ�, ��Ÿ�� ���̺귯���� �����մϴ�. �� ���̵忡���� [9.0.176](https://developer.nvidia.com/compute/cuda/9.0/Prod/network_installers/cuda_9.0.176_win10_network-exe))������ ����մϴ�. ��ġ�ϱ� ��, __���� ���� ����Ƽ �Ǵ� ���־� ��Ʃ����� �����ߴ���__ Ȯ���Ͽ� �ֽʽÿ�. �ν��緯�� �����ϰ� Express �ɼ��� �����Ͻʽÿ�. CUDA ��Ŷ�� ��ġ�� ���丮�� ������ �ֽʽÿ�. �� ���̵忡����, `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0` ��ο� ��ġ�մϴ�. ### Nvidia cuDNN ���̺귯�� ��ġ Nvidia���� cuDNN ���̺귯���� [�ٿ�ε�](https://developer.nvidia.com/cudnn)�ϰ� ��ġ�Ͻʽÿ�. cuDNN�� ���� �Ű���� ���� �⺻�� �Ǵ� GPU ���� ���̺귯��. �ٿ�ε� ���� Nvidia Developer Program�� �����ؾ��� ���Դϴ�(����). <p align="center"> <img src="images/cuDNN_membership_required.png" alt="cuDNN membership required" width="500" border="10" /> </p> �����ϰ� cuDNN [�ٿ�ε� ������](https://developer.nvidia.com/cudnn)�� ���ư��ʽÿ�. ª�� �������翡 �����ؾ� �� ���� �ֽ��ϴ�. When you get to the list cuDNN ������ ����Ʈ���� __�ܰ� 1���� ��ġ�� CUDA ��Ŷ�� �´� ������ �ٿ�ε��ϰ� �ִ��� Ȯ���Ͻʽÿ�.__ �� ���̵忡����, CUDA ��Ŷ 9.0 ������ ���� 7.0.5 ������ ����մϴ� ([�ٿ�ε� ��ũ](https://developer.nvidia.com/compute/machine-learning/cudnn/secure/v7.0.5/prod/9.0_20171129/cudnn-9.0-windows10-x64-v7)). cuDNN ������ �ٿ�ε� �� �Ŀ�, CUDA ��Ŷ ���丮�ȿ� ������ ����(���� ����)�ؾ� �մϴ�. cuDNN zip ���� �ȿ��� ������ ���� `bin`, `include`, �׸��� `lib`�� �ֽ��ϴ�. <p align="center"> <img src="images/cudnn_zip_files.PNG" alt="cuDNN zip files" width="500" border="10" /> </p> �� ������ ������ CUDA ��Ŷ ���丮�ȿ� �����Ͻʽÿ�. CUDA ��Ŷ ���丮�� `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0`�� ��ġ�� �ֽ��ϴ�. <p align="center"> <img src="images/cuda_toolkit_directory.PNG" alt="cuda toolkit directory" width="500" border="10" /> </p> ### ȯ�� ���� ���� 1���� ȯ�� ������ 2���� ��� ������ �߰��ؾ� �մϴ�. ȯ�� ������ �����ϱ� ����, Ž�� â���� `ȯ�� ����`�� Ÿ���� �Ͽ� (������ Ű�� �����ų� ���� �Ʒ� ������ ��ư�� ���� �� �� �ֽ��ϴ�). __�ý��� ȯ�� ���� ����__ �ɼ��� �ҷ��ɴϴ�. <p align="center"> <img src="images/edit_env_var_kr.png" alt="edit env variables" width="250" border="10" /> </p> �� �ɼǿ��� __ȯ�� ����__ ��ư�� Ŭ���ϰ� �ý��� ������ __���� �����__�� Ŭ���Ͻʽÿ� _(����� ������ �ƴ� �Ʒ��� __�ý��� ����__���� Ȯ���Ͻʽÿ�). <p align="center"> <img src="images/new_system_variable_kr.PNG" alt="new system variable" width="500" border="10" /> </p> __���� �̸�__�� `CUDA_HOME`���� �����ϰ� ���� ������ CUDA ��Ŷ ���丮 ��θ� �Է��� �ֽʽÿ�. �� ���̵忡�� ���丮 ��δ� `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0` �Դϴ�. Ȯ�� ��ư�� �����ֽʽÿ�. <p align="center"> <img src="images/system_variable_name_value_kr.PNG" alt="system variable names and values" width="500" border="10" /> </p> 2���� ��� ���� ������ ���� __ȯ�� ����__ â �׸��� �Ʒ� �ι�° �ڽ��� __�ý��� ����__�ȿ���, `Path` ������ ã�� Ŭ���ϰ� __����__��ư�� �����ʽÿ�. ����Ʈ�� 2���� ���丮�� �߰��� ���Դϴ�. �� ���丮�� ������ �����ϴ�: ```console C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib\x64 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\extras\CUPTI\libx64 ``` ���� ���丮 ��ġ�� ��ġ�� ���丮 ������� Ȯ���Ͻʽÿ�. _��ҹ��ڿ� �����Ͻʽÿ�_. <p align="center"> <img src="images/path_variables_kr.PNG" alt="Path variables" width="500" border="10" /> </p> ### TensorFlow GPU ��ġ ����, `pip`�� ����Ͽ� 1.7.1. ���� `tensorflow-gpu`�� ��ġ�Ͻʽÿ� . ml-agents Conda ȯ���� Ȱ��ȭ ��Ų Anaconda ������Ʈ���� CPU�� TensorFlow �����ϰ� GPU�� TensorFlow�� ��ġ�ϱ� ���� ���� ��ɾ Ÿ���� �Ͻʽÿ� _(���ͳ��� ����Ǿ� �ִ��� Ȯ���Ͻʽÿ�)_: ```sh pip uninstall tensorflow pip install tensorflow-gpu==1.7.1 ``` ����������, ��� ���� ����� ��ġ�Ǿ� �ְ�, Tensorflow���� GPU�� �ν��ϰ� �ִ��� �׽�Ʈ�ؾ��մϴ�. ���� Anaconda ������Ʈ���� Python�� ȣ���Ͽ� ���ϴ�: ```sh python ``` �׸��� ���� ��ɾ Ÿ���� �Ͻʽÿ�: ```python import tensorflow as tf sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) ``` ������ ����� ������ �� �� ���� ���Դϴ�: ```console Found device 0 with properties ... ``` ## Acknowledgments �� ���̵带 ����� ���� ���� �ʾ��� �ۼ��� [Jason Weimann](https://unity3d.college/2017/10/25/machine-learning-in-unity3d-setting-up-the-environment-tensorflow-for-agentml-on-windows-10/) �� [Nitish S. Mutha](http://blog.nitishmutha.com/tensorflow/2017/01/22/TensorFlow-with-gpu-for-windows.html) ���� ����帳�ϴ�. ## �ѱ� ���� �ش� ������ �ѱ� ������ [������ (Hyeonjun Jang)]([https://github.com/janghyeonjun](https://github.com/janghyeonjun))�� ���� ����Ǿ����ϴ�. ����� ������ ��Ż�ڰ� �ִ� ��� totok682@naver.com ���� �����ֽø� ����帮�ڽ��ϴ�.
ml-agents/localized_docs/KR/docs/Installation-Anaconda-Windows.md/0
{ "file_path": "ml-agents/localized_docs/KR/docs/Installation-Anaconda-Windows.md", "repo_id": "ml-agents", "token_count": 6174 }
1,899
<jupyter_start><jupyter_text>ML-Agents PettingZoo Wrapper Setup<jupyter_code>#@title Install Rendering Dependencies { display-mode: "form" } #@markdown (You only need to run this code when using Colab's hosted runtime) import os from IPython.display import HTML, display def progress(value, max=100): return HTML(""" <progress value='{value}' max='{max}', style='width: 100%' > {value} </progress> """.format(value=value, max=max)) pro_bar = display(progress(0, 100), display_id=True) try: import google.colab INSTALL_XVFB = True except ImportError: INSTALL_XVFB = 'COLAB_ALWAYS_INSTALL_XVFB' in os.environ if INSTALL_XVFB: with open('frame-buffer', 'w') as writefile: writefile.write("""#taken from https://gist.github.com/jterrace/2911875 XVFB=/usr/bin/Xvfb XVFBARGS=":1 -screen 0 1024x768x24 -ac +extension GLX +render -noreset" PIDFILE=./frame-buffer.pid case "$1" in start) echo -n "Starting virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS echo "." ;; stop) echo -n "Stopping virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE rm $PIDFILE echo "." ;; restart) $0 stop $0 start ;; *) echo "Usage: /etc/init.d/xvfb {start|stop|restart}" exit 1 esac exit 0 """) pro_bar.update(progress(5, 100)) !apt-get install daemon >/dev/null 2>&1 pro_bar.update(progress(10, 100)) !apt-get install wget >/dev/null 2>&1 pro_bar.update(progress(20, 100)) !wget http://security.ubuntu.com/ubuntu/pool/main/libx/libxfont/libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb >/dev/null 2>&1 pro_bar.update(progress(30, 100)) !wget --output-document xvfb.deb http://security.ubuntu.com/ubuntu/pool/universe/x/xorg-server/xvfb_1.18.4-0ubuntu0.12_amd64.deb >/dev/null 2>&1 pro_bar.update(progress(40, 100)) !dpkg -i libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb >/dev/null 2>&1 pro_bar.update(progress(50, 100)) !dpkg -i xvfb.deb >/dev/null 2>&1 pro_bar.update(progress(70, 100)) !rm libxfont1_1.5.1-1ubuntu0.16.04.4_amd64.deb pro_bar.update(progress(80, 100)) !rm xvfb.deb pro_bar.update(progress(90, 100)) !bash frame-buffer start os.environ["DISPLAY"] = ":1" pro_bar.update(progress(100, 100))<jupyter_output><empty_output><jupyter_text>Installing ml-agents<jupyter_code>try: import mlagents print("ml-agents already installed") except ImportError: !git clone -b main --single-branch https://github.com/Unity-Technologies/ml-agents.git !python -m pip install -q ./ml-agents/ml-agents-envs !python -m pip install -q ./ml-agents/ml-agents print("Installed ml-agents")<jupyter_output><empty_output><jupyter_text>Run the Environment List of available environments:* Basic* ThreeDBall* ThreeDBallHard* GridWorld* Hallway* VisualHallway* CrawlerDynamicTarget* CrawlerStaticTarget* Bouncer* SoccerTwos* PushBlock* VisualPushBlock* WallJump* Tennis* Reacher* Pyramids* VisualPyramids* Walker* FoodCollector* VisualFoodCollector* StrikersVsGoalie* WormStaticTarget* WormDynamicTarget Start Environment with PettingZoo Wrapper<jupyter_code># ----------------- # This code is used to close an env that might not have been closed before try: env.close() except: pass # ----------------- import numpy as np from mlagents_envs.envs import StrikersVsGoalie # import unity environment env = StrikersVsGoalie.env()<jupyter_output><empty_output><jupyter_text>Stepping the environmentExample of interacting with the environment in basic RL loop. It follows the same interface as described in [PettingZoo API page](https://pettingzoo.farama.org/api/aec/).<jupyter_code>num_cycles = 10 env.reset() for agent in env.agent_iter(env.num_agents * num_cycles): prev_observe, reward, done, info = env.last() if isinstance(prev_observe, dict) and 'action_mask' in prev_observe: action_mask = prev_observe['action_mask'] if done: action = None else: action = env.action_spaces[agent].sample() # randomly choose an action for example env.step(action)<jupyter_output><empty_output><jupyter_text>Additional Environment APIAll the API described in the `Additional Environment API` section in the [PettingZoo API page](https://pettingzoo.farama.org/api/aec/) are all supported. A few examples are shown below.<jupyter_code># `agents`: a list of the names of all current agents print("Agent names:", env.agents) # `agent_selection`: the currently agent that an action can be taken for. print("Current agent:", env.agent_selection) # `observation_spaces`: a dict of the observation spaces of every agent, keyed by name. print("Observation space of current agent:", env.observation_spaces[env.agent_selection]) # `action_spaces`: a dict of the observation spaces of every agent, keyed by name. print("Action space of current agent:", env.action_spaces[env.agent_selection])<jupyter_output><empty_output><jupyter_text>Close the Environment to free the port it is using<jupyter_code>env.close()<jupyter_output><empty_output>
ml-agents/ml-agents-envs/colabs/Colab_PettingZoo.ipynb/0
{ "file_path": "ml-agents/ml-agents-envs/colabs/Colab_PettingZoo.ipynb", "repo_id": "ml-agents", "token_count": 1931 }
1,900
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from google.protobuf.descriptor import ( EnumDescriptor as google___protobuf___descriptor___EnumDescriptor, ) from google.protobuf.message import ( Message as google___protobuf___message___Message, ) from typing import ( List as typing___List, Tuple as typing___Tuple, cast as typing___cast, ) builtin___int = int builtin___str = str class CommandProto(builtin___int): DESCRIPTOR: google___protobuf___descriptor___EnumDescriptor = ... @classmethod def Name(cls, number: builtin___int) -> builtin___str: ... @classmethod def Value(cls, name: builtin___str) -> 'CommandProto': ... @classmethod def keys(cls) -> typing___List[builtin___str]: ... @classmethod def values(cls) -> typing___List['CommandProto']: ... @classmethod def items(cls) -> typing___List[typing___Tuple[builtin___str, 'CommandProto']]: ... STEP = typing___cast('CommandProto', 0) RESET = typing___cast('CommandProto', 1) QUIT = typing___cast('CommandProto', 2) STEP = typing___cast('CommandProto', 0) RESET = typing___cast('CommandProto', 1) QUIT = typing___cast('CommandProto', 2)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/command_pb2.pyi/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/command_pb2.pyi", "repo_id": "ml-agents", "token_count": 438 }
1,901
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from google.protobuf.descriptor import ( Descriptor as google___protobuf___descriptor___Descriptor, ) from google.protobuf.message import ( Message as google___protobuf___message___Message, ) from mlagents_envs.communicator_objects.unity_rl_initialization_input_pb2 import ( UnityRLInitializationInputProto as mlagents_envs___communicator_objects___unity_rl_initialization_input_pb2___UnityRLInitializationInputProto, ) from mlagents_envs.communicator_objects.unity_rl_input_pb2 import ( UnityRLInputProto as mlagents_envs___communicator_objects___unity_rl_input_pb2___UnityRLInputProto, ) from typing import ( Optional as typing___Optional, ) from typing_extensions import ( Literal as typing_extensions___Literal, ) builtin___bool = bool builtin___bytes = bytes builtin___float = float builtin___int = int class UnityInputProto(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... @property def rl_input(self) -> mlagents_envs___communicator_objects___unity_rl_input_pb2___UnityRLInputProto: ... @property def rl_initialization_input(self) -> mlagents_envs___communicator_objects___unity_rl_initialization_input_pb2___UnityRLInitializationInputProto: ... def __init__(self, *, rl_input : typing___Optional[mlagents_envs___communicator_objects___unity_rl_input_pb2___UnityRLInputProto] = None, rl_initialization_input : typing___Optional[mlagents_envs___communicator_objects___unity_rl_initialization_input_pb2___UnityRLInitializationInputProto] = None, ) -> None: ... @classmethod def FromString(cls, s: builtin___bytes) -> UnityInputProto: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... if sys.version_info >= (3,): def HasField(self, field_name: typing_extensions___Literal[u"rl_initialization_input",u"rl_input"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"rl_initialization_input",u"rl_input"]) -> None: ... else: def HasField(self, field_name: typing_extensions___Literal[u"rl_initialization_input",b"rl_initialization_input",u"rl_input",b"rl_input"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"rl_initialization_input",b"rl_initialization_input",u"rl_input",b"rl_input"]) -> None: ...
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_input_pb2.pyi/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_input_pb2.pyi", "repo_id": "ml-agents", "token_count": 909 }
1,902
import glob import os import subprocess from sys import platform from typing import Optional, List from mlagents_envs.logging_util import get_logger, DEBUG from mlagents_envs.exception import UnityEnvironmentException logger = get_logger(__name__) def get_platform(): """ returns the platform of the operating system : linux, darwin or win32 """ return platform def validate_environment_path(env_path: str) -> Optional[str]: """ Strip out executable extensions of the env_path :param env_path: The path to the executable """ env_path = ( env_path.strip() .replace(".app", "") .replace(".exe", "") .replace(".x86_64", "") .replace(".x86", "") ) true_filename = os.path.basename(os.path.normpath(env_path)) logger.debug(f"The true file name is {true_filename}") if not (glob.glob(env_path) or glob.glob(env_path + ".*")): return None cwd = os.getcwd() launch_string = None true_filename = os.path.basename(os.path.normpath(env_path)) if get_platform() == "linux" or get_platform() == "linux2": candidates = glob.glob(os.path.join(cwd, env_path) + ".x86_64") if len(candidates) == 0: candidates = glob.glob(os.path.join(cwd, env_path) + ".x86") if len(candidates) == 0: candidates = glob.glob(env_path + ".x86_64") if len(candidates) == 0: candidates = glob.glob(env_path + ".x86") if len(candidates) == 0: if os.path.isfile(env_path): candidates = [env_path] if len(candidates) > 0: launch_string = candidates[0] elif get_platform() == "darwin": candidates = glob.glob( os.path.join(cwd, env_path + ".app", "Contents", "MacOS", true_filename) ) if len(candidates) == 0: candidates = glob.glob( os.path.join(env_path + ".app", "Contents", "MacOS", true_filename) ) if len(candidates) == 0: candidates = glob.glob( os.path.join(cwd, env_path + ".app", "Contents", "MacOS", "*") ) if len(candidates) == 0: candidates = glob.glob( os.path.join(env_path + ".app", "Contents", "MacOS", "*") ) if len(candidates) > 0: launch_string = candidates[0] elif get_platform() == "win32": candidates = glob.glob(os.path.join(cwd, env_path + ".exe")) if len(candidates) == 0: candidates = glob.glob(env_path + ".exe") if len(candidates) == 0: # Look for e.g. 3DBall\UnityEnvironment.exe crash_handlers = set( glob.glob(os.path.join(cwd, env_path, "UnityCrashHandler*.exe")) ) candidates = [ c for c in glob.glob(os.path.join(cwd, env_path, "*.exe")) if c not in crash_handlers ] if len(candidates) > 0: launch_string = candidates[0] return launch_string def launch_executable(file_name: str, args: List[str]) -> subprocess.Popen: """ Launches a Unity executable and returns the process handle for it. :param file_name: the name of the executable :param args: List of string that will be passed as command line arguments when launching the executable. """ launch_string = validate_environment_path(file_name) if launch_string is None: raise UnityEnvironmentException( f"Couldn't launch the {file_name} environment. Provided filename does not match any environments." ) else: logger.debug(f"The launch string is {launch_string}") logger.debug(f"Running with args {args}") # Launch Unity environment subprocess_args = [launch_string] + args # std_out_option = DEVNULL means the outputs will not be displayed on terminal. # std_out_option = None is default behavior: the outputs are displayed on terminal. std_out_option = subprocess.DEVNULL if logger.level > DEBUG else None try: return subprocess.Popen( subprocess_args, # start_new_session=True means that signals to the parent python process # (e.g. SIGINT from keyboard interrupt) will not be sent to the new process on POSIX platforms. # This is generally good since we want the environment to have a chance to shutdown, # but may be undesirable in come cases; if so, we'll add a command-line toggle. # Note that on Windows, the CTRL_C signal will still be sent. start_new_session=True, stdout=std_out_option, stderr=std_out_option, ) except PermissionError as perm: # This is likely due to missing read or execute permissions on file. raise UnityEnvironmentException( f"Error when trying to launch environment - make sure " f"permissions are set correctly. For example " f'"chmod -R 755 {launch_string}"' ) from perm
ml-agents/ml-agents-envs/mlagents_envs/env_utils.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/env_utils.py", "repo_id": "ml-agents", "token_count": 2267 }
1,903
from typing import Dict, Iterator, Any, List from collections.abc import Mapping from mlagents_envs.registry.base_registry_entry import BaseRegistryEntry from mlagents_envs.registry.binary_utils import ( load_local_manifest, load_remote_manifest, ) from mlagents_envs.registry.remote_registry_entry import RemoteRegistryEntry class UnityEnvRegistry(Mapping): """ ### UnityEnvRegistry Provides a library of Unity environments that can be launched without the need of downloading the Unity Editor. The UnityEnvRegistry implements a Map, to access an entry of the Registry, use: ```python registry = UnityEnvRegistry() entry = registry[<environment_identifier>] ``` An entry has the following properties : * `identifier` : Uniquely identifies this environment * `expected_reward` : Corresponds to the reward an agent must obtained for the task to be considered completed. * `description` : A human readable description of the environment. To launch a Unity environment from a registry entry, use the `make` method: ```python registry = UnityEnvRegistry() env = registry[<environment_identifier>].make() ``` """ def __init__(self): self._REGISTERED_ENVS: Dict[str, BaseRegistryEntry] = {} self._manifests: List[str] = [] self._sync = True def register(self, new_entry: BaseRegistryEntry) -> None: """ Registers a new BaseRegistryEntry to the registry. The BaseRegistryEntry.identifier value will be used as indexing key. If two are more environments are registered under the same key, the most recentry added will replace the others. """ self._REGISTERED_ENVS[new_entry.identifier] = new_entry def register_from_yaml(self, path_to_yaml: str) -> None: """ Registers the environments listed in a yaml file (either local or remote). Note that the entries are registered lazily: the registration will only happen when an environment is accessed. The yaml file must have the following format : ```yaml environments: - <identifier of the first environment>: expected_reward: <expected reward of the environment> description: | <a multi line description of the environment> <continued multi line description> linux_url: <The url for the Linux executable zip file> darwin_url: <The url for the OSX executable zip file> win_url: <The url for the Windows executable zip file> - <identifier of the second environment>: expected_reward: <expected reward of the environment> description: | <a multi line description of the environment> <continued multi line description> linux_url: <The url for the Linux executable zip file> darwin_url: <The url for the OSX executable zip file> win_url: <The url for the Windows executable zip file> - ... ``` :param path_to_yaml: A local path or url to the yaml file """ self._manifests.append(path_to_yaml) self._sync = False def _load_all_manifests(self) -> None: if not self._sync: for path_to_yaml in self._manifests: if path_to_yaml[:4] == "http": manifest = load_remote_manifest(path_to_yaml) else: manifest = load_local_manifest(path_to_yaml) for env in manifest["environments"]: remote_entry_args = list(env.values())[0] remote_entry_args["identifier"] = list(env.keys())[0] self.register(RemoteRegistryEntry(**remote_entry_args)) self._manifests = [] self._sync = True def clear(self) -> None: """ Deletes all entries in the registry. """ self._REGISTERED_ENVS.clear() self._manifests = [] self._sync = True def __getitem__(self, identifier: str) -> BaseRegistryEntry: """ Returns the BaseRegistryEntry with the provided identifier. BaseRegistryEntry can then be used to make a Unity Environment. :param identifier: The identifier of the BaseRegistryEntry :returns: The associated BaseRegistryEntry """ self._load_all_manifests() if identifier not in self._REGISTERED_ENVS: raise KeyError(f"The entry {identifier} is not present in the registry.") return self._REGISTERED_ENVS[identifier] def __len__(self) -> int: self._load_all_manifests() return len(self._REGISTERED_ENVS) def __iter__(self) -> Iterator[Any]: self._load_all_manifests() yield from self._REGISTERED_ENVS default_registry = UnityEnvRegistry() default_registry.register_from_yaml( "https://storage.googleapis.com/mlagents-test-environments/1.1.0/manifest.yaml" ) # noqa E501
ml-agents/ml-agents-envs/mlagents_envs/registry/unity_env_registry.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/registry/unity_env_registry.py", "repo_id": "ml-agents", "token_count": 1982 }
1,904
import os import sys from setuptools import setup, find_packages from setuptools.command.install import install import mlagents_envs VERSION = mlagents_envs.__version__ EXPECTED_TAG = mlagents_envs.__release_tag__ here = os.path.abspath(os.path.dirname(__file__)) class VerifyVersionCommand(install): """ Custom command to verify that the git tag is the expected one for the release. Originally based on https://circleci.com/blog/continuously-deploying-python-packages-to-pypi-with-circleci/ This differs slightly because our tags and versions are different. """ description = "verify that the git tag matches our version" def run(self): tag = os.getenv("GITHUB_REF", "NO GITHUB TAG!").replace("refs/tags/", "") if tag != EXPECTED_TAG: info = "Git tag: {} does not match the expected tag of this app: {}".format( tag, EXPECTED_TAG ) sys.exit(info) # Get the long description from the README file with open(os.path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="mlagents_envs", version=VERSION, description="Unity Machine Learning Agents Interface", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Unity-Technologies/ml-agents", author="Unity Technologies", author_email="ML-Agents@unity3d.com", classifiers=[ "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Artificial Intelligence", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.10", ], packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests", "colabs", "*.ipynb"] ), zip_safe=False, install_requires=[ "cloudpickle", "grpcio>=1.11.0,<=1.48.2", "Pillow>=4.2.1", "protobuf>=3.6,<3.21", "pyyaml>=3.1.0", "gym>=0.21.0", "pettingzoo==1.15.0", "numpy>=1.23.5,<1.24.0", "filelock>=3.4.0", ], python_requires=">=3.10.1,<=3.10.12", # TODO: Remove this once mypy stops having spurious setuptools issues. cmdclass={"verify": VerifyVersionCommand}, # type: ignore )
ml-agents/ml-agents-envs/setup.py/0
{ "file_path": "ml-agents/ml-agents-envs/setup.py", "repo_id": "ml-agents", "token_count": 931 }
1,905
from typing import Dict, List from mlagents.trainers.settings import RunOptions from mlagents.trainers.stats import StatsWriter, StatsSummary class ExampleStatsWriter(StatsWriter): """ Example implementation of the StatsWriter abstract class. This doesn't do anything interesting, just prints the stats that it gets. """ def write_stats( self, category: str, values: Dict[str, StatsSummary], step: int ) -> None: print(f"ExampleStatsWriter category: {category} values: {values}") def get_example_stats_writer(run_options: RunOptions) -> List[StatsWriter]: """ Registration function. This is referenced in setup.py and will be called by mlagents-learn when it starts to determine the list of StatsWriters to use. It must return a list of StatsWriters. """ print("Creating a new stats writer! This is so exciting!") return [ExampleStatsWriter()]
ml-agents/ml-agents-plugin-examples/mlagents_plugin_examples/example_stats_writer.py/0
{ "file_path": "ml-agents/ml-agents-plugin-examples/mlagents_plugin_examples/example_stats_writer.py", "repo_id": "ml-agents", "token_count": 279 }
1,906
from typing import Dict, Any ML_AGENTS_STATS_WRITER = "mlagents.stats_writer" ML_AGENTS_TRAINER_TYPE = "mlagents.trainer_type" # TODO: the real type is Dict[str, HyperparamSettings] all_trainer_types: Dict[str, Any] = {} all_trainer_settings: Dict[str, Any] = {}
ml-agents/ml-agents/mlagents/plugins/__init__.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/plugins/__init__.py", "repo_id": "ml-agents", "token_count": 105 }
1,907
from typing import Dict, List, Tuple, Optional from mlagents.trainers.settings import ( EnvironmentParameterSettings, ParameterRandomizationSettings, ) from collections import defaultdict from mlagents.trainers.training_status import GlobalTrainingStatus, StatusType from mlagents_envs.logging_util import get_logger logger = get_logger(__name__) class EnvironmentParameterManager: def __init__( self, settings: Optional[Dict[str, EnvironmentParameterSettings]] = None, run_seed: int = -1, restore: bool = False, ): """ EnvironmentParameterManager manages all the environment parameters of a training session. It determines when parameters should change and gives access to the current sampler of each parameter. :param settings: A dictionary from environment parameter to EnvironmentParameterSettings. :param run_seed: When the seed is not provided for an environment parameter, this seed will be used instead. :param restore: If true, the EnvironmentParameterManager will use the GlobalTrainingStatus to try and reload the lesson status of each environment parameter. """ if settings is None: settings = {} self._dict_settings = settings for parameter_name in self._dict_settings.keys(): initial_lesson = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) if initial_lesson is None or not restore: GlobalTrainingStatus.set_parameter_state( parameter_name, StatusType.LESSON_NUM, 0 ) self._smoothed_values: Dict[str, float] = defaultdict(float) for key in self._dict_settings.keys(): self._smoothed_values[key] = 0.0 # Update the seeds of the samplers self._set_sampler_seeds(run_seed) def _set_sampler_seeds(self, seed): """ Sets the seeds for the samplers (if no seed was already present). Note that using the provided seed. """ offset = 0 for settings in self._dict_settings.values(): for lesson in settings.curriculum: if lesson.value.seed == -1: lesson.value.seed = seed + offset offset += 1 def get_minimum_reward_buffer_size(self, behavior_name: str) -> int: """ Calculates the minimum size of the reward buffer a behavior must use. This method uses the 'min_lesson_length' sampler_parameter to determine this value. :param behavior_name: The name of the behavior the minimum reward buffer size corresponds to. """ result = 1 for settings in self._dict_settings.values(): for lesson in settings.curriculum: if lesson.completion_criteria is not None: if lesson.completion_criteria.behavior == behavior_name: result = max( result, lesson.completion_criteria.min_lesson_length ) return result def get_current_samplers(self) -> Dict[str, ParameterRandomizationSettings]: """ Creates a dictionary from environment parameter name to their corresponding ParameterRandomizationSettings. If curriculum is used, the ParameterRandomizationSettings corresponds to the sampler of the current lesson. """ samplers: Dict[str, ParameterRandomizationSettings] = {} for param_name, settings in self._dict_settings.items(): lesson_num = GlobalTrainingStatus.get_parameter_state( param_name, StatusType.LESSON_NUM ) lesson = settings.curriculum[lesson_num] samplers[param_name] = lesson.value return samplers def get_current_lesson_number(self) -> Dict[str, int]: """ Creates a dictionary from environment parameter to the current lesson number. If not using curriculum, this number is always 0 for that environment parameter. """ result: Dict[str, int] = {} for parameter_name in self._dict_settings.keys(): result[parameter_name] = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) return result def log_current_lesson(self, parameter_name: Optional[str] = None) -> None: """ Logs the current lesson number and sampler value of the parameter with name parameter_name. If no parameter_name is provided, the values and lesson numbers of all parameters will be displayed. """ if parameter_name is not None: settings = self._dict_settings[parameter_name] lesson_number = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) lesson_name = settings.curriculum[lesson_number].name lesson_value = settings.curriculum[lesson_number].value logger.info( f"Parameter '{parameter_name}' is in lesson '{lesson_name}' " f"and has value '{lesson_value}'." ) else: for parameter_name, settings in self._dict_settings.items(): lesson_number = GlobalTrainingStatus.get_parameter_state( parameter_name, StatusType.LESSON_NUM ) lesson_name = settings.curriculum[lesson_number].name lesson_value = settings.curriculum[lesson_number].value logger.info( f"Parameter '{parameter_name}' is in lesson '{lesson_name}' " f"and has value '{lesson_value}'." ) def update_lessons( self, trainer_steps: Dict[str, int], trainer_max_steps: Dict[str, int], trainer_reward_buffer: Dict[str, List[float]], ) -> Tuple[bool, bool]: """ Given progress metrics, calculates if at least one environment parameter is in a new lesson and if at least one environment parameter requires the env to reset. :param trainer_steps: A dictionary from behavior_name to the number of training steps this behavior's trainer has performed. :param trainer_max_steps: A dictionary from behavior_name to the maximum number of training steps this behavior's trainer has performed. :param trainer_reward_buffer: A dictionary from behavior_name to the list of the most recent episode returns for this behavior's trainer. :returns: A tuple of two booleans : (True if any lesson has changed, True if environment needs to reset) """ must_reset = False updated = False for param_name, settings in self._dict_settings.items(): lesson_num = GlobalTrainingStatus.get_parameter_state( param_name, StatusType.LESSON_NUM ) next_lesson_num = lesson_num + 1 lesson = settings.curriculum[lesson_num] if ( lesson.completion_criteria is not None and len(settings.curriculum) > next_lesson_num ): behavior_to_consider = lesson.completion_criteria.behavior if behavior_to_consider in trainer_steps: ( must_increment, new_smoothing, ) = lesson.completion_criteria.need_increment( float(trainer_steps[behavior_to_consider]) / float(trainer_max_steps[behavior_to_consider]), trainer_reward_buffer[behavior_to_consider], self._smoothed_values[param_name], ) self._smoothed_values[param_name] = new_smoothing if must_increment: GlobalTrainingStatus.set_parameter_state( param_name, StatusType.LESSON_NUM, next_lesson_num ) self.log_current_lesson(param_name) updated = True if lesson.completion_criteria.require_reset: must_reset = True return updated, must_reset
ml-agents/ml-agents/mlagents/trainers/environment_parameter_manager.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/environment_parameter_manager.py", "repo_id": "ml-agents", "token_count": 3690 }
1,908
# # Unity ML-Agents Toolkit from typing import Dict, Any, Optional, List import os import attr from mlagents.trainers.training_status import GlobalTrainingStatus, StatusType from mlagents_envs.logging_util import get_logger logger = get_logger(__name__) @attr.s(auto_attribs=True) class ModelCheckpoint: steps: int file_path: str reward: Optional[float] creation_time: float auxillary_file_paths: List[str] = attr.ib(factory=list) class ModelCheckpointManager: @staticmethod def get_checkpoints(behavior_name: str) -> List[Dict[str, Any]]: checkpoint_list = GlobalTrainingStatus.get_parameter_state( behavior_name, StatusType.CHECKPOINTS ) if not checkpoint_list: checkpoint_list = [] GlobalTrainingStatus.set_parameter_state( behavior_name, StatusType.CHECKPOINTS, checkpoint_list ) return checkpoint_list @staticmethod def remove_checkpoint(checkpoint: Dict[str, Any]) -> None: """ Removes a checkpoint stored in checkpoint_list. If checkpoint cannot be found, no action is done. :param checkpoint: A checkpoint stored in checkpoint_list """ file_paths: List[str] = [checkpoint["file_path"]] file_paths.extend(checkpoint["auxillary_file_paths"]) for file_path in file_paths: if os.path.exists(file_path): os.remove(file_path) logger.debug(f"Removed checkpoint model {file_path}.") else: logger.debug(f"Checkpoint at {file_path} could not be found.") return @classmethod def _cleanup_extra_checkpoints( cls, checkpoints: List[Dict], keep_checkpoints: int ) -> List[Dict]: """ Ensures that the number of checkpoints stored are within the number of checkpoints the user defines. If the limit is hit, checkpoints are removed to create room for the next checkpoint to be inserted. :param behavior_name: The behavior name whose checkpoints we will mange. :param keep_checkpoints: Number of checkpoints to record (user-defined). """ while len(checkpoints) > keep_checkpoints: if keep_checkpoints <= 0 or len(checkpoints) == 0: break ModelCheckpointManager.remove_checkpoint(checkpoints.pop(0)) return checkpoints @classmethod def add_checkpoint( cls, behavior_name: str, new_checkpoint: ModelCheckpoint, keep_checkpoints: int ) -> None: """ Make room for new checkpoint if needed and insert new checkpoint information. :param behavior_name: Behavior name for the checkpoint. :param new_checkpoint: The new checkpoint to be recorded. :param keep_checkpoints: Number of checkpoints to record (user-defined). """ new_checkpoint_dict = attr.asdict(new_checkpoint) checkpoints = cls.get_checkpoints(behavior_name) checkpoints.append(new_checkpoint_dict) cls._cleanup_extra_checkpoints(checkpoints, keep_checkpoints) GlobalTrainingStatus.set_parameter_state( behavior_name, StatusType.CHECKPOINTS, checkpoints ) @classmethod def track_final_checkpoint( cls, behavior_name: str, final_checkpoint: ModelCheckpoint ) -> None: """ Ensures number of checkpoints stored is within the max number of checkpoints defined by the user and finally stores the information about the final model (or intermediate model if training is interrupted). :param behavior_name: Behavior name of the model. :param final_checkpoint: Checkpoint information for the final model. """ final_model_dict = attr.asdict(final_checkpoint) GlobalTrainingStatus.set_parameter_state( behavior_name, StatusType.FINAL_CHECKPOINT, final_model_dict )
ml-agents/ml-agents/mlagents/trainers/policy/checkpoint_manager.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/policy/checkpoint_manager.py", "repo_id": "ml-agents", "token_count": 1537 }
1,909
from typing import List, Tuple from mlagents_envs.base_env import ObservationSpec, DimensionProperty, ObservationType import pytest import copy import os from mlagents.trainers.settings import ( TrainerSettings, GAILSettings, CuriositySettings, RewardSignalSettings, NetworkSettings, RewardSignalType, ScheduleType, ) from mlagents.trainers.ppo.optimizer_torch import PPOSettings from mlagents.trainers.sac.optimizer_torch import SACSettings from mlagents.trainers.poca.optimizer_torch import POCASettings CONTINUOUS_DEMO_PATH = os.path.dirname(os.path.abspath(__file__)) + "/test.demo" DISCRETE_DEMO_PATH = os.path.dirname(os.path.abspath(__file__)) + "/testdcvis.demo" _PPO_CONFIG = TrainerSettings( trainer_type="ppo", hyperparameters=PPOSettings( learning_rate=5.0e-3, learning_rate_schedule=ScheduleType.CONSTANT, batch_size=16, buffer_size=64, ), network_settings=NetworkSettings(num_layers=1, hidden_units=32), summary_freq=500, max_steps=3000, threaded=False, ) _SAC_CONFIG = TrainerSettings( trainer_type="sac", hyperparameters=SACSettings( learning_rate=5.0e-3, learning_rate_schedule=ScheduleType.CONSTANT, batch_size=8, buffer_init_steps=100, buffer_size=5000, tau=0.01, init_entcoef=0.01, ), network_settings=NetworkSettings(num_layers=1, hidden_units=16), summary_freq=100, max_steps=1000, threaded=False, ) _POCA_CONFIG = TrainerSettings( trainer_type="poca", hyperparameters=POCASettings( learning_rate=5.0e-3, learning_rate_schedule=ScheduleType.CONSTANT, batch_size=16, buffer_size=64, ), network_settings=NetworkSettings(num_layers=1, hidden_units=32), summary_freq=500, max_steps=3000, threaded=False, ) def ppo_dummy_config(): return copy.deepcopy(_PPO_CONFIG) def sac_dummy_config(): return copy.deepcopy(_SAC_CONFIG) def poca_dummy_config(): return copy.deepcopy(_POCA_CONFIG) @pytest.fixture def gail_dummy_config(): return {RewardSignalType.GAIL: GAILSettings(demo_path=CONTINUOUS_DEMO_PATH)} @pytest.fixture def curiosity_dummy_config(): return {RewardSignalType.CURIOSITY: CuriositySettings()} @pytest.fixture def extrinsic_dummy_config(): return {RewardSignalType.EXTRINSIC: RewardSignalSettings()} def create_observation_specs_with_shapes( shapes: List[Tuple[int, ...]] ) -> List[ObservationSpec]: obs_specs: List[ObservationSpec] = [] for i, shape in enumerate(shapes): dim_prop = (DimensionProperty.UNSPECIFIED,) * len(shape) if len(shape) == 2: dim_prop = (DimensionProperty.VARIABLE_SIZE, DimensionProperty.NONE) spec = ObservationSpec( name=f"observation {i} with shape {shape}", shape=shape, dimension_property=dim_prop, observation_type=ObservationType.DEFAULT, ) obs_specs.append(spec) return obs_specs
ml-agents/ml-agents/mlagents/trainers/tests/dummy_config.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/dummy_config.py", "repo_id": "ml-agents", "token_count": 1282 }
1,910
import attr import cattr import pickle import pytest import yaml from typing import Dict, List, Optional from mlagents.trainers.settings import ( RunOptions, TrainerSettings, NetworkSettings, RewardSignalType, RewardSignalSettings, CuriositySettings, EnvironmentSettings, EnvironmentParameterSettings, ConstantSettings, UniformSettings, GaussianSettings, MultiRangeUniformSettings, deep_update_dict, strict_to_cls, ScheduleType, ) from mlagents.trainers.ppo.trainer import PPOSettings, TRAINER_NAME as PPO_TRAINER_NAME from mlagents.trainers.sac.trainer import SACSettings, TRAINER_NAME as SAC_TRAINER_NAME from mlagents.trainers.exception import TrainerConfigError TRAINER_SETTING_TYPES = {"ppo": PPOSettings, "sac": SACSettings} def check_if_different(testobj1: object, testobj2: object) -> None: assert testobj1 is not testobj2 if attr.has(testobj1.__class__) and attr.has(testobj2.__class__): for key, val in attr.asdict(testobj1, recurse=False).items(): if ( isinstance(val, dict) or isinstance(val, list) or attr.has(val) ) and val != {}: # Note: this check doesn't check the contents of mutables. check_if_different(val, attr.asdict(testobj2, recurse=False)[key]) def check_dict_is_at_least( testdict1: Dict, testdict2: Dict, exceptions: Optional[List[str]] = None ) -> None: """ Check if everything present in the 1st dict is the same in the second dict. Excludes things that the second dict has but is not present in the heirarchy of the 1st dict. Used to compare an underspecified config dict structure (e.g. as would be provided by a user) with a complete one (e.g. as exported by RunOptions). """ for key, val in testdict1.items(): if exceptions is not None and key in exceptions: continue assert key in testdict2 if isinstance(val, dict): check_dict_is_at_least(val, testdict2[key]) elif isinstance(val, list): assert isinstance(testdict2[key], list) for _el0, _el1 in zip(val, testdict2[key]): if isinstance(_el0, dict): check_dict_is_at_least(_el0, _el1) else: assert val == testdict2[key] else: # If not a dict, don't recurse into it assert val == testdict2[key] def test_is_new_instance(): """ Verify that every instance of RunOptions() and its subclasses is a new instance (i.e. all factory methods are used properly.) """ check_if_different(RunOptions(), RunOptions()) check_if_different(TrainerSettings(), TrainerSettings()) def test_no_configuration(): """ Verify that a new config will have a PPO trainer with extrinsic rewards. """ blank_runoptions = RunOptions() blank_runoptions.behaviors.set_config_specified(False) assert isinstance(blank_runoptions.behaviors["test"], TrainerSettings) assert isinstance(blank_runoptions.behaviors["test"].hyperparameters, PPOSettings) assert ( RewardSignalType.EXTRINSIC in blank_runoptions.behaviors["test"].reward_signals ) def test_strict_to_cls(): """ Test strict structuring method. """ @attr.s(auto_attribs=True) class TestAttrsClass: field1: int = 0 field2: str = "test" correct_dict = {"field1": 1, "field2": "test2"} assert strict_to_cls(correct_dict, TestAttrsClass) == TestAttrsClass(**correct_dict) incorrect_dict = {"field3": 1, "field2": "test2"} with pytest.raises(TrainerConfigError): strict_to_cls(incorrect_dict, TestAttrsClass) with pytest.raises(TrainerConfigError): strict_to_cls("non_dict_input", TestAttrsClass) def test_deep_update_dict(): dict1 = {"a": 1, "b": 2, "c": {"d": 3}} dict2 = {"a": 2, "c": {"d": 4, "e": 5}} deep_update_dict(dict1, dict2) assert dict1 == {"a": 2, "b": 2, "c": {"d": 4, "e": 5}} def test_trainersettings_structure(): """ Test structuring method for TrainerSettings """ trainersettings_dict = { "trainer_type": SAC_TRAINER_NAME, "hyperparameters": {"batch_size": 1024}, "max_steps": 1.0, "reward_signals": {"curiosity": {"encoding_size": 64}}, } trainer_settings = TrainerSettings.structure(trainersettings_dict, TrainerSettings) # check_trainer_setting_types([trainer_settings], TRAINER_SETTING_TYPES) assert isinstance(trainer_settings.hyperparameters, SACSettings) assert trainer_settings.trainer_type == SAC_TRAINER_NAME assert isinstance(trainer_settings.max_steps, int) assert RewardSignalType.CURIOSITY in trainer_settings.reward_signals # Check invalid trainer type with pytest.raises(TrainerConfigError): trainersettings_dict = { "trainer_type": "puppo", "hyperparameters": {"batch_size": 1024}, "max_steps": 1.0, } TrainerSettings.structure(trainersettings_dict, TrainerSettings) # Check invalid hyperparameter with pytest.raises(TrainerConfigError): trainersettings_dict = { "trainer_type": PPO_TRAINER_NAME, "hyperparameters": {"notahyperparam": 1024}, "max_steps": 1.0, } TrainerSettings.structure(trainersettings_dict, TrainerSettings) # Check non-dict with pytest.raises(TrainerConfigError): TrainerSettings.structure("notadict", TrainerSettings) # Check hyperparameters specified but trainer type left as default. # This shouldn't work as you could specify non-PPO hyperparameters. with pytest.raises(TrainerConfigError): trainersettings_dict = {"hyperparameters": {"batch_size": 1024}} TrainerSettings.structure(trainersettings_dict, TrainerSettings) def test_trainersettingsschedules_structure(): """ Test structuring method for Trainer Settings Schedule """ trainersettings_dict = { "trainer_type": PPO_TRAINER_NAME, "hyperparameters": { "learning_rate_schedule": "linear", "beta_schedule": "constant", }, } trainer_settings = TrainerSettings.structure(trainersettings_dict, TrainerSettings) assert isinstance(trainer_settings.hyperparameters, PPOSettings) assert ( trainer_settings.hyperparameters.learning_rate_schedule == ScheduleType.LINEAR ) assert trainer_settings.hyperparameters.beta_schedule == ScheduleType.CONSTANT assert trainer_settings.hyperparameters.epsilon_schedule == ScheduleType.LINEAR def test_even_checkpoints_structure(): """ Test structuring for even checkpoints """ trainersettings_dict = { "trainer_type": PPO_TRAINER_NAME, "keep_checkpoints": 2, "even_checkpoints": True, "max_steps": 100.0, } trainer_settings = TrainerSettings.structure(trainersettings_dict, TrainerSettings) assert isinstance(trainer_settings.hyperparameters, PPOSettings) assert trainer_settings.checkpoint_interval == 50 def test_default_checkpoint_interval_structure(): """ Test structuring for even checkpoints """ trainersettings_dict = { "trainer_type": PPO_TRAINER_NAME, "keep_checkpoints": 2, "max_steps": 100.0, } trainer_settings = TrainerSettings.structure(trainersettings_dict, TrainerSettings) assert isinstance(trainer_settings.hyperparameters, PPOSettings) assert trainer_settings.checkpoint_interval == 500000 def test_reward_signal_structure(): """ Tests the RewardSignalSettings structure method. This one is special b/c it takes in a Dict[RewardSignalType, RewardSignalSettings]. """ reward_signals_dict = { "extrinsic": {"strength": 1.0}, "curiosity": {"strength": 1.0}, } reward_signals = RewardSignalSettings.structure( reward_signals_dict, Dict[RewardSignalType, RewardSignalSettings] ) assert isinstance(reward_signals[RewardSignalType.EXTRINSIC], RewardSignalSettings) assert isinstance(reward_signals[RewardSignalType.CURIOSITY], CuriositySettings) # Check invalid reward signal type reward_signals_dict = {"puppo": {"strength": 1.0}} with pytest.raises(ValueError): RewardSignalSettings.structure( reward_signals_dict, Dict[RewardSignalType, RewardSignalSettings] ) # Check missing GAIL demo path reward_signals_dict = {"gail": {"strength": 1.0}} with pytest.raises(TypeError): RewardSignalSettings.structure( reward_signals_dict, Dict[RewardSignalType, RewardSignalSettings] ) # Check non-Dict input with pytest.raises(TrainerConfigError): RewardSignalSettings.structure( "notadict", Dict[RewardSignalType, RewardSignalSettings] ) def test_memory_settings_validation(): with pytest.raises(TrainerConfigError): NetworkSettings.MemorySettings(sequence_length=128, memory_size=63) with pytest.raises(TrainerConfigError): NetworkSettings.MemorySettings(sequence_length=128, memory_size=0) def test_env_parameter_structure(): """ Tests the EnvironmentParameterSettings structure method and all validators. """ env_params_dict = { "mass": { "sampler_type": "uniform", "sampler_parameters": {"min_value": 1.0, "max_value": 2.0}, }, "scale": { "sampler_type": "gaussian", "sampler_parameters": {"mean": 1.0, "st_dev": 2.0}, }, "length": { "sampler_type": "multirangeuniform", "sampler_parameters": {"intervals": [[1.0, 2.0], [3.0, 4.0]]}, }, "gravity": 1, "wall_height": { "curriculum": [ { "name": "Lesson1", "completion_criteria": { "measure": "reward", "behavior": "fake_behavior", "threshold": 10, }, "value": 1, }, {"value": 4, "name": "Lesson2"}, ] }, } env_param_settings = EnvironmentParameterSettings.structure( env_params_dict, Dict[str, EnvironmentParameterSettings] ) assert isinstance(env_param_settings["mass"].curriculum[0].value, UniformSettings) assert isinstance(env_param_settings["scale"].curriculum[0].value, GaussianSettings) assert isinstance( env_param_settings["length"].curriculum[0].value, MultiRangeUniformSettings ) # Check __str__ is correct assert ( str(env_param_settings["mass"].curriculum[0].value) == "Uniform sampler: min=1.0, max=2.0" ) assert ( str(env_param_settings["scale"].curriculum[0].value) == "Gaussian sampler: mean=1.0, stddev=2.0" ) assert ( str(env_param_settings["length"].curriculum[0].value) == "MultiRangeUniform sampler: intervals=[(1.0, 2.0), (3.0, 4.0)]" ) assert str(env_param_settings["gravity"].curriculum[0].value) == "Float: value=1" assert isinstance( env_param_settings["wall_height"].curriculum[0].value, ConstantSettings ) assert isinstance( env_param_settings["wall_height"].curriculum[1].value, ConstantSettings ) # Check invalid distribution type invalid_distribution_dict = { "mass": { "sampler_type": "beta", "sampler_parameters": {"alpha": 1.0, "beta": 2.0}, } } with pytest.raises(ValueError): EnvironmentParameterSettings.structure( invalid_distribution_dict, Dict[str, EnvironmentParameterSettings] ) # Check min less than max in uniform invalid_distribution_dict = { "mass": { "sampler_type": "uniform", "sampler_parameters": {"min_value": 2.0, "max_value": 1.0}, } } with pytest.raises(TrainerConfigError): EnvironmentParameterSettings.structure( invalid_distribution_dict, Dict[str, EnvironmentParameterSettings] ) # Check min less than max in multirange invalid_distribution_dict = { "mass": { "sampler_type": "multirangeuniform", "sampler_parameters": {"intervals": [[2.0, 1.0]]}, } } with pytest.raises(TrainerConfigError): EnvironmentParameterSettings.structure( invalid_distribution_dict, Dict[str, EnvironmentParameterSettings] ) # Check multirange has valid intervals invalid_distribution_dict = { "mass": { "sampler_type": "multirangeuniform", "sampler_parameters": {"intervals": [[1.0, 2.0], [3.0]]}, } } with pytest.raises(TrainerConfigError): EnvironmentParameterSettings.structure( invalid_distribution_dict, Dict[str, EnvironmentParameterSettings] ) # Check non-Dict input with pytest.raises(TrainerConfigError): EnvironmentParameterSettings.structure( "notadict", Dict[str, EnvironmentParameterSettings] ) invalid_curriculum_dict = { "wall_height": { "curriculum": [ { "name": "Lesson1", "completion_criteria": { "measure": "progress", "behavior": "fake_behavior", "threshold": 10, }, # > 1 is too large "value": 1, }, {"value": 4, "name": "Lesson2"}, ] } } with pytest.raises(TrainerConfigError): EnvironmentParameterSettings.structure( invalid_curriculum_dict, Dict[str, EnvironmentParameterSettings] ) @pytest.mark.parametrize("use_defaults", [True, False]) def test_exportable_settings(use_defaults): """ Test that structuring and unstructuring a RunOptions object results in the same configuration representation. """ # Try to enable as many features as possible in this test YAML to hit all the # edge cases. Set as much as possible as non-default values to ensure no flukes. test_yaml = """ behaviors: 3DBall: trainer_type: sac hyperparameters: learning_rate: 0.0004 learning_rate_schedule: constant batch_size: 64 buffer_size: 200000 buffer_init_steps: 100 tau: 0.006 steps_per_update: 10.0 save_replay_buffer: true init_entcoef: 0.5 reward_signal_steps_per_update: 10.0 network_settings: deterministic: true normalize: false hidden_units: 256 num_layers: 3 vis_encode_type: nature_cnn memory: memory_size: 1288 sequence_length: 12 reward_signals: extrinsic: gamma: 0.999 strength: 1.0 curiosity: gamma: 0.999 strength: 1.0 keep_checkpoints: 5 max_steps: 500000 time_horizon: 1000 summary_freq: 12000 checkpoint_interval: 1 threaded: true env_settings: env_path: test_env_path env_args: - test_env_args1 - test_env_args2 base_port: 12345 num_envs: 8 num_areas: 8 seed: 12345 engine_settings: width: 12345 height: 12345 quality_level: 12345 time_scale: 12345 target_frame_rate: 12345 capture_frame_rate: 12345 no_graphics: true checkpoint_settings: run_id: test_run_id initialize_from: test_directory load_model: false resume: true force: true train_model: false inference: false debug: true environment_parameters: big_wall_height: curriculum: - name: Lesson0 completion_criteria: measure: progress behavior: BigWallJump signal_smoothing: true min_lesson_length: 100 threshold: 0.1 value: sampler_type: uniform sampler_parameters: min_value: 0.0 max_value: 4.0 - name: Lesson1 completion_criteria: measure: reward behavior: BigWallJump signal_smoothing: true min_lesson_length: 100 threshold: 0.2 value: sampler_type: gaussian sampler_parameters: mean: 4.0 st_dev: 7.0 - name: Lesson2 completion_criteria: measure: progress behavior: BigWallJump signal_smoothing: true min_lesson_length: 20 threshold: 0.3 value: sampler_type: multirangeuniform sampler_parameters: intervals: [[1.0, 2.0],[4.0, 5.0]] - name: Lesson3 value: 8.0 small_wall_height: 42.0 other_wall_height: sampler_type: multirangeuniform sampler_parameters: intervals: [[1.0, 2.0],[4.0, 5.0]] """ if not use_defaults: loaded_yaml = yaml.safe_load(test_yaml) run_options = RunOptions.from_dict(yaml.safe_load(test_yaml)) else: run_options = RunOptions() dict_export = run_options.as_dict() if not use_defaults: # Don't need to check if no yaml check_dict_is_at_least( loaded_yaml, dict_export, exceptions=["environment_parameters"] ) # Re-import and verify has same elements run_options2 = RunOptions.from_dict(dict_export) second_export = run_options2.as_dict() check_dict_is_at_least(dict_export, second_export) # Should be able to use equality instead of back-and-forth once environment_parameters # is working check_dict_is_at_least(second_export, dict_export) # Check that the two exports are the same assert dict_export == second_export # check if cehckpoint_settings priorotizes resume over initialize from run_options2.checkpoint_settings.prioritize_resume_init() assert run_options2.checkpoint_settings.initialize_from is None def test_environment_settings(): # default args EnvironmentSettings() # 1 env is OK if no env_path EnvironmentSettings(num_envs=1) # 2 areas are OK EnvironmentSettings(num_areas=2) # multiple envs is OK if env_path is set EnvironmentSettings(num_envs=42, env_path="/foo/bar.exe") # Multiple environments with no env_path is an error with pytest.raises(ValueError): EnvironmentSettings(num_envs=2) def test_default_settings(): # Make default settings, one nested and one not. default_settings = { "max_steps": 1, "network_settings": {"num_layers": 1000, "deterministic": True}, } behaviors = {"test1": {"max_steps": 2, "network_settings": {"hidden_units": 2000}}} run_options_dict = {"default_settings": default_settings, "behaviors": behaviors} run_options = RunOptions.from_dict(run_options_dict) # Check that a new behavior has the default settings default_settings_cls = cattr.structure(default_settings, TrainerSettings) check_if_different(default_settings_cls, run_options.behaviors["test2"]) # Check that an existing behavior overrides the defaults in specified fields test1_settings = run_options.behaviors["test1"] assert test1_settings.max_steps == 2 assert test1_settings.network_settings.hidden_units == 2000 assert test1_settings.network_settings.deterministic is True assert test1_settings.network_settings.num_layers == 1000 # Change the overridden fields back, and check if the rest are equal. test1_settings.max_steps = 1 test1_settings.network_settings.hidden_units = ( default_settings_cls.network_settings.hidden_units ) check_if_different(test1_settings, default_settings_cls) def test_config_specified(): # Test require all behavior names to be specified (or not) # Remove any pre-set defaults TrainerSettings.default_override = None behaviors = {"test1": {"max_steps": 2, "network_settings": {"hidden_units": 2000}}} run_options_dict = {"behaviors": behaviors} ro = RunOptions.from_dict(run_options_dict) # Don't require all behavior names ro.behaviors.set_config_specified(False) # Test that we can grab an entry that is not in the dict. assert isinstance(ro.behaviors["test2"], TrainerSettings) # Create strict RunOptions with no defualt_settings run_options_dict = {"behaviors": behaviors} ro = RunOptions.from_dict(run_options_dict) # Require all behavior names ro.behaviors.set_config_specified(True) with pytest.raises(TrainerConfigError): # Variable must be accessed otherwise Python won't query the dict print(ro.behaviors["test2"]) # Create strict RunOptions with default settings default_settings = {"max_steps": 1, "network_settings": {"num_layers": 1000}} run_options_dict = {"default_settings": default_settings, "behaviors": behaviors} ro = RunOptions.from_dict(run_options_dict) # Require all behavior names ro.behaviors.set_config_specified(True) # Test that we can grab an entry that is not in the dict. assert isinstance(ro.behaviors["test2"], TrainerSettings) def test_pickle(): # Make sure RunOptions is pickle-able. run_options = RunOptions() p = pickle.dumps(run_options) pickle.loads(p)
ml-agents/ml-agents/mlagents/trainers/tests/test_settings.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_settings.py", "repo_id": "ml-agents", "token_count": 9681 }
1,911
import numpy as np from mlagents.torch_utils import torch from mlagents.trainers.buffer import AgentBuffer, BufferKey from mlagents.trainers.torch_entities.agent_action import AgentAction def test_agent_action_group_from_buffer(): buff = AgentBuffer() # Create some actions for _ in range(3): buff[BufferKey.GROUP_CONTINUOUS_ACTION].append( 3 * [np.ones((5,), dtype=np.float32)] ) buff[BufferKey.GROUP_DISCRETE_ACTION].append( 3 * [np.ones((4,), dtype=np.float32)] ) # Some agents have died for _ in range(2): buff[BufferKey.GROUP_CONTINUOUS_ACTION].append( 1 * [np.ones((5,), dtype=np.float32)] ) buff[BufferKey.GROUP_DISCRETE_ACTION].append( 1 * [np.ones((4,), dtype=np.float32)] ) # Get the group actions, which will be a List of Lists of AgentAction, where each element is the same # length as the AgentBuffer but contains only one agent's obs. Dead agents are padded by # NaNs. gact = AgentAction.group_from_buffer(buff) # Agent 0 is full agent_0_act = gact[0] assert agent_0_act.continuous_tensor.shape == (buff.num_experiences, 5) assert agent_0_act.discrete_tensor.shape == (buff.num_experiences, 4) agent_1_act = gact[1] assert agent_1_act.continuous_tensor.shape == (buff.num_experiences, 5) assert agent_1_act.discrete_tensor.shape == (buff.num_experiences, 4) assert (agent_1_act.continuous_tensor[0:3] > 0).all() assert (agent_1_act.continuous_tensor[3:] == 0).all() assert (agent_1_act.discrete_tensor[0:3] > 0).all() assert (agent_1_act.discrete_tensor[3:] == 0).all() def test_slice(): # Both continuous and discrete aa = AgentAction( torch.tensor([[1.0], [1.0], [1.0]]), [torch.tensor([2, 1, 0]), torch.tensor([1, 2, 0])], ) saa = aa.slice(0, 2) assert saa.continuous_tensor.shape == (2, 1) assert saa.discrete_tensor.shape == (2, 2) def test_to_flat(): # Both continuous and discrete aa = AgentAction( torch.tensor([[1.0, 1.0, 1.0]]), [torch.tensor([2]), torch.tensor([1])] ) flattened_actions = aa.to_flat([3, 3]) assert torch.eq( flattened_actions, torch.tensor([[1, 1, 1, 0, 0, 1, 0, 1, 0]]) ).all() # Just continuous aa = AgentAction(torch.tensor([[1.0, 1.0, 1.0]]), None) flattened_actions = aa.to_flat([]) assert torch.eq(flattened_actions, torch.tensor([1, 1, 1])).all() # Just discrete aa = AgentAction(torch.tensor([]), [torch.tensor([2]), torch.tensor([1])]) flattened_actions = aa.to_flat([3, 3]) assert torch.eq(flattened_actions, torch.tensor([0, 0, 1, 0, 1, 0])).all()
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_agent_action.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_agent_action.py", "repo_id": "ml-agents", "token_count": 1181 }
1,912
from typing import Any import numpy as np import pytest from unittest.mock import patch from mlagents.torch_utils import torch import os from mlagents.trainers.torch_entities.components.reward_providers import ( GAILRewardProvider, create_reward_provider, ) from mlagents_envs.base_env import BehaviorSpec, ActionSpec from mlagents.trainers.settings import GAILSettings, RewardSignalType from mlagents.trainers.tests.torch_entities.test_reward_providers.utils import ( create_agent_buffer, ) from mlagents.trainers.torch_entities.components.reward_providers.gail_reward_provider import ( DiscriminatorNetwork, ) from mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes CONTINUOUS_PATH = ( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir) + "/test.demo" ) DISCRETE_PATH = ( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir) + "/testdcvis.demo" ) SEED = [42] ACTIONSPEC_CONTINUOUS = ActionSpec.create_continuous(2) ACTIONSPEC_FOURDISCRETE = ActionSpec.create_discrete((2, 3, 3, 3)) ACTIONSPEC_DISCRETE = ActionSpec.create_discrete((20,)) @pytest.mark.parametrize( "behavior_spec", [BehaviorSpec(create_observation_specs_with_shapes([(8,)]), ACTIONSPEC_CONTINUOUS)], ) def test_construction(behavior_spec: BehaviorSpec) -> None: gail_settings = GAILSettings(demo_path=CONTINUOUS_PATH) gail_rp = GAILRewardProvider(behavior_spec, gail_settings) assert gail_rp.name == "GAIL" @pytest.mark.parametrize( "behavior_spec", [BehaviorSpec(create_observation_specs_with_shapes([(8,)]), ACTIONSPEC_CONTINUOUS)], ) def test_factory(behavior_spec: BehaviorSpec) -> None: gail_settings = GAILSettings(demo_path=CONTINUOUS_PATH) gail_rp = create_reward_provider( RewardSignalType.GAIL, behavior_spec, gail_settings ) assert gail_rp.name == "GAIL" @pytest.mark.parametrize("seed", SEED) @pytest.mark.parametrize( "behavior_spec", [ BehaviorSpec( create_observation_specs_with_shapes([(8,), (1, 24, 26)]), ACTIONSPEC_CONTINUOUS, ), BehaviorSpec( create_observation_specs_with_shapes([(50,)]), ACTIONSPEC_FOURDISCRETE ), BehaviorSpec( create_observation_specs_with_shapes([(10,)]), ACTIONSPEC_DISCRETE ), ], ) @pytest.mark.parametrize("use_actions", [False, True]) @patch( "mlagents.trainers.torch_entities.components.reward_providers.gail_reward_provider.demo_to_buffer" ) def test_reward_decreases( demo_to_buffer: Any, use_actions: bool, behavior_spec: BehaviorSpec, seed: int ) -> None: np.random.seed(seed) torch.manual_seed(seed) buffer_expert = create_agent_buffer(behavior_spec, 1000) buffer_policy = create_agent_buffer(behavior_spec, 1000) demo_to_buffer.return_value = None, buffer_expert gail_settings = GAILSettings( demo_path="", learning_rate=0.005, use_vail=False, use_actions=use_actions ) gail_rp = create_reward_provider( RewardSignalType.GAIL, behavior_spec, gail_settings ) init_reward_expert = gail_rp.evaluate(buffer_expert)[0] init_reward_policy = gail_rp.evaluate(buffer_policy)[0] for _ in range(20): gail_rp.update(buffer_policy) reward_expert = gail_rp.evaluate(buffer_expert)[0] reward_policy = gail_rp.evaluate(buffer_policy)[0] assert reward_expert >= 0 # GAIL / VAIL reward always positive assert reward_policy >= 0 reward_expert = gail_rp.evaluate(buffer_expert)[0] reward_policy = gail_rp.evaluate(buffer_policy)[0] assert reward_expert > reward_policy # Expert reward greater than non-expert reward assert ( reward_expert > init_reward_expert ) # Expert reward getting better as network trains assert ( reward_policy < init_reward_policy ) # Non-expert reward getting worse as network trains @pytest.mark.parametrize("seed", SEED) @pytest.mark.parametrize( "behavior_spec", [ BehaviorSpec( create_observation_specs_with_shapes([(8,), (1, 24, 26)]), ACTIONSPEC_CONTINUOUS, ), BehaviorSpec( create_observation_specs_with_shapes([(50,)]), ACTIONSPEC_FOURDISCRETE ), BehaviorSpec( create_observation_specs_with_shapes([(10,)]), ACTIONSPEC_DISCRETE ), ], ) @pytest.mark.parametrize("use_actions", [False, True]) @patch( "mlagents.trainers.torch_entities.components.reward_providers.gail_reward_provider.demo_to_buffer" ) def test_reward_decreases_vail( demo_to_buffer: Any, use_actions: bool, behavior_spec: BehaviorSpec, seed: int ) -> None: np.random.seed(seed) torch.manual_seed(seed) buffer_expert = create_agent_buffer(behavior_spec, 1000) buffer_policy = create_agent_buffer(behavior_spec, 1000) demo_to_buffer.return_value = None, buffer_expert gail_settings = GAILSettings( demo_path="", learning_rate=0.005, use_vail=True, use_actions=use_actions ) DiscriminatorNetwork.initial_beta = 0.0 # we must set the initial value of beta to 0 for testing # If we do not, the kl-loss will dominate early and will block the estimator gail_rp = create_reward_provider( RewardSignalType.GAIL, behavior_spec, gail_settings ) for _ in range(20): gail_rp.update(buffer_policy) reward_expert = gail_rp.evaluate(buffer_expert)[0] reward_policy = gail_rp.evaluate(buffer_policy)[0] assert reward_expert >= 0 # GAIL / VAIL reward always positive assert reward_policy >= 0 reward_expert = gail_rp.evaluate(buffer_expert)[0] reward_policy = gail_rp.evaluate(buffer_policy)[0] assert reward_expert > reward_policy # Expert reward greater than non-expert reward
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_reward_providers/test_gail.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_reward_providers/test_gail.py", "repo_id": "ml-agents", "token_count": 2408 }
1,913
from mlagents.trainers.torch_entities.components.reward_providers.base_reward_provider import ( # noqa F401 BaseRewardProvider, ) from mlagents.trainers.torch_entities.components.reward_providers.extrinsic_reward_provider import ( # noqa F401 ExtrinsicRewardProvider, ) from mlagents.trainers.torch_entities.components.reward_providers.curiosity_reward_provider import ( # noqa F401 CuriosityRewardProvider, ) from mlagents.trainers.torch_entities.components.reward_providers.gail_reward_provider import ( # noqa F401 GAILRewardProvider, ) from mlagents.trainers.torch_entities.components.reward_providers.rnd_reward_provider import ( # noqa F401 RNDRewardProvider, ) from mlagents.trainers.torch_entities.components.reward_providers.reward_provider_factory import ( # noqa F401 create_reward_provider, )
ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/__init__.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/__init__.py", "repo_id": "ml-agents", "token_count": 305 }
1,914
# ## ML-Agent Learning (SAC) # Contains an implementation of SAC as described in https://arxiv.org/abs/1801.01290 # and implemented in https://github.com/hill-a/stable-baselines from collections import defaultdict from typing import Dict, cast import os import numpy as np from mlagents.trainers.policy.checkpoint_manager import ModelCheckpoint from mlagents_envs.logging_util import get_logger from mlagents_envs.timers import timed from mlagents.trainers.buffer import RewardSignalUtil from mlagents.trainers.policy import Policy from mlagents.trainers.optimizer.torch_optimizer import TorchOptimizer from mlagents.trainers.trainer.rl_trainer import RLTrainer from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers from mlagents.trainers.settings import TrainerSettings, OffPolicyHyperparamSettings logger = get_logger(__name__) BUFFER_TRUNCATE_PERCENT = 0.8 class OffPolicyTrainer(RLTrainer): """ The SACTrainer is an implementation of the SAC algorithm, with support for discrete actions and recurrent networks. """ def __init__( self, behavior_name: str, reward_buff_cap: int, trainer_settings: TrainerSettings, training: bool, load: bool, seed: int, artifact_path: str, ): """ Responsible for collecting experiences and training an off-policy model. :param behavior_name: The name of the behavior associated with trainer config :param reward_buff_cap: Max reward history to track in the reward buffer :param trainer_settings: The parameters for the trainer. :param training: Whether the trainer is set for training. :param load: Whether the model should be loaded. :param seed: The seed the model will be initialized with :param artifact_path: The directory within which to store artifacts from this trainer. """ super().__init__( behavior_name, trainer_settings, training, load, artifact_path, reward_buff_cap, ) self.seed = seed self.policy: Policy = None # type: ignore self.optimizer: TorchOptimizer = None # type: ignore self.hyperparameters: OffPolicyHyperparamSettings = cast( OffPolicyHyperparamSettings, trainer_settings.hyperparameters ) self._step = 0 # Don't divide by zero self.update_steps = 1 self.reward_signal_update_steps = 1 self.steps_per_update = self.hyperparameters.steps_per_update self.reward_signal_steps_per_update = ( self.hyperparameters.reward_signal_steps_per_update ) self.checkpoint_replay_buffer = self.hyperparameters.save_replay_buffer def _checkpoint(self) -> ModelCheckpoint: """ Writes a checkpoint model to memory Overrides the default to save the replay buffer. """ ckpt = super()._checkpoint() if self.checkpoint_replay_buffer: self.save_replay_buffer() return ckpt def save_model(self) -> None: """ Saves the final training model to memory Overrides the default to save the replay buffer. """ super().save_model() if self.checkpoint_replay_buffer: self.save_replay_buffer() def save_replay_buffer(self) -> None: """ Save the training buffer's update buffer to a pickle file. """ filename = os.path.join(self.artifact_path, "last_replay_buffer.hdf5") logger.info(f"Saving Experience Replay Buffer to {filename}...") with open(filename, "wb") as file_object: self.update_buffer.save_to_file(file_object) logger.info( f"Saved Experience Replay Buffer ({os.path.getsize(filename)} bytes)." ) def load_replay_buffer(self) -> None: """ Loads the last saved replay buffer from a file. """ filename = os.path.join(self.artifact_path, "last_replay_buffer.hdf5") logger.info(f"Loading Experience Replay Buffer from {filename}...") with open(filename, "rb+") as file_object: self.update_buffer.load_from_file(file_object) logger.debug( "Experience replay buffer has {} experiences.".format( self.update_buffer.num_experiences ) ) def _is_ready_update(self) -> bool: """ Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not _update_policy() can be run """ return ( self.update_buffer.num_experiences >= self.hyperparameters.batch_size and self._step >= self.hyperparameters.buffer_init_steps ) def maybe_load_replay_buffer(self): # Load the replay buffer if load if self.load and self.checkpoint_replay_buffer: try: self.load_replay_buffer() except (AttributeError, FileNotFoundError): logger.warning( "Replay buffer was unable to load, starting from scratch." ) logger.debug( "Loaded update buffer with {} sequences".format( self.update_buffer.num_experiences ) ) def add_policy( self, parsed_behavior_id: BehaviorIdentifiers, policy: Policy ) -> None: """ Adds policy to trainer. """ if self.policy: logger.warning( "Your environment contains multiple teams, but {} doesn't support adversarial games. Enable self-play to \ train adversarial games.".format( self.__class__.__name__ ) ) self.policy = policy self.policies[parsed_behavior_id.behavior_id] = policy self.optimizer = self.create_optimizer() for _reward_signal in self.optimizer.reward_signals.keys(): self.collected_rewards[_reward_signal] = defaultdict(lambda: 0) self.model_saver.register(self.policy) self.model_saver.register(self.optimizer) self.model_saver.initialize_or_load() # Needed to resume loads properly self._step = policy.get_current_step() # Assume steps were updated at the correct ratio before self.update_steps = int(max(1, self._step / self.steps_per_update)) self.reward_signal_update_steps = int( max(1, self._step / self.reward_signal_steps_per_update) ) @timed def _update_policy(self) -> bool: """ Uses update_buffer to update the policy. We sample the update_buffer and update until the steps_per_update ratio is met. """ has_updated = False self.cumulative_returns_since_policy_update.clear() n_sequences = max( int(self.hyperparameters.batch_size / self.policy.sequence_length), 1 ) batch_update_stats: Dict[str, list] = defaultdict(list) while ( self._step - self.hyperparameters.buffer_init_steps ) / self.update_steps > self.steps_per_update: logger.debug(f"Updating SAC policy at step {self._step}") buffer = self.update_buffer if self.update_buffer.num_experiences >= self.hyperparameters.batch_size: sampled_minibatch = buffer.sample_mini_batch( self.hyperparameters.batch_size, sequence_length=self.policy.sequence_length, ) # Get rewards for each reward for name, signal in self.optimizer.reward_signals.items(): sampled_minibatch[RewardSignalUtil.rewards_key(name)] = ( signal.evaluate(sampled_minibatch) * signal.strength ) update_stats = self.optimizer.update(sampled_minibatch, n_sequences) for stat_name, value in update_stats.items(): batch_update_stats[stat_name].append(value) self.update_steps += 1 for stat, stat_list in batch_update_stats.items(): self._stats_reporter.add_stat(stat, np.mean(stat_list)) has_updated = True if self.optimizer.bc_module: update_stats = self.optimizer.bc_module.update() for stat, val in update_stats.items(): self._stats_reporter.add_stat(stat, val) # Truncate update buffer if neccessary. Truncate more than we need to to avoid truncating # a large buffer at each update. if self.update_buffer.num_experiences > self.hyperparameters.buffer_size: self.update_buffer.truncate( int(self.hyperparameters.buffer_size * BUFFER_TRUNCATE_PERCENT) ) # TODO: revisit this update self._update_reward_signals() return has_updated def _update_reward_signals(self) -> None: """ Iterate through the reward signals and update them. Unlike in PPO, do it separate from the policy so that it can be done at a different interval. This function should only be used to simulate http://arxiv.org/abs/1809.02925 and similar papers, where the policy is updated N times, then the reward signals are updated N times. Normally, the reward signal and policy are updated in parallel. """ buffer = self.update_buffer batch_update_stats: Dict[str, list] = defaultdict(list) while ( self._step - self.hyperparameters.buffer_init_steps ) / self.reward_signal_update_steps > self.reward_signal_steps_per_update: # Get minibatches for reward signal update if needed minibatch = buffer.sample_mini_batch( self.hyperparameters.batch_size, sequence_length=self.policy.sequence_length, ) update_stats = self.optimizer.update_reward_signals(minibatch) for stat_name, value in update_stats.items(): batch_update_stats[stat_name].append(value) self.reward_signal_update_steps += 1 for stat, stat_list in batch_update_stats.items(): self._stats_reporter.add_stat(stat, np.mean(stat_list))
ml-agents/ml-agents/mlagents/trainers/trainer/off_policy_trainer.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/trainer/off_policy_trainer.py", "repo_id": "ml-agents", "token_count": 4514 }
1,915
syntax = "proto3"; import "mlagents_envs/communicator_objects/agent_info.proto"; import "mlagents_envs/communicator_objects/agent_action.proto"; option csharp_namespace = "Unity.MLAgents.CommunicatorObjects"; package communicator_objects; message AgentInfoActionPairProto { AgentInfoProto agent_info = 1; AgentActionProto action_info = 2; }
ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/agent_info_action_pair.proto/0
{ "file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/agent_info_action_pair.proto", "repo_id": "ml-agents", "token_count": 121 }
1,916
syntax = "proto3"; import "mlagents_envs/communicator_objects/agent_action.proto"; import "mlagents_envs/communicator_objects/command.proto"; option csharp_namespace = "Unity.MLAgents.CommunicatorObjects"; package communicator_objects; message UnityRLInputProto { message ListAgentActionProto { repeated AgentActionProto value = 1; } map<string, ListAgentActionProto> agent_actions = 1; reserved 2; //deprecated environment proto reserved 3; //deprecated is_trainig CommandProto command = 4; bytes side_channel = 5; }
ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/unity_rl_input.proto/0
{ "file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/unity_rl_input.proto", "repo_id": "ml-agents", "token_count": 198 }
1,917
fileFormatVersion: 2 guid: 6d2d240998b7a9a44b7402136c946623 folderAsset: yes DefaultImporter: userData:
xLua/Assets/XLua.meta/0
{ "file_path": "xLua/Assets/XLua.meta", "repo_id": "xLua", "token_count": 46 }
1,918
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using XLua; /// <summary> /// xLua 默认配置 /// </summary> static class XLuaUnityDefaultConfig { #if UNITY_2022_1_OR_NEWER static bool IsSpanType(Type type) { if (!type.IsGenericType) return false; var genericDefinition = type.GetGenericTypeDefinition(); return genericDefinition == typeof(Span<>) || genericDefinition == typeof(ReadOnlySpan<>); } static bool IsSpanMember(MemberInfo memberInfo) { switch (memberInfo) { case FieldInfo fieldInfo: return IsSpanType(fieldInfo.FieldType); case PropertyInfo propertyInfo: return IsSpanType(propertyInfo.PropertyType); case ConstructorInfo constructorInfo: return constructorInfo.GetParameters().Any(p => IsSpanType(p.ParameterType)); case MethodInfo methodInfo: return methodInfo.GetParameters().Any(p => IsSpanType(p.ParameterType)) || IsSpanType(methodInfo.ReturnType); default: return false; } } [BlackList] public static Func<MemberInfo, bool> SpanMembersFilter = IsSpanMember; #endif }
xLua/Assets/XLua/Editor/XLuaUnityDefaultConfig.cs/0
{ "file_path": "xLua/Assets/XLua/Editor/XLuaUnityDefaultConfig.cs", "repo_id": "xLua", "token_count": 573 }
1,919
fileFormatVersion: 2 guid: 9b998ff8754d165438f1f34adb4f3d7e TextScriptImporter: userData:
xLua/Assets/XLua/Examples/03_UIEvent/ButtonInteraction.lua.txt.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/03_UIEvent/ButtonInteraction.lua.txt.meta", "repo_id": "xLua", "token_count": 44 }
1,920
fileFormatVersion: 2 guid: 213d1592ca01d9a4fba0477875fcd2ef timeCreated: 1489371350 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/10_SignatureLoader/otherfiles/signatured1.lua.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/10_SignatureLoader/otherfiles/signatured1.lua.meta", "repo_id": "xLua", "token_count": 71 }
1,921
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLua.Mini", "XLua.Mini.csproj", "{9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLuaGenerate", "XLuaGenerate.csproj", "{6A24C3AC-5687-5251-FF0C-8B07EB4E1ED4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLuaHotfixInject", "XLuaHotfixInject.csproj", "{0E713D15-FA69-5C67-239C-41EC0FF43B73}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeyPairsGen", "KeyPairsGen.csproj", "{67F72FA1-D3AC-A896-5CA1-A26DC8559F9A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FilesSignature", "FilesSignature.csproj", "{2A7BAA8E-1649-9E94-FFDC-0EBBEB497AF9}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLuaTest", "XLuaTest.csproj", "{DF2795A4-CBF4-EFAF-F40D-DE57E039253E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLuaUnitTest", "XLuaUnitTest.csproj", "{7F2D7E42-6B90-0DE7-1416-469D0058D969}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}.Debug|Any CPU.Build.0 = Debug|Any CPU {9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}.Release|Any CPU.ActiveCfg = Release|Any CPU {9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}.Release|Any CPU.Build.0 = Release|Any CPU {6A24C3AC-5687-5251-FF0C-8B07EB4E1ED4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6A24C3AC-5687-5251-FF0C-8B07EB4E1ED4}.Debug|Any CPU.Build.0 = Debug|Any CPU {6A24C3AC-5687-5251-FF0C-8B07EB4E1ED4}.Release|Any CPU.ActiveCfg = Release|Any CPU {6A24C3AC-5687-5251-FF0C-8B07EB4E1ED4}.Release|Any CPU.Build.0 = Release|Any CPU {0E713D15-FA69-5C67-239C-41EC0FF43B73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0E713D15-FA69-5C67-239C-41EC0FF43B73}.Debug|Any CPU.Build.0 = Debug|Any CPU {0E713D15-FA69-5C67-239C-41EC0FF43B73}.Release|Any CPU.ActiveCfg = Release|Any CPU {0E713D15-FA69-5C67-239C-41EC0FF43B73}.Release|Any CPU.Build.0 = Release|Any CPU {67F72FA1-D3AC-A896-5CA1-A26DC8559F9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {67F72FA1-D3AC-A896-5CA1-A26DC8559F9A}.Debug|Any CPU.Build.0 = Debug|Any CPU {67F72FA1-D3AC-A896-5CA1-A26DC8559F9A}.Release|Any CPU.ActiveCfg = Release|Any CPU {67F72FA1-D3AC-A896-5CA1-A26DC8559F9A}.Release|Any CPU.Build.0 = Release|Any CPU {2A7BAA8E-1649-9E94-FFDC-0EBBEB497AF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A7BAA8E-1649-9E94-FFDC-0EBBEB497AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A7BAA8E-1649-9E94-FFDC-0EBBEB497AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A7BAA8E-1649-9E94-FFDC-0EBBEB497AF9}.Release|Any CPU.Build.0 = Release|Any CPU {DF2795A4-CBF4-EFAF-F40D-DE57E039253E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DF2795A4-CBF4-EFAF-F40D-DE57E039253E}.Debug|Any CPU.Build.0 = Debug|Any CPU {DF2795A4-CBF4-EFAF-F40D-DE57E039253E}.Release|Any CPU.ActiveCfg = Release|Any CPU {DF2795A4-CBF4-EFAF-F40D-DE57E039253E}.Release|Any CPU.Build.0 = Release|Any CPU {7F2D7E42-6B90-0DE7-1416-469D0058D969}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F2D7E42-6B90-0DE7-1416-469D0058D969}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F2D7E42-6B90-0DE7-1416-469D0058D969}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F2D7E42-6B90-0DE7-1416-469D0058D969}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
xLua/General/vs2013/XLua.sln/0
{ "file_path": "xLua/General/vs2013/XLua.sln", "repo_id": "xLua", "token_count": 1854 }
1,922
fileFormatVersion: 2 guid: 0668986d04994e448939e21fb74c5d5a timeCreated: 1475977076 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
xLua/Test/PrefTest/xLuaPerfTest/PeformentTestConfig.cs.meta/0
{ "file_path": "xLua/Test/PrefTest/xLuaPerfTest/PeformentTestConfig.cs.meta", "repo_id": "xLua", "token_count": 101 }
1,923
fileFormatVersion: 2 guid: c81508a9cd6507b43aa52a394d110123 timeCreated: 1483528414 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/StreamingAssets/ltest/loutput.lua.meta/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/ltest/loutput.lua.meta", "repo_id": "xLua", "token_count": 69 }
1,924
@rem Script to build Lua under "Visual Studio .NET Command Prompt". @rem Do not run from this directory; run it from the toplevel: etc\luavs.bat . @rem It creates lua51.dll, lua51.lib, lua.exe, and luac.exe in src. @rem (contributed by David Manura and Mike Pall) @setlocal @set MYCOMPILE=cl /nologo /MD /O2 /W3 /c /D_CRT_SECURE_NO_DEPRECATE @set MYLINK=link /nologo @set MYMT=mt /nologo cd src %MYCOMPILE% /DLUA_BUILD_AS_DLL l*.c del lua.obj luac.obj %MYLINK% /DLL /out:lua51.dll l*.obj if exist lua51.dll.manifest^ %MYMT% -manifest lua51.dll.manifest -outputresource:lua51.dll;2 %MYCOMPILE% /DLUA_BUILD_AS_DLL lua.c %MYLINK% /out:lua.exe lua.obj lua51.lib if exist lua.exe.manifest^ %MYMT% -manifest lua.exe.manifest -outputresource:lua.exe %MYCOMPILE% l*.c print.c del lua.obj linit.obj lbaselib.obj ldblib.obj liolib.obj lmathlib.obj^ loslib.obj ltablib.obj lstrlib.obj loadlib.obj %MYLINK% /out:luac.exe *.obj if exist luac.exe.manifest^ %MYMT% -manifest luac.exe.manifest -outputresource:luac.exe del *.obj *.manifest cd ..
xLua/build/lua-5.1.5/etc/luavs.bat/0
{ "file_path": "xLua/build/lua-5.1.5/etc/luavs.bat", "repo_id": "xLua", "token_count": 453 }
1,925
/* ** $Id: ldo.h,v 2.7.1.1 2007/12/27 13:02:25 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #ifndef ldo_h #define ldo_h #include "lobject.h" #include "lstate.h" #include "lzio.h" #define luaD_checkstack(L,n) \ if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \ luaD_growstack(L, n); \ else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); #define incr_top(L) {luaD_checkstack(L,1); L->top++;} #define savestack(L,p) ((char *)(p) - (char *)L->stack) #define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) #define saveci(L,p) ((char *)(p) - (char *)L->base_ci) #define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n))) /* results from luaD_precall */ #define PCRLUA 0 /* initiated a call to a Lua function */ #define PCRC 1 /* did a call to a C function */ #define PCRYIELD 2 /* C funtion yielded */ /* type of protected functions, to be ran by `runprotected' */ typedef void (*Pfunc) (lua_State *L, void *ud); LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name); LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line); LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult); LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize); LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); LUAI_FUNC void luaD_growstack (lua_State *L, int n); LUAI_FUNC void luaD_throw (lua_State *L, int errcode); LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); #endif
xLua/build/lua-5.1.5/src/ldo.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/ldo.h", "repo_id": "xLua", "token_count": 825 }
1,926
/* ** $Id: lobject.h,v 2.20.1.2 2008/08/06 13:29:48 roberto Exp $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ #ifndef lobject_h #define lobject_h #include <stdarg.h> #include "llimits.h" #include "lua.h" /* tags for values visible from Lua */ #define LAST_TAG LUA_TTHREAD #define NUM_TAGS (LAST_TAG+1) /* ** Extra tags for non-values */ #define LUA_TPROTO (LAST_TAG+1) #define LUA_TUPVAL (LAST_TAG+2) #define LUA_TDEADKEY (LAST_TAG+3) /* ** Union of all collectable objects */ typedef union GCObject GCObject; /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked /* ** Common header in struct form */ typedef struct GCheader { CommonHeader; } GCheader; /* ** Union of all Lua values */ typedef union { GCObject *gc; void *p; lua_Number n; int b; } Value; /* ** Tagged Values */ #define TValuefields Value value; int tt typedef struct lua_TValue { TValuefields; } TValue; /* Macros to test type */ #define ttisnil(o) (ttype(o) == LUA_TNIL) #define ttisnumber(o) (ttype(o) == LUA_TNUMBER) #define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) #define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) #define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) #define ttisthread(o) (ttype(o) == LUA_TTHREAD) #define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) /* Macros to access values */ #define ttype(o) ((o)->tt) #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) #define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define tsvalue(o) (&rawtsvalue(o)->tsv) #define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) #define uvalue(o) (&rawuvalue(o)->uv) #define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) #define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) #define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) #define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) /* ** for internal debug only */ #define checkconsistency(obj) \ lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) #define checkliveness(g,obj) \ lua_assert(!iscollectable(obj) || \ ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) /* Macros to set values */ #define setnilvalue(obj) ((obj)->tt=LUA_TNIL) #define setnvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; } #define setpvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; } #define setbvalue(obj,x) \ { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; } #define setsvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \ checkliveness(G(L),i_o); } #define setuvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \ checkliveness(G(L),i_o); } #define setthvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \ checkliveness(G(L),i_o); } #define setclvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \ checkliveness(G(L),i_o); } #define sethvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \ checkliveness(G(L),i_o); } #define setptvalue(L,obj,x) \ { TValue *i_o=(obj); \ i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \ checkliveness(G(L),i_o); } #define setobj(L,obj1,obj2) \ { const TValue *o2=(obj2); TValue *o1=(obj1); \ o1->value = o2->value; o1->tt=o2->tt; \ checkliveness(G(L),o1); } /* ** different types of sets, according to destination */ /* from stack to (same) stack */ #define setobjs2s setobj /* to stack (not from same stack) */ #define setobj2s setobj #define setsvalue2s setsvalue #define sethvalue2s sethvalue #define setptvalue2s setptvalue /* from table to same table */ #define setobjt2t setobj /* to table */ #define setobj2t setobj /* to new object */ #define setobj2n setobj #define setsvalue2n setsvalue #define setttype(obj, tt) (ttype(obj) = (tt)) #define iscollectable(o) (ttype(o) >= LUA_TSTRING) typedef TValue *StkId; /* index to stack elements */ /* ** String headers for string table */ typedef union TString { L_Umaxalign dummy; /* ensures maximum alignment for strings */ struct { CommonHeader; lu_byte reserved; unsigned int hash; size_t len; } tsv; } TString; #define getstr(ts) cast(const char *, (ts) + 1) #define svalue(o) getstr(rawtsvalue(o)) typedef union Udata { L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ struct { CommonHeader; struct Table *metatable; struct Table *env; size_t len; } uv; } Udata; /* ** Function Prototypes */ typedef struct Proto { CommonHeader; TValue *k; /* constants used by the function */ Instruction *code; struct Proto **p; /* functions defined inside the function */ int *lineinfo; /* map from opcodes to source lines */ struct LocVar *locvars; /* information about local variables */ TString **upvalues; /* upvalue names */ TString *source; int sizeupvalues; int sizek; /* size of `k' */ int sizecode; int sizelineinfo; int sizep; /* size of `p' */ int sizelocvars; int linedefined; int lastlinedefined; GCObject *gclist; lu_byte nups; /* number of upvalues */ lu_byte numparams; lu_byte is_vararg; lu_byte maxstacksize; } Proto; /* masks for new-style vararg */ #define VARARG_HASARG 1 #define VARARG_ISVARARG 2 #define VARARG_NEEDSARG 4 typedef struct LocVar { TString *varname; int startpc; /* first point where variable is active */ int endpc; /* first point where variable is dead */ } LocVar; /* ** Upvalues */ typedef struct UpVal { CommonHeader; TValue *v; /* points to stack or to its own value */ union { TValue value; /* the value (when closed) */ struct { /* double linked list (when open) */ struct UpVal *prev; struct UpVal *next; } l; } u; } UpVal; /* ** Closures */ #define ClosureHeader \ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ struct Table *env typedef struct CClosure { ClosureHeader; lua_CFunction f; TValue upvalue[1]; } CClosure; typedef struct LClosure { ClosureHeader; struct Proto *p; UpVal *upvals[1]; } LClosure; typedef union Closure { CClosure c; LClosure l; } Closure; #define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) #define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) /* ** Tables */ typedef union TKey { struct { TValuefields; struct Node *next; /* for chaining */ } nk; TValue tvk; } TKey; typedef struct Node { TValue i_val; TKey i_key; } Node; typedef struct Table { CommonHeader; lu_byte flags; /* 1<<p means tagmethod(p) is not present */ lu_byte lsizenode; /* log2 of size of `node' array */ struct Table *metatable; TValue *array; /* array part */ Node *node; Node *lastfree; /* any free position is before this position */ GCObject *gclist; int sizearray; /* size of `array' array */ } Table; /* ** `module' operation for hashing (size is always a power of 2) */ #define lmod(s,size) \ (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) #define twoto(x) (1<<(x)) #define sizenode(t) (twoto((t)->lsizenode)) #define luaO_nilobject (&luaO_nilobject_) LUAI_DATA const TValue luaO_nilobject_; #define ceillog2(x) (luaO_log2((x)-1) + 1) LUAI_FUNC int luaO_log2 (unsigned int x); LUAI_FUNC int luaO_int2fb (unsigned int x); LUAI_FUNC int luaO_fb2int (int x); LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp); LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); #endif
xLua/build/lua-5.1.5/src/lobject.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/lobject.h", "repo_id": "xLua", "token_count": 3696 }
1,927
/* ** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define lua_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" static lua_State *globalL = NULL; static const char *progname = LUA_PROGNAME; static void lstop (lua_State *L, lua_Debug *ar) { (void)ar; /* unused arg. */ lua_sethook(L, NULL, 0, 0); luaL_error(L, "interrupted!"); } static void laction (int i) { signal(i, SIG_DFL); /* if another SIGINT happens before lstop, terminate process (default action) */ lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); } static void print_usage (void) { fprintf(stderr, "usage: %s [options] [script [args]].\n" "Available options are:\n" " -e stat execute string " LUA_QL("stat") "\n" " -l name require library " LUA_QL("name") "\n" " -i enter interactive mode after executing " LUA_QL("script") "\n" " -v show version information\n" " -- stop handling options\n" " - execute stdin and stop handling options\n" , progname); fflush(stderr); } static void l_message (const char *pname, const char *msg) { if (pname) fprintf(stderr, "%s: ", pname); fprintf(stderr, "%s\n", msg); fflush(stderr); } static int report (lua_State *L, int status) { if (status && !lua_isnil(L, -1)) { const char *msg = lua_tostring(L, -1); if (msg == NULL) msg = "(error object is not a string)"; l_message(progname, msg); lua_pop(L, 1); } return status; } static int traceback (lua_State *L) { if (!lua_isstring(L, 1)) /* 'message' not a string? */ return 1; /* keep it intact */ lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } static int docall (lua_State *L, int narg, int clear) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ signal(SIGINT, laction); status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); signal(SIGINT, SIG_DFL); lua_remove(L, base); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); return status; } static void print_version (void) { l_message(NULL, LUA_RELEASE " " LUA_COPYRIGHT); } static int getargs (lua_State *L, char **argv, int n) { int narg; int i; int argc = 0; while (argv[argc]) argc++; /* count total number of arguments */ narg = argc - (n + 1); /* number of arguments to the script */ luaL_checkstack(L, narg + 3, "too many arguments to script"); for (i=n+1; i < argc; i++) lua_pushstring(L, argv[i]); lua_createtable(L, narg, n + 1); for (i=0; i < argc; i++) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i - n); } return narg; } static int dofile (lua_State *L, const char *name) { int status = luaL_loadfile(L, name) || docall(L, 0, 1); return report(L, status); } static int dostring (lua_State *L, const char *s, const char *name) { int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); return report(L, status); } static int dolibrary (lua_State *L, const char *name) { lua_getglobal(L, "require"); lua_pushstring(L, name); return report(L, docall(L, 1, 1)); } static const char *get_prompt (lua_State *L, int firstline) { const char *p; lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); p = lua_tostring(L, -1); if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); lua_pop(L, 1); /* remove global */ return p; } static int incomplete (lua_State *L, int status) { if (status == LUA_ERRSYNTAX) { size_t lmsg; const char *msg = lua_tolstring(L, -1, &lmsg); const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1); if (strstr(msg, LUA_QL("<eof>")) == tp) { lua_pop(L, 1); return 1; } } return 0; /* else... */ } static int pushline (lua_State *L, int firstline) { char buffer[LUA_MAXINPUT]; char *b = buffer; size_t l; const char *prmt = get_prompt(L, firstline); if (lua_readline(L, b, prmt) == 0) return 0; /* no input */ l = strlen(b); if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ b[l-1] = '\0'; /* remove it */ if (firstline && b[0] == '=') /* first line starts with `=' ? */ lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ else lua_pushstring(L, b); lua_freeline(L, b); return 1; } static int loadline (lua_State *L) { int status; lua_settop(L, 0); if (!pushline(L, 1)) return -1; /* no input */ for (;;) { /* repeat until gets a complete line */ status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); if (!incomplete(L, status)) break; /* cannot try to add lines? */ if (!pushline(L, 0)) /* no more input? */ return -1; lua_pushliteral(L, "\n"); /* add a new line... */ lua_insert(L, -2); /* ...between the two lines */ lua_concat(L, 3); /* join them */ } lua_saveline(L, 1); lua_remove(L, 1); /* remove line */ return status; } static void dotty (lua_State *L) { int status; const char *oldprogname = progname; progname = NULL; while ((status = loadline(L)) != -1) { if (status == 0) status = docall(L, 0, 0); report(L, status); if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ lua_getglobal(L, "print"); lua_insert(L, 1); if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) l_message(progname, lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)", lua_tostring(L, -1))); } } lua_settop(L, 0); /* clear stack */ fputs("\n", stdout); fflush(stdout); progname = oldprogname; } static int handle_script (lua_State *L, char **argv, int n) { int status; const char *fname; int narg = getargs(L, argv, n); /* collect arguments */ lua_setglobal(L, "arg"); fname = argv[n]; if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) fname = NULL; /* stdin */ status = luaL_loadfile(L, fname); lua_insert(L, -(narg+1)); if (status == 0) status = docall(L, narg, 0); else lua_pop(L, narg); return report(L, status); } /* check that argument has no extra characters at the end */ #define notail(x) {if ((x)[2] != '\0') return -1;} static int collectargs (char **argv, int *pi, int *pv, int *pe) { int i; for (i = 1; argv[i] != NULL; i++) { if (argv[i][0] != '-') /* not an option? */ return i; switch (argv[i][1]) { /* option */ case '-': notail(argv[i]); return (argv[i+1] != NULL ? i+1 : 0); case '\0': return i; case 'i': notail(argv[i]); *pi = 1; /* go through */ case 'v': notail(argv[i]); *pv = 1; break; case 'e': *pe = 1; /* go through */ case 'l': if (argv[i][2] == '\0') { i++; if (argv[i] == NULL) return -1; } break; default: return -1; /* invalid option */ } } return 0; } static int runargs (lua_State *L, char **argv, int n) { int i; for (i = 1; i < n; i++) { if (argv[i] == NULL) continue; lua_assert(argv[i][0] == '-'); switch (argv[i][1]) { /* option */ case 'e': { const char *chunk = argv[i] + 2; if (*chunk == '\0') chunk = argv[++i]; lua_assert(chunk != NULL); if (dostring(L, chunk, "=(command line)") != 0) return 1; break; } case 'l': { const char *filename = argv[i] + 2; if (*filename == '\0') filename = argv[++i]; lua_assert(filename != NULL); if (dolibrary(L, filename)) return 1; /* stop if file fails */ break; } default: break; } } return 0; } static int handle_luainit (lua_State *L) { const char *init = getenv(LUA_INIT); if (init == NULL) return 0; /* status OK */ else if (init[0] == '@') return dofile(L, init+1); else return dostring(L, init, "=" LUA_INIT); } struct Smain { int argc; char **argv; int status; }; static int pmain (lua_State *L) { struct Smain *s = (struct Smain *)lua_touserdata(L, 1); char **argv = s->argv; int script; int has_i = 0, has_v = 0, has_e = 0; globalL = L; if (argv[0] && argv[0][0]) progname = argv[0]; lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ luaL_openlibs(L); /* open libraries */ lua_gc(L, LUA_GCRESTART, 0); s->status = handle_luainit(L); if (s->status != 0) return 0; script = collectargs(argv, &has_i, &has_v, &has_e); if (script < 0) { /* invalid args? */ print_usage(); s->status = 1; return 0; } if (has_v) print_version(); s->status = runargs(L, argv, (script > 0) ? script : s->argc); if (s->status != 0) return 0; if (script) s->status = handle_script(L, argv, script); if (s->status != 0) return 0; if (has_i) dotty(L); else if (script == 0 && !has_e && !has_v) { if (lua_stdin_is_tty()) { print_version(); dotty(L); } else dofile(L, NULL); /* executes stdin as a file */ } return 0; } int main (int argc, char **argv) { int status; struct Smain s; lua_State *L = lua_open(); /* create state */ if (L == NULL) { l_message(argv[0], "cannot create state: not enough memory"); return EXIT_FAILURE; } s.argc = argc; s.argv = argv; status = lua_cpcall(L, &pmain, &s); report(L, status); lua_close(L); return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; }
xLua/build/lua-5.1.5/src/lua.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/lua.c", "repo_id": "xLua", "token_count": 4581 }
1,928
# - Try to find Readline # Once done this will define # READLINE_FOUND - System has readline # READLINE_INCLUDE_DIRS - The readline include directories # READLINE_LIBRARIES - The libraries needed to use readline # READLINE_DEFINITIONS - Compiler switches required for using readline find_package ( PkgConfig ) pkg_check_modules ( PC_READLINE QUIET readline ) set ( READLINE_DEFINITIONS ${PC_READLINE_CFLAGS_OTHER} ) find_path ( READLINE_INCLUDE_DIR readline/readline.h HINTS ${PC_READLINE_INCLUDEDIR} ${PC_READLINE_INCLUDE_DIRS} PATH_SUFFIXES readline ) find_library ( READLINE_LIBRARY NAMES readline HINTS ${PC_READLINE_LIBDIR} ${PC_READLINE_LIBRARY_DIRS} ) set ( READLINE_LIBRARIES ${READLINE_LIBRARY} ) set ( READLINE_INCLUDE_DIRS ${READLINE_INCLUDE_DIR} ) include ( FindPackageHandleStandardArgs ) # handle the QUIETLY and REQUIRED arguments and set READLINE_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args ( readline DEFAULT_MSG READLINE_LIBRARY READLINE_INCLUDE_DIR )
xLua/build/lua-5.3.3/cmake/FindReadline.cmake/0
{ "file_path": "xLua/build/lua-5.3.3/cmake/FindReadline.cmake", "repo_id": "xLua", "token_count": 372 }
1,929
/* ** $Id: ldebug.h $ ** Auxiliary functions from Debug Interface module ** See Copyright Notice in lua.h */ #ifndef ldebug_h #define ldebug_h #include "lstate.h" #define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1) /* Active Lua function (given call info) */ #define ci_func(ci) (clLvalue(s2v((ci)->func))) #define resethookcount(L) (L->hookcount = L->basehookcount) /* ** mark for entries in 'lineinfo' array that has absolute information in ** 'abslineinfo' array */ #define ABSLINEINFO (-0x80) LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc); LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos); LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *opname); LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what); LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg); LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line); LUAI_FUNC l_noret luaG_errormsg (lua_State *L); LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc); #endif
xLua/build/lua-5.4.1/src/ldebug.h/0
{ "file_path": "xLua/build/lua-5.4.1/src/ldebug.h", "repo_id": "xLua", "token_count": 1051 }
1,930
/* ** $Id: lmem.h $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #ifndef lmem_h #define lmem_h #include <stddef.h> #include "llimits.h" #include "lua.h" #define luaM_error(L) luaD_throw(L, LUA_ERRMEM) /* ** This macro tests whether it is safe to multiply 'n' by the size of ** type 't' without overflows. Because 'e' is always constant, it avoids ** the runtime division MAX_SIZET/(e). ** (The macro is somewhat complex to avoid warnings: The 'sizeof' ** comparison avoids a runtime comparison when overflow cannot occur. ** The compiler should be able to optimize the real test by itself, but ** when it does it, it may give a warning about "comparison is always ** false due to limited range of data type"; the +1 tricks the compiler, ** avoiding this warning but also this optimization.) */ #define luaM_testsize(n,e) \ (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e)) #define luaM_checksize(L,n,e) \ (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0)) /* ** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that ** the result is not larger than 'n' and cannot overflow a 'size_t' ** when multiplied by the size of type 't'. (Assumes that 'n' is an ** 'int' or 'unsigned int' and that 'int' is not larger than 'size_t'.) */ #define luaM_limitN(n,t) \ ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \ cast_uint((MAX_SIZET/sizeof(t)))) /* ** Arrays of chars do not need any test */ #define luaM_reallocvchar(L,b,on,n) \ cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) #define luaM_freemem(L, b, s) luaM_free_(L, (b), (s)) #define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b))) #define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b))) #define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0)) #define luaM_newvector(L,n,t) cast(t*, luaM_malloc_(L, (n)*sizeof(t), 0)) #define luaM_newvectorchecked(L,n,t) \ (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t)) #define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag) #define luaM_growvector(L,v,nelems,size,t,limit,e) \ ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \ luaM_limitN(limit,t),e))) #define luaM_reallocvector(L, v,oldn,n,t) \ (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \ cast_sizet(n) * sizeof(t)))) #define luaM_shrinkvector(L,v,size,fs,t) \ ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t)))) LUAI_FUNC l_noret luaM_toobig (lua_State *L); /* not to be called directly */ LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, size_t size); LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize, size_t size); LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize); LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *size, int size_elem, int limit, const char *what); LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem, int final_n, int size_elem); LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag); #endif
xLua/build/lua-5.4.1/src/lmem.h/0
{ "file_path": "xLua/build/lua-5.4.1/src/lmem.h", "repo_id": "xLua", "token_count": 1584 }
1,931
/* ** $Id: ltable.c $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #define ltable_c #define LUA_CORE #include "lprefix.h" /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest 'n' such that ** more than half the slots between 1 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the 'original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ #include <math.h> #include <limits.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "lvm.h" /* ** MAXABITS is the largest integer such that MAXASIZE fits in an ** unsigned int. */ #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1) /* ** MAXASIZE is the maximum size of the array part. It is the minimum ** between 2^MAXABITS and the maximum size that, measured in bytes, ** fits in a 'size_t'. */ #define MAXASIZE luaM_limitN(1u << MAXABITS, TValue) /* ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a ** signed int. */ #define MAXHBITS (MAXABITS - 1) /* ** MAXHSIZE is the maximum size of the hash part. It is the minimum ** between 2^MAXHBITS and the maximum size such that, measured in bytes, ** it fits in a 'size_t'. */ #define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node) #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) #define hashstr(t,str) hashpow2(t, (str)->hash) #define hashboolean(t,p) hashpow2(t, p) #define hashint(t,i) hashpow2(t, i) /* ** for some types, it is better to avoid modulus by power of 2, as ** they tend to have many 2 factors. */ #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) #define hashpointer(t,p) hashmod(t, point2uint(p)) #define dummynode (&dummynode_) static const Node dummynode_ = { {{NULL}, LUA_VEMPTY, /* value's value and type */ LUA_VNIL, 0, {NULL}} /* key type, next, and key value */ }; static const TValue absentkey = {ABSTKEYCONSTANT}; /* ** Hash for floating-point numbers. ** The main computation should be just ** n = frexp(n, &i); return (n * INT_MAX) + i ** but there are some numerical subtleties. ** In a two-complement representation, INT_MAX does not has an exact ** representation as a float, but INT_MIN does; because the absolute ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with ** INT_MIN. */ #if !defined(l_hashfloat) static int l_hashfloat (lua_Number n) { int i; lua_Integer ni; n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); return 0; } else { /* normal case */ unsigned int u = cast_uint(i) + cast_uint(ni); return cast_int(u <= cast_uint(INT_MAX) ? u : ~u); } } #endif /* ** returns the 'main' position of an element in a table (that is, ** the index of its hash value). The key comes broken (tag in 'ktt' ** and value in 'vkl') so that we can call it on keys inserted into ** nodes. */ static Node *mainposition (const Table *t, int ktt, const Value *kvl) { switch (withvariant(ktt)) { case LUA_VNUMINT: return hashint(t, ivalueraw(*kvl)); case LUA_VNUMFLT: return hashmod(t, l_hashfloat(fltvalueraw(*kvl))); case LUA_VSHRSTR: return hashstr(t, tsvalueraw(*kvl)); case LUA_VLNGSTR: return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl))); case LUA_VFALSE: return hashboolean(t, 0); case LUA_VTRUE: return hashboolean(t, 1); case LUA_VLIGHTUSERDATA: return hashpointer(t, pvalueraw(*kvl)); case LUA_VLCF: return hashpointer(t, fvalueraw(*kvl)); default: return hashpointer(t, gcvalueraw(*kvl)); } } /* ** Returns the main position of an element given as a 'TValue' */ static Node *mainpositionTV (const Table *t, const TValue *key) { return mainposition(t, rawtt(key), valraw(key)); } /* ** Check whether key 'k1' is equal to the key in node 'n2'. ** This equality is raw, so there are no metamethods. Floats ** with integer values have been normalized, so integers cannot ** be equal to floats. It is assumed that 'eqshrstr' is simply ** pointer equality, so that short strings are handled in the ** default case. */ static int equalkey (const TValue *k1, const Node *n2) { if (rawtt(k1) != keytt(n2)) /* not the same variants? */ return 0; /* cannot be same key */ switch (ttypetag(k1)) { case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1; case LUA_VNUMINT: return (ivalue(k1) == keyival(n2)); case LUA_VNUMFLT: return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2))); case LUA_VLIGHTUSERDATA: return pvalue(k1) == pvalueraw(keyval(n2)); case LUA_VLCF: return fvalue(k1) == fvalueraw(keyval(n2)); case LUA_VLNGSTR: return luaS_eqlngstr(tsvalue(k1), keystrval(n2)); default: return gcvalue(k1) == gcvalueraw(keyval(n2)); } } /* ** True if value of 'alimit' is equal to the real size of the array ** part of table 't'. (Otherwise, the array part must be larger than ** 'alimit'.) */ #define limitequalsasize(t) (isrealasize(t) || ispow2((t)->alimit)) /* ** Returns the real size of the 'array' array */ LUAI_FUNC unsigned int luaH_realasize (const Table *t) { if (limitequalsasize(t)) return t->alimit; /* this is the size */ else { unsigned int size = t->alimit; /* compute the smallest power of 2 not smaller than 'n' */ size |= (size >> 1); size |= (size >> 2); size |= (size >> 4); size |= (size >> 8); size |= (size >> 16); #if (UINT_MAX >> 30) > 3 size |= (size >> 32); /* unsigned int has more than 32 bits */ #endif size++; lua_assert(ispow2(size) && size/2 < t->alimit && t->alimit < size); return size; } } /* ** Check whether real size of the array is a power of 2. ** (If it is not, 'alimit' cannot be changed to any other value ** without changing the real size.) */ static int ispow2realasize (const Table *t) { return (!isrealasize(t) || ispow2(t->alimit)); } static unsigned int setlimittosize (Table *t) { t->alimit = luaH_realasize(t); setrealasize(t); return t->alimit; } #define limitasasize(t) check_exp(isrealasize(t), t->alimit) /* ** "Generic" get version. (Not that generic: not valid for integers, ** which may be in array part, nor for floats with integral values.) */ static const TValue *getgeneric (Table *t, const TValue *key) { Node *n = mainpositionTV(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ if (equalkey(key, n)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return &absentkey; /* not found */ n += nx; } } } /* ** returns the index for 'k' if 'k' is an appropriate key to live in ** the array part of a table, 0 otherwise. */ static unsigned int arrayindex (lua_Integer k) { if (l_castS2U(k) - 1u < MAXASIZE) /* 'k' in [1, MAXASIZE]? */ return cast_uint(k); /* 'key' is an appropriate array index */ else return 0; } /* ** returns the index of a 'key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signaled by 0. */ static unsigned int findindex (lua_State *L, Table *t, TValue *key, unsigned int asize) { unsigned int i; if (ttisnil(key)) return 0; /* first iteration */ i = ttisinteger(key) ? arrayindex(ivalue(key)) : 0; if (i - 1u < asize) /* is 'key' inside array part? */ return i; /* yes; that's the index */ else { const TValue *n = getgeneric(t, key); if (unlikely(isabstkey(n))) luaG_runerror(L, "invalid key to 'next'"); /* key not found */ i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */ /* hash elements are numbered after array ones */ return (i + 1) + asize; } } int luaH_next (lua_State *L, Table *t, StkId key) { unsigned int asize = luaH_realasize(t); unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */ for (; i < asize; i++) { /* try first array part */ if (!isempty(&t->array[i])) { /* a non-empty entry? */ setivalue(s2v(key), i + 1); setobj2s(L, key + 1, &t->array[i]); return 1; } } for (i -= asize; cast_int(i) < sizenode(t); i++) { /* hash part */ if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */ Node *n = gnode(t, i); getnodekey(L, s2v(key), n); setobj2s(L, key + 1, gval(n)); return 1; } } return 0; /* no more elements */ } static void freehash (lua_State *L, Table *t) { if (!isdummy(t)) luaM_freearray(L, t->node, cast_sizet(sizenode(t))); } /* ** {============================================================= ** Rehash ** ============================================================== */ /* ** Compute the optimal size for the array part of table 't'. 'nums' is a ** "count array" where 'nums[i]' is the number of integers in the table ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of ** integer keys in the table and leaves with the number of keys that ** will go to the array part; return the optimal size. (The condition ** 'twotoi > 0' in the for loop stops the loop if 'twotoi' overflows.) */ static unsigned int computesizes (unsigned int nums[], unsigned int *pna) { int i; unsigned int twotoi; /* 2^i (candidate for optimal size) */ unsigned int a = 0; /* number of elements smaller than 2^i */ unsigned int na = 0; /* number of elements to go to array part */ unsigned int optimal = 0; /* optimal size for array part */ /* loop while keys can fill more than half of total size */ for (i = 0, twotoi = 1; twotoi > 0 && *pna > twotoi / 2; i++, twotoi *= 2) { a += nums[i]; if (a > twotoi/2) { /* more than half elements present? */ optimal = twotoi; /* optimal size (till now) */ na = a; /* all elements up to 'optimal' will go to array part */ } } lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal); *pna = na; return optimal; } static int countint (lua_Integer key, unsigned int *nums) { unsigned int k = arrayindex(key); if (k != 0) { /* is 'key' an appropriate array index? */ nums[luaO_ceillog2(k)]++; /* count as such */ return 1; } else return 0; } /* ** Count keys in array part of table 't': Fill 'nums[i]' with ** number of keys that will go into corresponding slice and return ** total number of non-nil keys. */ static unsigned int numusearray (const Table *t, unsigned int *nums) { int lg; unsigned int ttlg; /* 2^lg */ unsigned int ause = 0; /* summation of 'nums' */ unsigned int i = 1; /* count to traverse all array keys */ unsigned int asize = limitasasize(t); /* real array size */ /* traverse each slice */ for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { unsigned int lc = 0; /* counter */ unsigned int lim = ttlg; if (lim > asize) { lim = asize; /* adjust upper limit */ if (i > lim) break; /* no more elements to count */ } /* count elements in range (2^(lg - 1), 2^lg] */ for (; i <= lim; i++) { if (!isempty(&t->array[i-1])) lc++; } nums[lg] += lc; ause += lc; } return ause; } static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) { int totaluse = 0; /* total number of elements */ int ause = 0; /* elements added to 'nums' (can go to array part) */ int i = sizenode(t); while (i--) { Node *n = &t->node[i]; if (!isempty(gval(n))) { if (keyisinteger(n)) ause += countint(keyival(n), nums); totaluse++; } } *pna += ause; return totaluse; } /* ** Creates an array for the hash part of a table with the given ** size, or reuses the dummy node if size is zero. ** The computation for size overflow is in two steps: the first ** comparison ensures that the shift in the second one does not ** overflow. */ static void setnodevector (lua_State *L, Table *t, unsigned int size) { if (size == 0) { /* no elements to hash part? */ t->node = cast(Node *, dummynode); /* use common 'dummynode' */ t->lsizenode = 0; t->lastfree = NULL; /* signal that it is using dummy node */ } else { int i; int lsize = luaO_ceillog2(size); if (lsize > MAXHBITS || (1u << lsize) > MAXHSIZE) luaG_runerror(L, "table overflow"); size = twoto(lsize); t->node = luaM_newvector(L, size, Node); for (i = 0; i < (int)size; i++) { Node *n = gnode(t, i); gnext(n) = 0; setnilkey(n); setempty(gval(n)); } t->lsizenode = cast_byte(lsize); t->lastfree = gnode(t, size); /* all positions are free */ } } /* ** (Re)insert all elements from the hash part of 'ot' into table 't'. */ static void reinsert (lua_State *L, Table *ot, Table *t) { int j; int size = sizenode(ot); for (j = 0; j < size; j++) { Node *old = gnode(ot, j); if (!isempty(gval(old))) { /* doesn't need barrier/invalidate cache, as entry was already present in the table */ TValue k; getnodekey(L, &k, old); setobjt2t(L, luaH_set(L, t, &k), gval(old)); } } } /* ** Exchange the hash part of 't1' and 't2'. */ static void exchangehashpart (Table *t1, Table *t2) { lu_byte lsizenode = t1->lsizenode; Node *node = t1->node; Node *lastfree = t1->lastfree; t1->lsizenode = t2->lsizenode; t1->node = t2->node; t1->lastfree = t2->lastfree; t2->lsizenode = lsizenode; t2->node = node; t2->lastfree = lastfree; } /* ** Resize table 't' for the new given sizes. Both allocations (for ** the hash part and for the array part) can fail, which creates some ** subtleties. If the first allocation, for the hash part, fails, an ** error is raised and that is it. Otherwise, it copies the elements from ** the shrinking part of the array (if it is shrinking) into the new ** hash. Then it reallocates the array part. If that fails, the table ** is in its original state; the function frees the new hash part and then ** raises the allocation error. Otherwise, it sets the new hash part ** into the table, initializes the new part of the array (if any) with ** nils and reinserts the elements of the old hash back into the new ** parts of the table. */ void luaH_resize (lua_State *L, Table *t, unsigned int newasize, unsigned int nhsize) { unsigned int i; Table newt; /* to keep the new hash part */ unsigned int oldasize = setlimittosize(t); TValue *newarray; /* create new hash part with appropriate size into 'newt' */ setnodevector(L, &newt, nhsize); if (newasize < oldasize) { /* will array shrink? */ t->alimit = newasize; /* pretend array has new size... */ exchangehashpart(t, &newt); /* and new hash */ /* re-insert into the new hash the elements from vanishing slice */ for (i = newasize; i < oldasize; i++) { if (!isempty(&t->array[i])) luaH_setint(L, t, i + 1, &t->array[i]); } t->alimit = oldasize; /* restore current size... */ exchangehashpart(t, &newt); /* and hash (in case of errors) */ } /* allocate new array */ newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue); if (unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */ freehash(L, &newt); /* release new hash part */ luaM_error(L); /* raise error (with array unchanged) */ } /* allocation ok; initialize new part of the array */ exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */ t->array = newarray; /* set new array part */ t->alimit = newasize; for (i = oldasize; i < newasize; i++) /* clear new slice of the array */ setempty(&t->array[i]); /* re-insert elements from old hash part into new parts */ reinsert(L, &newt, t); /* 'newt' now has the old hash */ freehash(L, &newt); /* free old hash part */ } void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { int nsize = allocsizenode(t); luaH_resize(L, t, nasize, nsize); } /* ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i */ static void rehash (lua_State *L, Table *t, const TValue *ek) { unsigned int asize; /* optimal size for array part */ unsigned int na; /* number of keys in the array part */ unsigned int nums[MAXABITS + 1]; int i; int totaluse; for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */ setlimittosize(t); na = numusearray(t, nums); /* count keys in array part */ totaluse = na; /* all those keys are integer keys */ totaluse += numusehash(t, nums, &na); /* count keys in hash part */ /* count extra key */ if (ttisinteger(ek)) na += countint(ivalue(ek), nums); totaluse++; /* compute new size for array part */ asize = computesizes(nums, &na); /* resize the table to new computed sizes */ luaH_resize(L, t, asize, totaluse - na); } /* ** }============================================================= */ Table *luaH_new (lua_State *L) { GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table)); Table *t = gco2t(o); t->metatable = NULL; t->flags = cast_byte(maskflags); /* table has no metamethod fields */ t->array = NULL; t->alimit = 0; setnodevector(L, t, 0); return t; } void luaH_free (lua_State *L, Table *t) { freehash(L, t); luaM_freearray(L, t->array, luaH_realasize(t)); luaM_free(L, t); } static Node *getfreepos (Table *t) { if (!isdummy(t)) { while (t->lastfree > t->node) { t->lastfree--; if (keyisnil(t->lastfree)) return t->lastfree; } } return NULL; /* could not find a free place */ } /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place and ** put new key in its main position; otherwise (colliding node is in its main ** position), new key goes to an empty position. */ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { Node *mp; TValue aux; if (unlikely(ttisnil(key))) luaG_runerror(L, "table index is nil"); else if (ttisfloat(key)) { lua_Number f = fltvalue(key); lua_Integer k; if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */ setivalue(&aux, k); key = &aux; /* insert it as an integer */ } else if (unlikely(luai_numisnan(f))) luaG_runerror(L, "table index is NaN"); } mp = mainpositionTV(t, key); if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */ Node *othern; Node *f = getfreepos(t); /* get a free place */ if (f == NULL) { /* cannot find a free place? */ rehash(L, t, key); /* grow table */ /* whatever called 'newkey' takes care of TM cache */ return luaH_set(L, t, key); /* insert key into grown table */ } lua_assert(!isdummy(t)); othern = mainposition(t, keytt(mp), &keyval(mp)); if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (othern + gnext(othern) != mp) /* find previous */ othern += gnext(othern); gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ if (gnext(mp) != 0) { gnext(f) += cast_int(mp - f); /* correct 'next' */ gnext(mp) = 0; /* now 'mp' is free */ } setempty(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ if (gnext(mp) != 0) gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ else lua_assert(gnext(f) == 0); gnext(mp) = cast_int(f - mp); mp = f; } } setnodekey(L, mp, key); luaC_barrierback(L, obj2gco(t), key); lua_assert(isempty(gval(mp))); return gval(mp); } /* ** Search function for integers. If integer is inside 'alimit', get it ** directly from the array part. Otherwise, if 'alimit' is not equal to ** the real size of the array, key still can be in the array part. In ** this case, try to avoid a call to 'luaH_realasize' when key is just ** one more than the limit (so that it can be incremented without ** changing the real size of the array). */ const TValue *luaH_getint (Table *t, lua_Integer key) { if (l_castS2U(key) - 1u < t->alimit) /* 'key' in [1, t->alimit]? */ return &t->array[key - 1]; else if (!limitequalsasize(t) && /* key still may be in the array part? */ (l_castS2U(key) == t->alimit + 1 || l_castS2U(key) - 1u < luaH_realasize(t))) { t->alimit = cast_uint(key); /* probably '#t' is here now */ return &t->array[key - 1]; } else { Node *n = hashint(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ if (keyisinteger(n) && keyival(n) == key) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) break; n += nx; } } return &absentkey; } } /* ** search function for short strings */ const TValue *luaH_getshortstr (Table *t, TString *key) { Node *n = hashstr(t, key); lua_assert(key->tt == LUA_VSHRSTR); for (;;) { /* check whether 'key' is somewhere in the chain */ if (keyisshrstr(n) && eqshrstr(keystrval(n), key)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return &absentkey; /* not found */ n += nx; } } } const TValue *luaH_getstr (Table *t, TString *key) { if (key->tt == LUA_VSHRSTR) return luaH_getshortstr(t, key); else { /* for long strings, use generic case */ TValue ko; setsvalue(cast(lua_State *, NULL), &ko, key); return getgeneric(t, &ko); } } /* ** main search function */ const TValue *luaH_get (Table *t, const TValue *key) { switch (ttypetag(key)) { case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key)); case LUA_VNUMINT: return luaH_getint(t, ivalue(key)); case LUA_VNIL: return &absentkey; case LUA_VNUMFLT: { lua_Integer k; if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */ return luaH_getint(t, k); /* use specialized version */ /* else... */ } /* FALLTHROUGH */ default: return getgeneric(t, key); } } /* ** beware: when using this function you probably need to check a GC ** barrier and invalidate the TM cache. */ TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { const TValue *p = luaH_get(t, key); if (!isabstkey(p)) return cast(TValue *, p); else return luaH_newkey(L, t, key); } void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { const TValue *p = luaH_getint(t, key); TValue *cell; if (!isabstkey(p)) cell = cast(TValue *, p); else { TValue k; setivalue(&k, key); cell = luaH_newkey(L, t, &k); } setobj2t(L, cell, value); } /* ** Try to find a boundary in the hash part of table 't'. From the ** caller, we know that 'j' is zero or present and that 'j + 1' is ** present. We want to find a larger key that is absent from the ** table, so that we can do a binary search between the two keys to ** find a boundary. We keep doubling 'j' until we get an absent index. ** If the doubling would overflow, we try LUA_MAXINTEGER. If it is ** absent, we are ready for the binary search. ('j', being max integer, ** is larger or equal to 'i', but it cannot be equal because it is ** absent while 'i' is present; so 'j > i'.) Otherwise, 'j' is a ** boundary. ('j + 1' cannot be a present integer key because it is ** not a valid integer in Lua.) */ static lua_Unsigned hash_search (Table *t, lua_Unsigned j) { lua_Unsigned i; if (j == 0) j++; /* the caller ensures 'j + 1' is present */ do { i = j; /* 'i' is a present index */ if (j <= l_castS2U(LUA_MAXINTEGER) / 2) j *= 2; else { j = LUA_MAXINTEGER; if (isempty(luaH_getint(t, j))) /* t[j] not present? */ break; /* 'j' now is an absent index */ else /* weird case */ return j; /* well, max integer is a boundary... */ } } while (!isempty(luaH_getint(t, j))); /* repeat until an absent t[j] */ /* i < j && t[i] present && t[j] absent */ while (j - i > 1u) { /* do a binary search between them */ lua_Unsigned m = (i + j) / 2; if (isempty(luaH_getint(t, m))) j = m; else i = m; } return i; } static unsigned int binsearch (const TValue *array, unsigned int i, unsigned int j) { while (j - i > 1u) { /* binary search */ unsigned int m = (i + j) / 2; if (isempty(&array[m - 1])) j = m; else i = m; } return i; } /* ** Try to find a boundary in table 't'. (A 'boundary' is an integer index ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent ** and 'maxinteger' if t[maxinteger] is present.) ** (In the next explanation, we use Lua indices, that is, with base 1. ** The code itself uses base 0 when indexing the array part of the table.) ** The code starts with 'limit = t->alimit', a position in the array ** part that may be a boundary. ** ** (1) If 't[limit]' is empty, there must be a boundary before it. ** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1' ** is present. If so, it is a boundary. Otherwise, do a binary search ** between 0 and limit to find a boundary. In both cases, try to ** use this boundary as the new 'alimit', as a hint for the next call. ** ** (2) If 't[limit]' is not empty and the array has more elements ** after 'limit', try to find a boundary there. Again, try first ** the special case (which should be quite frequent) where 'limit+1' ** is empty, so that 'limit' is a boundary. Otherwise, check the ** last element of the array part. If it is empty, there must be a ** boundary between the old limit (present) and the last element ** (absent), which is found with a binary search. (This boundary always ** can be a new limit.) ** ** (3) The last case is when there are no elements in the array part ** (limit == 0) or its last element (the new limit) is present. ** In this case, must check the hash part. If there is no hash part ** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call ** 'hash_search' to find a boundary in the hash part of the table. ** (In those cases, the boundary is not inside the array part, and ** therefore cannot be used as a new limit.) */ lua_Unsigned luaH_getn (Table *t) { unsigned int limit = t->alimit; if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */ /* there must be a boundary before 'limit' */ if (limit >= 2 && !isempty(&t->array[limit - 2])) { /* 'limit - 1' is a boundary; can it be a new limit? */ if (ispow2realasize(t) && !ispow2(limit - 1)) { t->alimit = limit - 1; setnorealasize(t); /* now 'alimit' is not the real size */ } return limit - 1; } else { /* must search for a boundary in [0, limit] */ unsigned int boundary = binsearch(t->array, 0, limit); /* can this boundary represent the real size of the array? */ if (ispow2realasize(t) && boundary > luaH_realasize(t) / 2) { t->alimit = boundary; /* use it as the new limit */ setnorealasize(t); } return boundary; } } /* 'limit' is zero or present in table */ if (!limitequalsasize(t)) { /* (2)? */ /* 'limit' > 0 and array has more elements after 'limit' */ if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */ return limit; /* this is the boundary */ /* else, try last element in the array */ limit = luaH_realasize(t); if (isempty(&t->array[limit - 1])) { /* empty? */ /* there must be a boundary in the array after old limit, and it must be a valid new limit */ unsigned int boundary = binsearch(t->array, t->alimit, limit); t->alimit = boundary; return boundary; } /* else, new limit is present in the table; check the hash part */ } /* (3) 'limit' is the last element and either is zero or present in table */ lua_assert(limit == luaH_realasize(t) && (limit == 0 || !isempty(&t->array[limit - 1]))); if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1)))) return limit; /* 'limit + 1' is absent */ else /* 'limit + 1' is also present */ return hash_search(t, limit); } #if defined(LUA_DEBUG) /* export these functions for the test library */ Node *luaH_mainposition (const Table *t, const TValue *key) { return mainpositionTV(t, key); } int luaH_isdummy (const Table *t) { return isdummy(t); } #endif
xLua/build/lua-5.4.1/src/ltable.c/0
{ "file_path": "xLua/build/lua-5.4.1/src/ltable.c", "repo_id": "xLua", "token_count": 11525 }
1,932
------------------------------------------------------------------------------ -- DynASM MIPS module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "mips", description = "DynASM MIPS module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, sar, tohex = bit.band, bit.lshift, bit.arshift, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(0xff000000 + w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n >= 0xff000000 then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp="r29", ra="r31" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r29" then return "sp" elseif s == "r31" then return "ra" end return s end ------------------------------------------------------------------------------ -- Template strings for MIPS instructions. local map_op = { -- First-level opcodes. j_1 = "08000000J", jal_1 = "0c000000J", b_1 = "10000000B", beqz_2 = "10000000SB", beq_3 = "10000000STB", bnez_2 = "14000000SB", bne_3 = "14000000STB", blez_2 = "18000000SB", bgtz_2 = "1c000000SB", addi_3 = "20000000TSI", li_2 = "24000000TI", addiu_3 = "24000000TSI", slti_3 = "28000000TSI", sltiu_3 = "2c000000TSI", andi_3 = "30000000TSU", lu_2 = "34000000TU", ori_3 = "34000000TSU", xori_3 = "38000000TSU", lui_2 = "3c000000TU", beqzl_2 = "50000000SB", beql_3 = "50000000STB", bnezl_2 = "54000000SB", bnel_3 = "54000000STB", blezl_2 = "58000000SB", bgtzl_2 = "5c000000SB", lb_2 = "80000000TO", lh_2 = "84000000TO", lwl_2 = "88000000TO", lw_2 = "8c000000TO", lbu_2 = "90000000TO", lhu_2 = "94000000TO", lwr_2 = "98000000TO", sb_2 = "a0000000TO", sh_2 = "a4000000TO", swl_2 = "a8000000TO", sw_2 = "ac000000TO", swr_2 = "b8000000TO", cache_2 = "bc000000NO", ll_2 = "c0000000TO", lwc1_2 = "c4000000HO", pref_2 = "cc000000NO", ldc1_2 = "d4000000HO", sc_2 = "e0000000TO", swc1_2 = "e4000000HO", sdc1_2 = "f4000000HO", -- Opcode SPECIAL. nop_0 = "00000000", sll_3 = "00000000DTA", movf_2 = "00000001DS", movf_3 = "00000001DSC", movt_2 = "00010001DS", movt_3 = "00010001DSC", srl_3 = "00000002DTA", rotr_3 = "00200002DTA", sra_3 = "00000003DTA", sllv_3 = "00000004DTS", srlv_3 = "00000006DTS", rotrv_3 = "00000046DTS", srav_3 = "00000007DTS", jr_1 = "00000008S", jalr_1 = "0000f809S", jalr_2 = "00000009DS", movz_3 = "0000000aDST", movn_3 = "0000000bDST", syscall_0 = "0000000c", syscall_1 = "0000000cY", break_0 = "0000000d", break_1 = "0000000dY", sync_0 = "0000000f", mfhi_1 = "00000010D", mthi_1 = "00000011S", mflo_1 = "00000012D", mtlo_1 = "00000013S", mult_2 = "00000018ST", multu_2 = "00000019ST", div_2 = "0000001aST", divu_2 = "0000001bST", add_3 = "00000020DST", move_2 = "00000021DS", addu_3 = "00000021DST", sub_3 = "00000022DST", negu_2 = "00000023DT", subu_3 = "00000023DST", and_3 = "00000024DST", or_3 = "00000025DST", xor_3 = "00000026DST", not_2 = "00000027DS", nor_3 = "00000027DST", slt_3 = "0000002aDST", sltu_3 = "0000002bDST", tge_2 = "00000030ST", tge_3 = "00000030STZ", tgeu_2 = "00000031ST", tgeu_3 = "00000031STZ", tlt_2 = "00000032ST", tlt_3 = "00000032STZ", tltu_2 = "00000033ST", tltu_3 = "00000033STZ", teq_2 = "00000034ST", teq_3 = "00000034STZ", tne_2 = "00000036ST", tne_3 = "00000036STZ", -- Opcode REGIMM. bltz_2 = "04000000SB", bgez_2 = "04010000SB", bltzl_2 = "04020000SB", bgezl_2 = "04030000SB", tgei_2 = "04080000SI", tgeiu_2 = "04090000SI", tlti_2 = "040a0000SI", tltiu_2 = "040b0000SI", teqi_2 = "040c0000SI", tnei_2 = "040e0000SI", bltzal_2 = "04100000SB", bal_1 = "04110000B", bgezal_2 = "04110000SB", bltzall_2 = "04120000SB", bgezall_2 = "04130000SB", synci_1 = "041f0000O", -- Opcode SPECIAL2. madd_2 = "70000000ST", maddu_2 = "70000001ST", mul_3 = "70000002DST", msub_2 = "70000004ST", msubu_2 = "70000005ST", clz_2 = "70000020DS=", clo_2 = "70000021DS=", sdbbp_0 = "7000003f", sdbbp_1 = "7000003fY", -- Opcode SPECIAL3. ext_4 = "7c000000TSAM", -- Note: last arg is msbd = size-1 ins_4 = "7c000004TSAM", -- Note: last arg is msb = pos+size-1 wsbh_2 = "7c0000a0DT", seb_2 = "7c000420DT", seh_2 = "7c000620DT", rdhwr_2 = "7c00003bTD", -- Opcode COP0. mfc0_2 = "40000000TD", mfc0_3 = "40000000TDW", mtc0_2 = "40800000TD", mtc0_3 = "40800000TDW", rdpgpr_2 = "41400000DT", di_0 = "41606000", di_1 = "41606000T", ei_0 = "41606020", ei_1 = "41606020T", wrpgpr_2 = "41c00000DT", tlbr_0 = "42000001", tlbwi_0 = "42000002", tlbwr_0 = "42000006", tlbp_0 = "42000008", eret_0 = "42000018", deret_0 = "4200001f", wait_0 = "42000020", -- Opcode COP1. mfc1_2 = "44000000TG", cfc1_2 = "44400000TG", mfhc1_2 = "44600000TG", mtc1_2 = "44800000TG", ctc1_2 = "44c00000TG", mthc1_2 = "44e00000TG", bc1f_1 = "45000000B", bc1f_2 = "45000000CB", bc1t_1 = "45010000B", bc1t_2 = "45010000CB", bc1fl_1 = "45020000B", bc1fl_2 = "45020000CB", bc1tl_1 = "45030000B", bc1tl_2 = "45030000CB", ["add.s_3"] = "46000000FGH", ["sub.s_3"] = "46000001FGH", ["mul.s_3"] = "46000002FGH", ["div.s_3"] = "46000003FGH", ["sqrt.s_2"] = "46000004FG", ["abs.s_2"] = "46000005FG", ["mov.s_2"] = "46000006FG", ["neg.s_2"] = "46000007FG", ["round.l.s_2"] = "46000008FG", ["trunc.l.s_2"] = "46000009FG", ["ceil.l.s_2"] = "4600000aFG", ["floor.l.s_2"] = "4600000bFG", ["round.w.s_2"] = "4600000cFG", ["trunc.w.s_2"] = "4600000dFG", ["ceil.w.s_2"] = "4600000eFG", ["floor.w.s_2"] = "4600000fFG", ["movf.s_2"] = "46000011FG", ["movf.s_3"] = "46000011FGC", ["movt.s_2"] = "46010011FG", ["movt.s_3"] = "46010011FGC", ["movz.s_3"] = "46000012FGT", ["movn.s_3"] = "46000013FGT", ["recip.s_2"] = "46000015FG", ["rsqrt.s_2"] = "46000016FG", ["cvt.d.s_2"] = "46000021FG", ["cvt.w.s_2"] = "46000024FG", ["cvt.l.s_2"] = "46000025FG", ["cvt.ps.s_3"] = "46000026FGH", ["c.f.s_2"] = "46000030GH", ["c.f.s_3"] = "46000030VGH", ["c.un.s_2"] = "46000031GH", ["c.un.s_3"] = "46000031VGH", ["c.eq.s_2"] = "46000032GH", ["c.eq.s_3"] = "46000032VGH", ["c.ueq.s_2"] = "46000033GH", ["c.ueq.s_3"] = "46000033VGH", ["c.olt.s_2"] = "46000034GH", ["c.olt.s_3"] = "46000034VGH", ["c.ult.s_2"] = "46000035GH", ["c.ult.s_3"] = "46000035VGH", ["c.ole.s_2"] = "46000036GH", ["c.ole.s_3"] = "46000036VGH", ["c.ule.s_2"] = "46000037GH", ["c.ule.s_3"] = "46000037VGH", ["c.sf.s_2"] = "46000038GH", ["c.sf.s_3"] = "46000038VGH", ["c.ngle.s_2"] = "46000039GH", ["c.ngle.s_3"] = "46000039VGH", ["c.seq.s_2"] = "4600003aGH", ["c.seq.s_3"] = "4600003aVGH", ["c.ngl.s_2"] = "4600003bGH", ["c.ngl.s_3"] = "4600003bVGH", ["c.lt.s_2"] = "4600003cGH", ["c.lt.s_3"] = "4600003cVGH", ["c.nge.s_2"] = "4600003dGH", ["c.nge.s_3"] = "4600003dVGH", ["c.le.s_2"] = "4600003eGH", ["c.le.s_3"] = "4600003eVGH", ["c.ngt.s_2"] = "4600003fGH", ["c.ngt.s_3"] = "4600003fVGH", ["add.d_3"] = "46200000FGH", ["sub.d_3"] = "46200001FGH", ["mul.d_3"] = "46200002FGH", ["div.d_3"] = "46200003FGH", ["sqrt.d_2"] = "46200004FG", ["abs.d_2"] = "46200005FG", ["mov.d_2"] = "46200006FG", ["neg.d_2"] = "46200007FG", ["round.l.d_2"] = "46200008FG", ["trunc.l.d_2"] = "46200009FG", ["ceil.l.d_2"] = "4620000aFG", ["floor.l.d_2"] = "4620000bFG", ["round.w.d_2"] = "4620000cFG", ["trunc.w.d_2"] = "4620000dFG", ["ceil.w.d_2"] = "4620000eFG", ["floor.w.d_2"] = "4620000fFG", ["movf.d_2"] = "46200011FG", ["movf.d_3"] = "46200011FGC", ["movt.d_2"] = "46210011FG", ["movt.d_3"] = "46210011FGC", ["movz.d_3"] = "46200012FGT", ["movn.d_3"] = "46200013FGT", ["recip.d_2"] = "46200015FG", ["rsqrt.d_2"] = "46200016FG", ["cvt.s.d_2"] = "46200020FG", ["cvt.w.d_2"] = "46200024FG", ["cvt.l.d_2"] = "46200025FG", ["c.f.d_2"] = "46200030GH", ["c.f.d_3"] = "46200030VGH", ["c.un.d_2"] = "46200031GH", ["c.un.d_3"] = "46200031VGH", ["c.eq.d_2"] = "46200032GH", ["c.eq.d_3"] = "46200032VGH", ["c.ueq.d_2"] = "46200033GH", ["c.ueq.d_3"] = "46200033VGH", ["c.olt.d_2"] = "46200034GH", ["c.olt.d_3"] = "46200034VGH", ["c.ult.d_2"] = "46200035GH", ["c.ult.d_3"] = "46200035VGH", ["c.ole.d_2"] = "46200036GH", ["c.ole.d_3"] = "46200036VGH", ["c.ule.d_2"] = "46200037GH", ["c.ule.d_3"] = "46200037VGH", ["c.sf.d_2"] = "46200038GH", ["c.sf.d_3"] = "46200038VGH", ["c.ngle.d_2"] = "46200039GH", ["c.ngle.d_3"] = "46200039VGH", ["c.seq.d_2"] = "4620003aGH", ["c.seq.d_3"] = "4620003aVGH", ["c.ngl.d_2"] = "4620003bGH", ["c.ngl.d_3"] = "4620003bVGH", ["c.lt.d_2"] = "4620003cGH", ["c.lt.d_3"] = "4620003cVGH", ["c.nge.d_2"] = "4620003dGH", ["c.nge.d_3"] = "4620003dVGH", ["c.le.d_2"] = "4620003eGH", ["c.le.d_3"] = "4620003eVGH", ["c.ngt.d_2"] = "4620003fGH", ["c.ngt.d_3"] = "4620003fVGH", ["add.ps_3"] = "46c00000FGH", ["sub.ps_3"] = "46c00001FGH", ["mul.ps_3"] = "46c00002FGH", ["abs.ps_2"] = "46c00005FG", ["mov.ps_2"] = "46c00006FG", ["neg.ps_2"] = "46c00007FG", ["movf.ps_2"] = "46c00011FG", ["movf.ps_3"] = "46c00011FGC", ["movt.ps_2"] = "46c10011FG", ["movt.ps_3"] = "46c10011FGC", ["movz.ps_3"] = "46c00012FGT", ["movn.ps_3"] = "46c00013FGT", ["cvt.s.pu_2"] = "46c00020FG", ["cvt.s.pl_2"] = "46c00028FG", ["pll.ps_3"] = "46c0002cFGH", ["plu.ps_3"] = "46c0002dFGH", ["pul.ps_3"] = "46c0002eFGH", ["puu.ps_3"] = "46c0002fFGH", ["c.f.ps_2"] = "46c00030GH", ["c.f.ps_3"] = "46c00030VGH", ["c.un.ps_2"] = "46c00031GH", ["c.un.ps_3"] = "46c00031VGH", ["c.eq.ps_2"] = "46c00032GH", ["c.eq.ps_3"] = "46c00032VGH", ["c.ueq.ps_2"] = "46c00033GH", ["c.ueq.ps_3"] = "46c00033VGH", ["c.olt.ps_2"] = "46c00034GH", ["c.olt.ps_3"] = "46c00034VGH", ["c.ult.ps_2"] = "46c00035GH", ["c.ult.ps_3"] = "46c00035VGH", ["c.ole.ps_2"] = "46c00036GH", ["c.ole.ps_3"] = "46c00036VGH", ["c.ule.ps_2"] = "46c00037GH", ["c.ule.ps_3"] = "46c00037VGH", ["c.sf.ps_2"] = "46c00038GH", ["c.sf.ps_3"] = "46c00038VGH", ["c.ngle.ps_2"] = "46c00039GH", ["c.ngle.ps_3"] = "46c00039VGH", ["c.seq.ps_2"] = "46c0003aGH", ["c.seq.ps_3"] = "46c0003aVGH", ["c.ngl.ps_2"] = "46c0003bGH", ["c.ngl.ps_3"] = "46c0003bVGH", ["c.lt.ps_2"] = "46c0003cGH", ["c.lt.ps_3"] = "46c0003cVGH", ["c.nge.ps_2"] = "46c0003dGH", ["c.nge.ps_3"] = "46c0003dVGH", ["c.le.ps_2"] = "46c0003eGH", ["c.le.ps_3"] = "46c0003eVGH", ["c.ngt.ps_2"] = "46c0003fGH", ["c.ngt.ps_3"] = "46c0003fVGH", ["cvt.s.w_2"] = "46800020FG", ["cvt.d.w_2"] = "46800021FG", ["cvt.s.l_2"] = "46a00020FG", ["cvt.d.l_2"] = "46a00021FG", -- Opcode COP1X. lwxc1_2 = "4c000000FX", ldxc1_2 = "4c000001FX", luxc1_2 = "4c000005FX", swxc1_2 = "4c000008FX", sdxc1_2 = "4c000009FX", suxc1_2 = "4c00000dFX", prefx_2 = "4c00000fMX", ["alnv.ps_4"] = "4c00001eFGHS", ["madd.s_4"] = "4c000020FRGH", ["madd.d_4"] = "4c000021FRGH", ["madd.ps_4"] = "4c000026FRGH", ["msub.s_4"] = "4c000028FRGH", ["msub.d_4"] = "4c000029FRGH", ["msub.ps_4"] = "4c00002eFRGH", ["nmadd.s_4"] = "4c000030FRGH", ["nmadd.d_4"] = "4c000031FRGH", ["nmadd.ps_4"] = "4c000036FRGH", ["nmsub.s_4"] = "4c000038FRGH", ["nmsub.d_4"] = "4c000039FRGH", ["nmsub.ps_4"] = "4c00003eFRGH", } ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") elseif match(imm, "^[rf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([rf][1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = shl(parse_gpr(reg), 21) local extname = match(imm, "^extern%s+(%S+)$") if extname then waction("REL_EXT", map_extern[extname], nil, 1) return r else return r + parse_imm(imm, 16, 0, 0, true) end end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 21) end end werror("bad displacement `"..disp.."'") end local function parse_index(idx) local rt, rs = match(idx, "^(.*)%(([%w_:]+)%)$") if rt then rt = parse_gpr(rt) rs = parse_gpr(rs) return shl(rt, 16) + shl(rs, 21) end werror("bad index `"..idx.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n = 1 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 2 positions (ins/ext). if secpos+2 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "D" then op = op + shl(parse_gpr(params[n]), 11); n = n + 1 elseif p == "T" then op = op + shl(parse_gpr(params[n]), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(params[n]), 21); n = n + 1 elseif p == "F" then op = op + shl(parse_fpr(params[n]), 6); n = n + 1 elseif p == "G" then op = op + shl(parse_fpr(params[n]), 11); n = n + 1 elseif p == "H" then op = op + shl(parse_fpr(params[n]), 16); n = n + 1 elseif p == "R" then op = op + shl(parse_fpr(params[n]), 21); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "O" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "X" then op = op + parse_index(params[n]); n = n + 1 elseif p == "B" or p == "J" then local mode, n, s = parse_label(params[n], false) if p == "B" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "A" then op = op + parse_imm(params[n], 5, 6, 0, false); n = n + 1 elseif p == "M" then op = op + parse_imm(params[n], 5, 11, 0, false); n = n + 1 elseif p == "N" then op = op + parse_imm(params[n], 5, 16, 0, false); n = n + 1 elseif p == "C" then op = op + parse_imm(params[n], 3, 18, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(params[n], 3, 8, 0, false); n = n + 1 elseif p == "W" then op = op + parse_imm(params[n], 3, 0, 0, false); n = n + 1 elseif p == "Y" then op = op + parse_imm(params[n], 20, 6, 0, false); n = n + 1 elseif p == "Z" then op = op + parse_imm(params[n], 10, 6, 0, false); n = n + 1 elseif p == "=" then op = op + shl(band(op, 0xf800), 5) -- Copy D to T for clz, clo. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
xLua/build/luajit-2.1.0b2/dynasm/dasm_mips.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b2/dynasm/dasm_mips.lua", "repo_id": "xLua", "token_count": 12693 }
1,933
---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module is a simple command line interface to the built-in -- low-overhead profiler of LuaJIT. -- -- The lower-level API of the profiler is accessible via the "jit.profile" -- module or the luaJIT_profile_* C API. -- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local vmdef = require("jit.vmdef") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x) return vmdef.ffnames[tonumber(x)] end) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k, v in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i=1,n do local k = t[i] local v = count1[k] local pct = floor(v*100/samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v*100/samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files+1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i=1,ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] if ann ~= 0 then local v2 = fl[n+ann] if show then if v2 then show = n+ann elseif v then show = n elseif show+ann < n then show = false end elseif v2 then show = n+ann out:write(format("@@ %d @@\n", n)) end if not show then goto next end end if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end ::next:: n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or (prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
xLua/build/luajit-2.1.0b2/src/jit/p.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/jit/p.lua", "repo_id": "xLua", "token_count": 3552 }
1,934
/* ** Error handling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_err_c #define LUA_CORE #include "lj_obj.h" #include "lj_err.h" #include "lj_debug.h" #include "lj_str.h" #include "lj_func.h" #include "lj_state.h" #include "lj_frame.h" #include "lj_ff.h" #include "lj_trace.h" #include "lj_vm.h" #include "lj_strfmt.h" /* ** LuaJIT can either use internal or external frame unwinding: ** ** - Internal frame unwinding (INT) is free-standing and doesn't require ** any OS or library support. ** ** - External frame unwinding (EXT) uses the system-provided unwind handler. ** ** Pros and Cons: ** ** - EXT requires unwind tables for *all* functions on the C stack between ** the pcall/catch and the error/throw. This is the default on x64, ** but needs to be manually enabled on x86/PPC for non-C++ code. ** ** - INT is faster when actually throwing errors (but this happens rarely). ** Setting up error handlers is zero-cost in any case. ** ** - EXT provides full interoperability with C++ exceptions. You can throw ** Lua errors or C++ exceptions through a mix of Lua frames and C++ frames. ** C++ destructors are called as needed. C++ exceptions caught by pcall ** are converted to the string "C++ exception". Lua errors can be caught ** with catch (...) in C++. ** ** - INT has only limited support for automatically catching C++ exceptions ** on POSIX systems using DWARF2 stack unwinding. Other systems may use ** the wrapper function feature. Lua errors thrown through C++ frames ** cannot be caught by C++ code and C++ destructors are not run. ** ** EXT is the default on x64 systems, INT is the default on all other systems. ** ** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack ** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled ** with -funwind-tables (or -fexceptions). This includes LuaJIT itself (set ** TARGET_CFLAGS), all of your C/Lua binding code, all loadable C modules ** and all C libraries that have callbacks which may be used to call back ** into Lua. C++ code must *not* be compiled with -fno-exceptions. ** ** EXT cannot be enabled on WIN32 since system exceptions use code-driven SEH. ** EXT is mandatory on WIN64 since the calling convention has an abundance ** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15). ** The POSIX/x64 interpreter only saves r12/r13 for INT (e.g. PS4). */ #if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL)) && !LJ_NO_UNWIND #define LJ_UNWIND_EXT 1 #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS #define LJ_UNWIND_EXT 1 #endif /* -- Error messages ------------------------------------------------------ */ /* Error message strings. */ LJ_DATADEF const char *lj_err_allmsg = #define ERRDEF(name, msg) msg "\0" #include "lj_errmsg.h" ; /* -- Internal frame unwinding -------------------------------------------- */ /* Unwind Lua stack and move error message to new top. */ LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top) { lj_func_closeuv(L, top); if (top < L->top-1) { copyTV(L, top, L->top-1); L->top = top+1; } lj_state_relimitstack(L); } /* Unwind until stop frame. Optionally cleanup frames. */ static void *err_unwind(lua_State *L, void *stopcf, int errcode) { TValue *frame = L->base-1; void *cf = L->cframe; while (cf) { int32_t nres = cframe_nres(cframe_raw(cf)); if (nres < 0) { /* C frame without Lua frame? */ TValue *top = restorestack(L, -nres); if (frame < top) { /* Frame reached? */ if (errcode) { L->base = frame+1; L->cframe = cframe_prev(cf); unwindstack(L, top); } return cf; } } if (frame <= tvref(L->stack)+LJ_FR2) break; switch (frame_typep(frame)) { case FRAME_LUA: /* Lua frame. */ case FRAME_LUAP: frame = frame_prevl(frame); break; case FRAME_C: /* C frame. */ unwind_c: #if LJ_UNWIND_EXT if (errcode) { L->base = frame_prevd(frame) + 1; L->cframe = cframe_prev(cf); unwindstack(L, frame - LJ_FR2); } else if (cf != stopcf) { cf = cframe_prev(cf); frame = frame_prevd(frame); break; } return NULL; /* Continue unwinding. */ #else UNUSED(stopcf); cf = cframe_prev(cf); frame = frame_prevd(frame); break; #endif case FRAME_CP: /* Protected C frame. */ if (cframe_canyield(cf)) { /* Resume? */ if (errcode) { hook_leave(G(L)); /* Assumes nobody uses coroutines inside hooks. */ L->cframe = NULL; L->status = (uint8_t)errcode; } return cf; } if (errcode) { L->base = frame_prevd(frame) + 1; L->cframe = cframe_prev(cf); unwindstack(L, frame - LJ_FR2); } return cf; case FRAME_CONT: /* Continuation frame. */ if (frame_iscont_fficb(frame)) goto unwind_c; case FRAME_VARG: /* Vararg frame. */ frame = frame_prevd(frame); break; case FRAME_PCALL: /* FF pcall() frame. */ case FRAME_PCALLH: /* FF pcall() frame inside hook. */ if (errcode) { if (errcode == LUA_YIELD) { frame = frame_prevd(frame); break; } if (frame_typep(frame) == FRAME_PCALL) hook_leave(G(L)); L->base = frame_prevd(frame) + 1; L->cframe = cf; unwindstack(L, L->base); } return (void *)((intptr_t)cf | CFRAME_UNWIND_FF); } } /* No C frame. */ if (errcode) { L->base = tvref(L->stack)+1+LJ_FR2; L->cframe = NULL; unwindstack(L, L->base); if (G(L)->panic) G(L)->panic(L); exit(EXIT_FAILURE); } return L; /* Anything non-NULL will do. */ } /* -- External frame unwinding -------------------------------------------- */ #if defined(__GNUC__) && !LJ_NO_UNWIND && !LJ_ABI_WIN /* ** We have to use our own definitions instead of the mandatory (!) unwind.h, ** since various OS, distros and compilers mess up the header installation. */ typedef struct _Unwind_Context _Unwind_Context; #define _URC_OK 0 #define _URC_FATAL_PHASE1_ERROR 3 #define _URC_HANDLER_FOUND 6 #define _URC_INSTALL_CONTEXT 7 #define _URC_CONTINUE_UNWIND 8 #define _URC_FAILURE 9 #define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */ #define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c)) #define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff) #define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff)) #if !LJ_TARGET_ARM typedef struct _Unwind_Exception { uint64_t exclass; void (*excleanup)(int, struct _Unwind_Exception *); uintptr_t p1, p2; } __attribute__((__aligned__)) _Unwind_Exception; extern uintptr_t _Unwind_GetCFA(_Unwind_Context *); extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t); extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t); extern void _Unwind_DeleteException(_Unwind_Exception *); extern int _Unwind_RaiseException(_Unwind_Exception *); #define _UA_SEARCH_PHASE 1 #define _UA_CLEANUP_PHASE 2 #define _UA_HANDLER_FRAME 4 #define _UA_FORCE_UNWIND 8 /* DWARF2 personality handler referenced from interpreter .eh_frame. */ LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions, uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx) { void *cf; lua_State *L; if (version != 1) return _URC_FATAL_PHASE1_ERROR; UNUSED(uexclass); cf = (void *)_Unwind_GetCFA(ctx); L = cframe_L(cf); if ((actions & _UA_SEARCH_PHASE)) { #if LJ_UNWIND_EXT if (err_unwind(L, cf, 0) == NULL) return _URC_CONTINUE_UNWIND; #endif if (!LJ_UEXCLASS_CHECK(uexclass)) { setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP)); } return _URC_HANDLER_FOUND; } if ((actions & _UA_CLEANUP_PHASE)) { int errcode; if (LJ_UEXCLASS_CHECK(uexclass)) { errcode = LJ_UEXCLASS_ERRCODE(uexclass); } else { if ((actions & _UA_HANDLER_FRAME)) _Unwind_DeleteException(uex); errcode = LUA_ERRRUN; } #if LJ_UNWIND_EXT cf = err_unwind(L, cf, errcode); if ((actions & _UA_FORCE_UNWIND)) { return _URC_CONTINUE_UNWIND; } else if (cf) { _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode); _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ? lj_vm_unwind_ff_eh : lj_vm_unwind_c_eh)); return _URC_INSTALL_CONTEXT; } #if LJ_TARGET_X86ORX64 else if ((actions & _UA_HANDLER_FRAME)) { /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/ ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h */ _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode); _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow); return _URC_INSTALL_CONTEXT; } #endif #else /* This is not the proper way to escape from the unwinder. We get away with ** it on non-x64 because the interpreter restores all callee-saved regs. */ lj_err_throw(L, errcode); #endif } return _URC_CONTINUE_UNWIND; } #if LJ_UNWIND_EXT #if LJ_TARGET_OSX || defined(__OpenBSD__) /* Sorry, no thread safety for OSX. Complain to Apple, not me. */ static _Unwind_Exception static_uex; #else static __thread _Unwind_Exception static_uex; #endif /* Raise DWARF2 exception. */ static void err_raise_ext(int errcode) { static_uex.exclass = LJ_UEXCLASS_MAKE(errcode); static_uex.excleanup = NULL; _Unwind_RaiseException(&static_uex); } #endif #else /* LJ_TARGET_ARM */ #define _US_VIRTUAL_UNWIND_FRAME 0 #define _US_UNWIND_FRAME_STARTING 1 #define _US_ACTION_MASK 3 #define _US_FORCE_UNWIND 8 typedef struct _Unwind_Control_Block _Unwind_Control_Block; typedef struct _Unwind_Context _Unwind_Context; struct _Unwind_Control_Block { uint64_t exclass; uint32_t misc[20]; }; extern int _Unwind_RaiseException(_Unwind_Control_Block *); extern int __gnu_unwind_frame(_Unwind_Control_Block *, _Unwind_Context *); extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *); extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *); static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r) { uint32_t v; _Unwind_VRS_Get(ctx, 0, r, 0, &v); return v; } static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v) { _Unwind_VRS_Set(ctx, 0, r, 0, &v); } extern void lj_vm_unwind_ext(void); /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */ LJ_FUNCA int lj_err_unwind_arm(int state, _Unwind_Control_Block *ucb, _Unwind_Context *ctx) { void *cf = (void *)_Unwind_GetGR(ctx, 13); lua_State *L = cframe_L(cf); int errcode; switch ((state & _US_ACTION_MASK)) { case _US_VIRTUAL_UNWIND_FRAME: if ((state & _US_FORCE_UNWIND)) break; return _URC_HANDLER_FOUND; case _US_UNWIND_FRAME_STARTING: if (LJ_UEXCLASS_CHECK(ucb->exclass)) { errcode = LJ_UEXCLASS_ERRCODE(ucb->exclass); } else { errcode = LUA_ERRRUN; setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP)); } cf = err_unwind(L, cf, errcode); if ((state & _US_FORCE_UNWIND) || cf == NULL) break; _Unwind_SetGR(ctx, 15, (uint32_t)lj_vm_unwind_ext); _Unwind_SetGR(ctx, 0, (uint32_t)ucb); _Unwind_SetGR(ctx, 1, (uint32_t)errcode); _Unwind_SetGR(ctx, 2, cframe_unwind_ff(cf) ? (uint32_t)lj_vm_unwind_ff_eh : (uint32_t)lj_vm_unwind_c_eh); return _URC_INSTALL_CONTEXT; default: return _URC_FAILURE; } if (__gnu_unwind_frame(ucb, ctx) != _URC_OK) return _URC_FAILURE; return _URC_CONTINUE_UNWIND; } #if LJ_UNWIND_EXT static __thread _Unwind_Control_Block static_uex; static void err_raise_ext(int errcode) { memset(&static_uex, 0, sizeof(static_uex)); static_uex.exclass = LJ_UEXCLASS_MAKE(errcode); _Unwind_RaiseException(&static_uex); } #endif #endif /* LJ_TARGET_ARM */ #elif LJ_TARGET_X64 && LJ_ABI_WIN /* ** Someone in Redmond owes me several days of my life. A lot of this is ** undocumented or just plain wrong on MSDN. Some of it can be gathered ** from 3rd party docs or must be found by trial-and-error. They really ** don't want you to write your own language-specific exception handler ** or to interact gracefully with MSVC. :-( ** ** Apparently MSVC doesn't call C++ destructors for foreign exceptions ** unless you compile your C++ code with /EHa. Unfortunately this means ** catch (...) also catches things like access violations. The use of ** _set_se_translator doesn't really help, because it requires /EHa, too. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> /* Taken from: http://www.nynaeve.net/?p=99 */ typedef struct UndocumentedDispatcherContext { ULONG64 ControlPc; ULONG64 ImageBase; PRUNTIME_FUNCTION FunctionEntry; ULONG64 EstablisherFrame; ULONG64 TargetIp; PCONTEXT ContextRecord; void (*LanguageHandler)(void); PVOID HandlerData; PUNWIND_HISTORY_TABLE HistoryTable; ULONG ScopeIndex; ULONG Fill0; } UndocumentedDispatcherContext; /* Another wild guess. */ extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow); #ifdef MINGW_SDK_INIT /* Workaround for broken MinGW64 declaration. */ VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx"); #define RtlUnwindEx RtlUnwindEx_FIXED #endif #define LJ_MSVC_EXCODE ((DWORD)0xe06d7363) #define LJ_GCC_EXCODE ((DWORD)0x20474343) #define LJ_EXCODE ((DWORD)0xe24c4a00) #define LJ_EXCODE_MAKE(c) (LJ_EXCODE | (DWORD)(c)) #define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff) #define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff)) /* Win64 exception handler for interpreter frame. */ LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec, void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch) { lua_State *L = cframe_L(cf); int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ? LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN; if ((rec->ExceptionFlags & 6)) { /* EH_UNWINDING|EH_EXIT_UNWIND */ /* Unwind internal frames. */ err_unwind(L, cf, errcode); } else { void *cf2 = err_unwind(L, cf, 0); if (cf2) { /* We catch it, so start unwinding the upper frames. */ if (rec->ExceptionCode == LJ_MSVC_EXCODE || rec->ExceptionCode == LJ_GCC_EXCODE) { #if LJ_TARGET_WINDOWS __DestructExceptionObject(rec, 1); #endif setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP)); } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) { /* Don't catch access violations etc. */ return ExceptionContinueSearch; } /* Unwind the stack and call all handlers for all lower C frames ** (including ourselves) again with EH_UNWINDING set. Then set ** rsp = cf, rax = errcode and jump to the specified target. */ RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ? lj_vm_unwind_ff_eh : lj_vm_unwind_c_eh), rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable); /* RtlUnwindEx should never return. */ } } return ExceptionContinueSearch; } /* Raise Windows exception. */ static void err_raise_ext(int errcode) { RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL); } #endif /* -- Error handling ------------------------------------------------------ */ /* Throw error. Find catch frame, unwind stack and continue. */ LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode) { global_State *g = G(L); lj_trace_abort(g); setmref(g->jit_base, NULL); L->status = 0; #if LJ_UNWIND_EXT err_raise_ext(errcode); /* ** A return from this function signals a corrupt C stack that cannot be ** unwound. We have no choice but to call the panic function and exit. ** ** Usually this is caused by a C function without unwind information. ** This should never happen on x64, but may happen if you've manually ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every* ** non-C++ file with -funwind-tables. */ if (G(L)->panic) G(L)->panic(L); #else { void *cf = err_unwind(L, NULL, errcode); if (cframe_unwind_ff(cf)) lj_vm_unwind_ff(cframe_raw(cf)); else lj_vm_unwind_c(cframe_raw(cf), errcode); } #endif exit(EXIT_FAILURE); } /* Return string object for error message. */ LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em) { return lj_str_newz(L, err2msg(em)); } /* Out-of-memory error. */ LJ_NOINLINE void lj_err_mem(lua_State *L) { if (L->status == LUA_ERRERR+1) /* Don't touch the stack during lua_open. */ lj_vm_unwind_c(L->cframe, LUA_ERRMEM); setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM)); lj_err_throw(L, LUA_ERRMEM); } /* Find error function for runtime errors. Requires an extra stack traversal. */ static ptrdiff_t finderrfunc(lua_State *L) { cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2; void *cf = L->cframe; while (frame > bot && cf) { while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */ if (frame >= restorestack(L, -cframe_nres(cf))) break; if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */ return cframe_errfunc(cf); cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */ if (cf == NULL) return 0; } switch (frame_typep(frame)) { case FRAME_LUA: case FRAME_LUAP: frame = frame_prevl(frame); break; case FRAME_C: cf = cframe_prev(cf); /* fallthrough */ case FRAME_VARG: frame = frame_prevd(frame); break; case FRAME_CONT: if (frame_iscont_fficb(frame)) cf = cframe_prev(cf); frame = frame_prevd(frame); break; case FRAME_CP: if (cframe_canyield(cf)) return 0; if (cframe_errfunc(cf) >= 0) return cframe_errfunc(cf); frame = frame_prevd(frame); break; case FRAME_PCALL: case FRAME_PCALLH: if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall) return savestack(L, frame_prevd(frame)+1); /* xpcall's errorfunc. */ return 0; default: lua_assert(0); return 0; } } return 0; } /* Runtime error. */ LJ_NOINLINE void lj_err_run(lua_State *L) { ptrdiff_t ef = finderrfunc(L); if (ef) { TValue *errfunc = restorestack(L, ef); TValue *top = L->top; lj_trace_abort(G(L)); if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) { setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR)); lj_err_throw(L, LUA_ERRERR); } L->status = LUA_ERRERR; copyTV(L, top+LJ_FR2, top-1); copyTV(L, top-1, errfunc); if (LJ_FR2) setnilV(top++); L->top = top+1; lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */ } lj_err_throw(L, LUA_ERRRUN); } /* Formatted runtime error message. */ LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...) { const char *msg; va_list argp; va_start(argp, em); if (curr_funcisL(L)) L->top = curr_topL(L); msg = lj_strfmt_pushvf(L, err2msg(em), argp); va_end(argp); lj_debug_addloc(L, msg, L->base-1, NULL); lj_err_run(L); } /* Non-vararg variant for better calling conventions. */ LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em) { err_msgv(L, em); } /* Lexer error. */ LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok, BCLine line, ErrMsg em, va_list argp) { char buff[LUA_IDSIZE]; const char *msg; lj_debug_shortname(buff, src, line); msg = lj_strfmt_pushvf(L, err2msg(em), argp); msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg); if (tok) lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok); lj_err_throw(L, LUA_ERRSYNTAX); } /* Typecheck error for operands. */ LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm) { const char *tname = lj_typename(o); const char *opname = err2msg(opm); if (curr_funcisL(L)) { GCproto *pt = curr_proto(L); const BCIns *pc = cframe_Lpc(L) - 1; const char *oname = NULL; const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname); if (kind) err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname); } err_msgv(L, LJ_ERR_BADOPRV, opname, tname); } /* Typecheck error for ordered comparisons. */ LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2) { const char *t1 = lj_typename(o1); const char *t2 = lj_typename(o2); err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2); /* This assumes the two "boolean" entries are commoned by the C compiler. */ } /* Typecheck error for __call. */ LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o) { /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object: ** L->base still points to the caller. So add a dummy frame with L instead ** of a function. See lua_getstack(). */ const BCIns *pc = cframe_Lpc(L); if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) { const char *tname = lj_typename(o); if (LJ_FR2) o++; setframe_pc(o, pc); setframe_gc(o, obj2gco(L), LJ_TTHREAD); L->top = L->base = o+1; err_msgv(L, LJ_ERR_BADCALL, tname); } lj_err_optype(L, o, LJ_ERR_OPCALL); } /* Error in context of caller. */ LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg) { TValue *frame = L->base-1; TValue *pframe = NULL; if (frame_islua(frame)) { pframe = frame_prevl(frame); } else if (frame_iscont(frame)) { if (frame_iscont_fficb(frame)) { pframe = frame; frame = NULL; } else { pframe = frame_prevd(frame); #if LJ_HASFFI /* Remove frame for FFI metamethods. */ if (frame_func(frame)->c.ffid >= FF_ffi_meta___index && frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) { L->base = pframe+1; L->top = frame; setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame)); } #endif } } lj_debug_addloc(L, msg, pframe, frame); lj_err_run(L); } /* Formatted error in context of caller. */ LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...) { const char *msg; va_list argp; va_start(argp, em); msg = lj_strfmt_pushvf(L, err2msg(em), argp); va_end(argp); lj_err_callermsg(L, msg); } /* Error in context of caller. */ LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em) { lj_err_callermsg(L, err2msg(em)); } /* Argument error message. */ LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg, const char *msg) { const char *fname = "?"; const char *ftype = lj_debug_funcname(L, L->base - 1, &fname); if (narg < 0 && narg > LUA_REGISTRYINDEX) narg = (int)(L->top - L->base) + narg + 1; if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */ msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg); else msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg); lj_err_callermsg(L, msg); } /* Formatted argument error. */ LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...) { const char *msg; va_list argp; va_start(argp, em); msg = lj_strfmt_pushvf(L, err2msg(em), argp); va_end(argp); err_argmsg(L, narg, msg); } /* Argument error. */ LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em) { err_argmsg(L, narg, err2msg(em)); } /* Typecheck error for arguments. */ LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname) { const char *tname, *msg; if (narg <= LUA_REGISTRYINDEX) { if (narg >= LUA_GLOBALSINDEX) { tname = lj_obj_itypename[~LJ_TTAB]; } else { GCfunc *fn = curr_func(L); int idx = LUA_GLOBALSINDEX - narg; if (idx <= fn->c.nupvalues) tname = lj_typename(&fn->c.upvalue[idx-1]); else tname = lj_obj_typename[0]; } } else { TValue *o = narg < 0 ? L->top + narg : L->base + narg-1; tname = o < L->top ? lj_typename(o) : lj_obj_typename[0]; } msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname); err_argmsg(L, narg, msg); } /* Typecheck error for arguments. */ LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt) { lj_err_argtype(L, narg, lj_obj_typename[tt+1]); } /* -- Public error handling API ------------------------------------------- */ LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf) { lua_CFunction old = G(L)->panic; G(L)->panic = panicf; return old; } /* Forwarders for the public API (C calling convention and no LJ_NORET). */ LUA_API int lua_error(lua_State *L) { lj_err_run(L); return 0; /* unreachable */ } LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg) { err_argmsg(L, narg, msg); return 0; /* unreachable */ } LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname) { lj_err_argtype(L, narg, xname); return 0; /* unreachable */ } LUALIB_API void luaL_where(lua_State *L, int level) { int size; cTValue *frame = lj_debug_frame(L, level, &size); lj_debug_addloc(L, "", frame, size ? frame+size : NULL); } LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...) { const char *msg; va_list argp; va_start(argp, fmt); msg = lj_strfmt_pushvf(L, fmt, argp); va_end(argp); lj_err_callermsg(L, msg); return 0; /* unreachable */ }
xLua/build/luajit-2.1.0b2/src/lj_err.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_err.c", "repo_id": "xLua", "token_count": 10827 }
1,935
/* ** Userdata handling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_udata_c #define LUA_CORE #include "lj_obj.h" #include "lj_gc.h" #include "lj_udata.h" GCudata *lj_udata_new(lua_State *L, MSize sz, GCtab *env) { GCudata *ud = lj_mem_newt(L, sizeof(GCudata) + sz, GCudata); global_State *g = G(L); newwhite(g, ud); /* Not finalized. */ ud->gct = ~LJ_TUDATA; ud->udtype = UDTYPE_USERDATA; ud->len = sz; /* NOBARRIER: The GCudata is new (marked white). */ setgcrefnull(ud->metatable); setgcref(ud->env, obj2gco(env)); /* Chain to userdata list (after main thread). */ setgcrefr(ud->nextgc, mainthread(g)->nextgc); setgcref(mainthread(g)->nextgc, obj2gco(ud)); return ud; } void LJ_FASTCALL lj_udata_free(global_State *g, GCudata *ud) { lj_mem_free(g, ud, sizeudata(ud)); }
xLua/build/luajit-2.1.0b2/src/lj_udata.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_udata.c", "repo_id": "xLua", "token_count": 386 }
1,936
<!DOCTYPE html> <html> <head> <title>Status</title> <meta charset="utf-8"> <meta name="Copyright" content="Copyright (C) 2005-2021"> <meta name="Language" content="en"> <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> <style type="text/css"> ul li { padding-bottom: 0.3em; } </style> </head> <body> <div id="site"> <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> </div> <div id="head"> <h1>Status</h1> </div> <div id="nav"> <ul><li> <a href="luajit.html">LuaJIT</a> <ul><li> <a href="https://luajit.org/download.html">Download <span class="ext">&raquo;</span></a> </li><li> <a href="install.html">Installation</a> </li><li> <a href="running.html">Running</a> </li></ul> </li><li> <a href="extensions.html">Extensions</a> <ul><li> <a href="ext_ffi.html">FFI Library</a> <ul><li> <a href="ext_ffi_tutorial.html">FFI Tutorial</a> </li><li> <a href="ext_ffi_api.html">ffi.* API</a> </li><li> <a href="ext_ffi_semantics.html">FFI Semantics</a> </li></ul> </li><li> <a href="ext_buffer.html">String Buffers</a> </li><li> <a href="ext_jit.html">jit.* Library</a> </li><li> <a href="ext_c_api.html">Lua/C API</a> </li><li> <a href="ext_profiler.html">Profiler</a> </li></ul> </li><li> <a class="current" href="status.html">Status</a> </li><li> <a href="faq.html">FAQ</a> </li><li> <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a> </li><li> <a href="https://luajit.org/list.html">Mailing List <span class="ext">&raquo;</span></a> </li></ul> </div> <div id="main"> <p> This documentation is for LuaJIT 2.1.0-beta3. Please check the <tt>doc</tt> directory in each git branch for the version-specific documentation. </p> <p> The currently developed branches are LuaJIT&nbsp;2.1 and LuaJIT&nbsp;2.0. </p> <p> LuaJIT&nbsp;2.0 is in feature-freeze &mdash; new features will only be added to LuaJIT&nbsp;2.1. </p> <h2>Current Status</h2> <p> LuaJIT ought to run all Lua&nbsp;5.1-compatible source code just fine. It's considered a serious bug if the VM crashes or produces unexpected results &mdash; please report this. </p> <p> Known incompatibilities and issues in LuaJIT&nbsp;2.0: </p> <ul> <li> There are some differences in <b>implementation-defined</b> behavior. These either have a good reason, are arbitrary design choices or are due to quirks in the VM. The latter cases may get fixed if a demonstrable need is shown. </li> <li> The Lua <b>debug API</b> is missing a couple of features (return hooks for non-Lua functions) and shows slightly different behavior in LuaJIT (no per-coroutine hooks, no tail call counting). </li> </ul> <br class="flush"> </div> <div id="foot"> <hr class="hide"> Copyright &copy; 2005-2021 <span class="noprint"> &middot; <a href="contact.html">Contact</a> </span> </div> </body> </html>
xLua/build/luajit-2.1.0b3/doc/status.html/0
{ "file_path": "xLua/build/luajit-2.1.0b3/doc/status.html", "repo_id": "xLua", "token_count": 1134 }
1,937
/* ** LuaJIT VM builder: PE object emitter. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h ** ** Only used for building on Windows, since we cannot assume the presence ** of a suitable assembler. The host and target byte order must match. */ #include "buildvm.h" #include "lj_bc.h" #if LJ_TARGET_X86ORX64 /* Context for PE object emitter. */ static char *strtab; static size_t strtabofs; /* -- PE object definitions ----------------------------------------------- */ /* PE header. */ typedef struct PEheader { uint16_t arch; uint16_t nsects; uint32_t time; uint32_t symtabofs; uint32_t nsyms; uint16_t opthdrsz; uint16_t flags; } PEheader; /* PE section. */ typedef struct PEsection { char name[8]; uint32_t vsize; uint32_t vaddr; uint32_t size; uint32_t ofs; uint32_t relocofs; uint32_t lineofs; uint16_t nreloc; uint16_t nline; uint32_t flags; } PEsection; /* PE relocation. */ typedef struct PEreloc { uint32_t vaddr; uint32_t symidx; uint16_t type; } PEreloc; /* Cannot use sizeof, because it pads up to the max. alignment. */ #define PEOBJ_RELOC_SIZE (4+4+2) /* PE symbol table entry. */ typedef struct PEsym { union { char name[8]; uint32_t nameref[2]; } n; uint32_t value; int16_t sect; uint16_t type; uint8_t scl; uint8_t naux; } PEsym; /* PE symbol table auxiliary entry for a section. */ typedef struct PEsymaux { uint32_t size; uint16_t nreloc; uint16_t nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel; uint8_t unused[3]; } PEsymaux; /* Cannot use sizeof, because it pads up to the max. alignment. */ #define PEOBJ_SYM_SIZE (8+4+2+2+1+1) /* PE object CPU specific defines. */ #if LJ_TARGET_X86 #define PEOBJ_ARCH_TARGET 0x014c #define PEOBJ_RELOC_REL32 0x14 /* MS: REL32, GNU: DISP32. */ #define PEOBJ_RELOC_DIR32 0x06 #define PEOBJ_RELOC_OFS 0 #define PEOBJ_TEXT_FLAGS 0x60500020 /* 60=r+x, 50=align16, 20=code. */ #elif LJ_TARGET_X64 #define PEOBJ_ARCH_TARGET 0x8664 #define PEOBJ_RELOC_REL32 0x04 /* MS: REL32, GNU: DISP32. */ #define PEOBJ_RELOC_DIR32 0x02 #define PEOBJ_RELOC_ADDR32NB 0x03 #define PEOBJ_RELOC_OFS 0 #define PEOBJ_TEXT_FLAGS 0x60500020 /* 60=r+x, 50=align16, 20=code. */ #endif /* Section numbers (0-based). */ enum { PEOBJ_SECT_ABS = -2, PEOBJ_SECT_UNDEF = -1, PEOBJ_SECT_TEXT, #if LJ_TARGET_X64 PEOBJ_SECT_PDATA, PEOBJ_SECT_XDATA, #elif LJ_TARGET_X86 PEOBJ_SECT_SXDATA, #endif PEOBJ_SECT_RDATA_Z, PEOBJ_NSECTIONS }; /* Symbol types. */ #define PEOBJ_TYPE_NULL 0 #define PEOBJ_TYPE_FUNC 0x20 /* Symbol storage class. */ #define PEOBJ_SCL_EXTERN 2 #define PEOBJ_SCL_STATIC 3 /* -- PE object emitter --------------------------------------------------- */ /* Emit PE object symbol. */ static void emit_peobj_sym(BuildCtx *ctx, const char *name, uint32_t value, int sect, int type, int scl) { PEsym sym; size_t len = strlen(name); if (!strtab) { /* Pass 1: only calculate string table length. */ if (len > 8) strtabofs += len+1; return; } if (len <= 8) { memcpy(sym.n.name, name, len); memset(sym.n.name+len, 0, 8-len); } else { sym.n.nameref[0] = 0; sym.n.nameref[1] = (uint32_t)strtabofs; memcpy(strtab + strtabofs, name, len); strtab[strtabofs+len] = 0; strtabofs += len+1; } sym.value = value; sym.sect = (int16_t)(sect+1); /* 1-based section number. */ sym.type = (uint16_t)type; sym.scl = (uint8_t)scl; sym.naux = 0; owrite(ctx, &sym, PEOBJ_SYM_SIZE); } /* Emit PE object section symbol. */ static void emit_peobj_sym_sect(BuildCtx *ctx, PEsection *pesect, int sect) { PEsym sym; PEsymaux aux; if (!strtab) return; /* Pass 1: no output. */ memcpy(sym.n.name, pesect[sect].name, 8); sym.value = 0; sym.sect = (int16_t)(sect+1); /* 1-based section number. */ sym.type = PEOBJ_TYPE_NULL; sym.scl = PEOBJ_SCL_STATIC; sym.naux = 1; owrite(ctx, &sym, PEOBJ_SYM_SIZE); memset(&aux, 0, sizeof(PEsymaux)); aux.size = pesect[sect].size; aux.nreloc = pesect[sect].nreloc; owrite(ctx, &aux, PEOBJ_SYM_SIZE); } /* Emit Windows PE object file. */ void emit_peobj(BuildCtx *ctx) { PEheader pehdr; PEsection pesect[PEOBJ_NSECTIONS]; uint32_t sofs; int i, nrsym; union { uint8_t b; uint32_t u; } host_endian; sofs = sizeof(PEheader) + PEOBJ_NSECTIONS*sizeof(PEsection); /* Fill in PE sections. */ memset(&pesect, 0, PEOBJ_NSECTIONS*sizeof(PEsection)); memcpy(pesect[PEOBJ_SECT_TEXT].name, ".text", sizeof(".text")-1); pesect[PEOBJ_SECT_TEXT].ofs = sofs; sofs += (pesect[PEOBJ_SECT_TEXT].size = (uint32_t)ctx->codesz); pesect[PEOBJ_SECT_TEXT].relocofs = sofs; sofs += (pesect[PEOBJ_SECT_TEXT].nreloc = (uint16_t)ctx->nreloc) * PEOBJ_RELOC_SIZE; /* Flags: 60 = read+execute, 50 = align16, 20 = code. */ pesect[PEOBJ_SECT_TEXT].flags = PEOBJ_TEXT_FLAGS; #if LJ_TARGET_X64 memcpy(pesect[PEOBJ_SECT_PDATA].name, ".pdata", sizeof(".pdata")-1); pesect[PEOBJ_SECT_PDATA].ofs = sofs; sofs += (pesect[PEOBJ_SECT_PDATA].size = 6*4); pesect[PEOBJ_SECT_PDATA].relocofs = sofs; sofs += (pesect[PEOBJ_SECT_PDATA].nreloc = 6) * PEOBJ_RELOC_SIZE; /* Flags: 40 = read, 30 = align4, 40 = initialized data. */ pesect[PEOBJ_SECT_PDATA].flags = 0x40300040; memcpy(pesect[PEOBJ_SECT_XDATA].name, ".xdata", sizeof(".xdata")-1); pesect[PEOBJ_SECT_XDATA].ofs = sofs; sofs += (pesect[PEOBJ_SECT_XDATA].size = 8*2+4+6*2); /* See below. */ pesect[PEOBJ_SECT_XDATA].relocofs = sofs; sofs += (pesect[PEOBJ_SECT_XDATA].nreloc = 1) * PEOBJ_RELOC_SIZE; /* Flags: 40 = read, 30 = align4, 40 = initialized data. */ pesect[PEOBJ_SECT_XDATA].flags = 0x40300040; #elif LJ_TARGET_X86 memcpy(pesect[PEOBJ_SECT_SXDATA].name, ".sxdata", sizeof(".sxdata")-1); pesect[PEOBJ_SECT_SXDATA].ofs = sofs; sofs += (pesect[PEOBJ_SECT_SXDATA].size = 4); pesect[PEOBJ_SECT_SXDATA].relocofs = sofs; /* Flags: 40 = read, 30 = align4, 02 = lnk_info, 40 = initialized data. */ pesect[PEOBJ_SECT_SXDATA].flags = 0x40300240; #endif memcpy(pesect[PEOBJ_SECT_RDATA_Z].name, ".rdata$Z", sizeof(".rdata$Z")-1); pesect[PEOBJ_SECT_RDATA_Z].ofs = sofs; sofs += (pesect[PEOBJ_SECT_RDATA_Z].size = (uint32_t)strlen(ctx->dasm_ident)+1); /* Flags: 40 = read, 30 = align4, 40 = initialized data. */ pesect[PEOBJ_SECT_RDATA_Z].flags = 0x40300040; /* Fill in PE header. */ pehdr.arch = PEOBJ_ARCH_TARGET; pehdr.nsects = PEOBJ_NSECTIONS; pehdr.time = 0; /* Timestamp is optional. */ pehdr.symtabofs = sofs; pehdr.opthdrsz = 0; pehdr.flags = 0; /* Compute the size of the symbol table: ** @feat.00 + nsections*2 ** + asm_start + nsym ** + nrsym */ nrsym = ctx->nrelocsym; pehdr.nsyms = 1+PEOBJ_NSECTIONS*2 + 1+ctx->nsym + nrsym; #if LJ_TARGET_X64 pehdr.nsyms += 1; /* Symbol for lj_err_unwind_win. */ #endif /* Write PE object header and all sections. */ owrite(ctx, &pehdr, sizeof(PEheader)); owrite(ctx, &pesect, sizeof(PEsection)*PEOBJ_NSECTIONS); /* Write .text section. */ host_endian.u = 1; if (host_endian.b != LJ_ENDIAN_SELECT(1, 0)) { fprintf(stderr, "Error: different byte order for host and target\n"); exit(1); } owrite(ctx, ctx->code, ctx->codesz); for (i = 0; i < ctx->nreloc; i++) { PEreloc reloc; reloc.vaddr = (uint32_t)ctx->reloc[i].ofs + PEOBJ_RELOC_OFS; reloc.symidx = 1+2+ctx->reloc[i].sym; /* Reloc syms are after .text sym. */ reloc.type = ctx->reloc[i].type ? PEOBJ_RELOC_REL32 : PEOBJ_RELOC_DIR32; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); } #if LJ_TARGET_X64 { /* Write .pdata section. */ uint32_t fcofs = (uint32_t)ctx->sym[ctx->nsym-1].ofs; uint32_t pdata[3]; /* Start of .text, end of .text and .xdata. */ PEreloc reloc; pdata[0] = 0; pdata[1] = fcofs; pdata[2] = 0; owrite(ctx, &pdata, sizeof(pdata)); pdata[0] = fcofs; pdata[1] = (uint32_t)ctx->codesz; pdata[2] = 20; owrite(ctx, &pdata, sizeof(pdata)); reloc.vaddr = 0; reloc.symidx = 1+2+nrsym+2+2+1; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); reloc.vaddr = 4; reloc.symidx = 1+2+nrsym+2+2+1; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); reloc.vaddr = 8; reloc.symidx = 1+2+nrsym+2; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); reloc.vaddr = 12; reloc.symidx = 1+2+nrsym+2+2+1; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); reloc.vaddr = 16; reloc.symidx = 1+2+nrsym+2+2+1; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); reloc.vaddr = 20; reloc.symidx = 1+2+nrsym+2; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); } { /* Write .xdata section. */ uint16_t xdata[8+2+6]; PEreloc reloc; xdata[0] = 0x01|0x08|0x10; /* Ver. 1, uhandler/ehandler, prolog size 0. */ xdata[1] = 0x0005; /* Number of unwind codes, no frame pointer. */ xdata[2] = 0x4200; /* Stack offset 4*8+8 = aword*5. */ xdata[3] = 0x3000; /* Push rbx. */ xdata[4] = 0x6000; /* Push rsi. */ xdata[5] = 0x7000; /* Push rdi. */ xdata[6] = 0x5000; /* Push rbp. */ xdata[7] = 0; /* Alignment. */ xdata[8] = xdata[9] = 0; /* Relocated address of exception handler. */ xdata[10] = 0x01; /* Ver. 1, no handler, prolog size 0. */ xdata[11] = 0x1504; /* Number of unwind codes, fp = rbp, fpofs = 16. */ xdata[12] = 0x0300; /* set_fpreg. */ xdata[13] = 0x0200; /* stack offset 0*8+8 = aword*1. */ xdata[14] = 0x3000; /* Push rbx. */ xdata[15] = 0x5000; /* Push rbp. */ owrite(ctx, &xdata, sizeof(xdata)); reloc.vaddr = 2*8; reloc.symidx = 1+2+nrsym+2+2; reloc.type = PEOBJ_RELOC_ADDR32NB; owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); } #elif LJ_TARGET_X86 /* Write .sxdata section. */ for (i = 0; i < nrsym; i++) { if (!strcmp(ctx->relocsym[i], "_lj_err_unwind_win")) { uint32_t symidx = 1+2+i; owrite(ctx, &symidx, 4); break; } } if (i == nrsym) { fprintf(stderr, "Error: extern lj_err_unwind_win not used\n"); exit(1); } #endif /* Write .rdata$Z section. */ owrite(ctx, ctx->dasm_ident, strlen(ctx->dasm_ident)+1); /* Write symbol table. */ strtab = NULL; /* 1st pass: collect string sizes. */ for (;;) { strtabofs = 4; /* Mark as SafeSEH compliant. */ emit_peobj_sym(ctx, "@feat.00", 1, PEOBJ_SECT_ABS, PEOBJ_TYPE_NULL, PEOBJ_SCL_STATIC); emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_TEXT); for (i = 0; i < nrsym; i++) emit_peobj_sym(ctx, ctx->relocsym[i], 0, PEOBJ_SECT_UNDEF, PEOBJ_TYPE_FUNC, PEOBJ_SCL_EXTERN); #if LJ_TARGET_X64 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_PDATA); emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_XDATA); emit_peobj_sym(ctx, "lj_err_unwind_win", 0, PEOBJ_SECT_UNDEF, PEOBJ_TYPE_FUNC, PEOBJ_SCL_EXTERN); #elif LJ_TARGET_X86 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_SXDATA); #endif emit_peobj_sym(ctx, ctx->beginsym, 0, PEOBJ_SECT_TEXT, PEOBJ_TYPE_NULL, PEOBJ_SCL_EXTERN); for (i = 0; i < ctx->nsym; i++) emit_peobj_sym(ctx, ctx->sym[i].name, (uint32_t)ctx->sym[i].ofs, PEOBJ_SECT_TEXT, PEOBJ_TYPE_FUNC, PEOBJ_SCL_EXTERN); emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_RDATA_Z); if (strtab) break; /* 2nd pass: alloc strtab, write syms and copy strings. */ strtab = (char *)malloc(strtabofs); *(uint32_t *)strtab = (uint32_t)strtabofs; } /* Write string table. */ owrite(ctx, strtab, strtabofs); } #else void emit_peobj(BuildCtx *ctx) { UNUSED(ctx); fprintf(stderr, "Error: no PE object support for this target\n"); exit(1); } #endif
xLua/build/luajit-2.1.0b3/src/host/buildvm_peobj.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/host/buildvm_peobj.c", "repo_id": "xLua", "token_count": 5609 }
1,938
/* ** PPC IR assembler (SSA IR -> machine code). ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ /* -- Register allocator extensions --------------------------------------- */ /* Allocate a register with a hint. */ static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow) { Reg r = IR(ref)->r; if (ra_noreg(r)) { if (!ra_hashint(r) && !iscrossref(as, ref)) ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */ r = ra_allocref(as, ref, allow); } ra_noweak(as, r); return r; } /* Allocate two source registers for three-operand instructions. */ static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) { IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); Reg left = irl->r, right = irr->r; if (ra_hasreg(left)) { ra_noweak(as, left); if (ra_noreg(right)) right = ra_allocref(as, ir->op2, rset_exclude(allow, left)); else ra_noweak(as, right); } else if (ra_hasreg(right)) { ra_noweak(as, right); left = ra_allocref(as, ir->op1, rset_exclude(allow, right)); } else if (ra_hashint(right)) { right = ra_allocref(as, ir->op2, allow); left = ra_alloc1(as, ir->op1, rset_exclude(allow, right)); } else { left = ra_allocref(as, ir->op1, allow); right = ra_alloc1(as, ir->op2, rset_exclude(allow, left)); } return left | (right << 8); } /* -- Guard handling ------------------------------------------------------ */ /* Setup exit stubs after the end of each trace. */ static void asm_exitstub_setup(ASMState *as, ExitNo nexits) { ExitNo i; MCode *mxp = as->mctop; if (mxp - (nexits + 3 + MCLIM_REDZONE) < as->mclim) asm_mclimit(as); /* 1: mflr r0; bl ->vm_exit_handler; li r0, traceno; bl <1; bl <1; ... */ for (i = nexits-1; (int32_t)i >= 0; i--) *--mxp = PPCI_BL|(((-3-i)&0x00ffffffu)<<2); *--mxp = PPCI_LI|PPCF_T(RID_TMP)|as->T->traceno; /* Read by exit handler. */ mxp--; *mxp = PPCI_BL|((((MCode *)(void *)lj_vm_exit_handler-mxp)&0x00ffffffu)<<2); *--mxp = PPCI_MFLR|PPCF_T(RID_TMP); as->mctop = mxp; } static MCode *asm_exitstub_addr(ASMState *as, ExitNo exitno) { /* Keep this in-sync with exitstub_trace_addr(). */ return as->mctop + exitno + 3; } /* Emit conditional branch to exit for guard. */ static void asm_guardcc(ASMState *as, PPCCC cc) { MCode *target = asm_exitstub_addr(as, as->snapno); MCode *p = as->mcp; if (LJ_UNLIKELY(p == as->invmcp)) { as->loopinv = 1; *p = PPCI_B | (((target-p) & 0x00ffffffu) << 2); emit_condbranch(as, PPCI_BC, cc^4, p); return; } emit_condbranch(as, PPCI_BC, cc, target); } /* -- Operand fusion ------------------------------------------------------ */ /* Limit linear search to this distance. Avoids O(n^2) behavior. */ #define CONFLICT_SEARCH_LIM 31 /* Check if there's no conflicting instruction between curins and ref. */ static int noconflict(ASMState *as, IRRef ref, IROp conflict) { IRIns *ir = as->ir; IRRef i = as->curins; if (i > ref + CONFLICT_SEARCH_LIM) return 0; /* Give up, ref is too far away. */ while (--i > ref) if (ir[i].o == conflict) return 0; /* Conflict found. */ return 1; /* Ok, no conflict. */ } /* Fuse the array base of colocated arrays. */ static int32_t asm_fuseabase(ASMState *as, IRRef ref) { IRIns *ir = IR(ref); if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE && !neverfuse(as) && noconflict(as, ref, IR_NEWREF)) return (int32_t)sizeof(GCtab); return 0; } /* Indicates load/store indexed is ok. */ #define AHUREF_LSX ((int32_t)0x80000000) /* Fuse array/hash/upvalue reference into register+offset operand. */ static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow) { IRIns *ir = IR(ref); if (ra_noreg(ir->r)) { if (ir->o == IR_AREF) { if (mayfuse(as, ref)) { if (irref_isk(ir->op2)) { IRRef tab = IR(ir->op1)->op1; int32_t ofs = asm_fuseabase(as, tab); IRRef refa = ofs ? tab : ir->op1; ofs += 8*IR(ir->op2)->i; if (checki16(ofs)) { *ofsp = ofs; return ra_alloc1(as, refa, allow); } } if (*ofsp == AHUREF_LSX) { Reg base = ra_alloc1(as, ir->op1, allow); Reg idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); return base | (idx << 8); } } } else if (ir->o == IR_HREFK) { if (mayfuse(as, ref)) { int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); if (checki16(ofs)) { *ofsp = ofs; return ra_alloc1(as, ir->op1, allow); } } } else if (ir->o == IR_UREFC) { if (irref_isk(ir->op1)) { GCfunc *fn = ir_kfunc(IR(ir->op1)); int32_t ofs = i32ptr(&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv); int32_t jgl = (intptr_t)J2G(as->J); if ((uint32_t)(ofs-jgl) < 65536) { *ofsp = ofs-jgl-32768; return RID_JGL; } else { *ofsp = (int16_t)ofs; return ra_allock(as, ofs-(int16_t)ofs, allow); } } } else if (ir->o == IR_TMPREF) { *ofsp = (int32_t)(offsetof(global_State, tmptv)-32768); return RID_JGL; } } *ofsp = 0; return ra_alloc1(as, ref, allow); } /* Fuse XLOAD/XSTORE reference into load/store operand. */ static void asm_fusexref(ASMState *as, PPCIns pi, Reg rt, IRRef ref, RegSet allow, int32_t ofs) { IRIns *ir = IR(ref); Reg base; if (ra_noreg(ir->r) && canfuse(as, ir)) { if (ir->o == IR_ADD) { int32_t ofs2; if (irref_isk(ir->op2) && (ofs2 = ofs + IR(ir->op2)->i, checki16(ofs2))) { ofs = ofs2; ref = ir->op1; } else if (ofs == 0) { Reg right, left = ra_alloc2(as, ir, allow); right = (left >> 8); left &= 255; emit_fab(as, PPCI_LWZX | ((pi >> 20) & 0x780), rt, left, right); return; } } else if (ir->o == IR_STRREF) { lj_assertA(ofs == 0, "bad usage"); ofs = (int32_t)sizeof(GCstr); if (irref_isk(ir->op2)) { ofs += IR(ir->op2)->i; ref = ir->op1; } else if (irref_isk(ir->op1)) { ofs += IR(ir->op1)->i; ref = ir->op2; } else { /* NYI: Fuse ADD with constant. */ Reg tmp, right, left = ra_alloc2(as, ir, allow); right = (left >> 8); left &= 255; tmp = ra_scratch(as, rset_exclude(rset_exclude(allow, left), right)); emit_fai(as, pi, rt, tmp, ofs); emit_tab(as, PPCI_ADD, tmp, left, right); return; } if (!checki16(ofs)) { Reg left = ra_alloc1(as, ref, allow); Reg right = ra_allock(as, ofs, rset_exclude(allow, left)); emit_fab(as, PPCI_LWZX | ((pi >> 20) & 0x780), rt, left, right); return; } } } base = ra_alloc1(as, ref, allow); emit_fai(as, pi, rt, base, ofs); } /* Fuse XLOAD/XSTORE reference into indexed-only load/store operand. */ static void asm_fusexrefx(ASMState *as, PPCIns pi, Reg rt, IRRef ref, RegSet allow) { IRIns *ira = IR(ref); Reg right, left; if (canfuse(as, ira) && ira->o == IR_ADD && ra_noreg(ira->r)) { left = ra_alloc2(as, ira, allow); right = (left >> 8); left &= 255; } else { right = ra_alloc1(as, ref, allow); left = RID_R0; } emit_tab(as, pi, rt, left, right); } #if !LJ_SOFTFP /* Fuse to multiply-add/sub instruction. */ static int asm_fusemadd(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pir) { IRRef lref = ir->op1, rref = ir->op2; IRIns *irm; if (lref != rref && ((mayfuse(as, lref) && (irm = IR(lref), irm->o == IR_MUL) && ra_noreg(irm->r)) || (mayfuse(as, rref) && (irm = IR(rref), irm->o == IR_MUL) && (rref = lref, pi = pir, ra_noreg(irm->r))))) { Reg dest = ra_dest(as, ir, RSET_FPR); Reg add = ra_alloc1(as, rref, RSET_FPR); Reg right, left = ra_alloc2(as, irm, rset_exclude(RSET_FPR, add)); right = (left >> 8); left &= 255; emit_facb(as, pi, dest, left, right, add); return 1; } return 0; } #endif /* -- Calls --------------------------------------------------------------- */ /* Generate a call to a C function. */ static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) { uint32_t n, nargs = CCI_XNARGS(ci); int32_t ofs = 8; Reg gpr = REGARG_FIRSTGPR; #if !LJ_SOFTFP Reg fpr = REGARG_FIRSTFPR; #endif if ((void *)ci->func) emit_call(as, (void *)ci->func); for (n = 0; n < nargs; n++) { /* Setup args. */ IRRef ref = args[n]; if (ref) { IRIns *ir = IR(ref); #if !LJ_SOFTFP if (irt_isfp(ir->t)) { if (fpr <= REGARG_LASTFPR) { lj_assertA(rset_test(as->freeset, fpr), "reg %d not free", fpr); /* Already evicted. */ ra_leftov(as, fpr, ref); fpr++; } else { Reg r = ra_alloc1(as, ref, RSET_FPR); if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4; emit_spstore(as, ir, r, ofs); ofs += irt_isnum(ir->t) ? 8 : 4; } } else #endif { if (gpr <= REGARG_LASTGPR) { lj_assertA(rset_test(as->freeset, gpr), "reg %d not free", gpr); /* Already evicted. */ ra_leftov(as, gpr, ref); gpr++; } else { Reg r = ra_alloc1(as, ref, RSET_GPR); emit_spstore(as, ir, r, ofs); ofs += 4; } } } else { if (gpr <= REGARG_LASTGPR) gpr++; else ofs += 4; } checkmclim(as); } #if !LJ_SOFTFP if ((ci->flags & CCI_VARARG)) /* Vararg calls need to know about FPR use. */ emit_tab(as, fpr == REGARG_FIRSTFPR ? PPCI_CRXOR : PPCI_CREQV, 6, 6, 6); #endif } /* Setup result reg/sp for call. Evict scratch regs. */ static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) { RegSet drop = RSET_SCRATCH; int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); #if !LJ_SOFTFP if ((ci->flags & CCI_NOFPRCLOBBER)) drop &= ~RSET_FPR; #endif if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); /* Dest reg handled below. */ if (hiop && ra_hasreg((ir+1)->r)) rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ ra_evictset(as, drop); /* Evictions must be performed first. */ if (ra_used(ir)) { lj_assertA(!irt_ispri(ir->t), "PRI dest"); if (!LJ_SOFTFP && irt_isfp(ir->t)) { if ((ci->flags & CCI_CASTU64)) { /* Use spill slot or temp slots. */ int32_t ofs = ir->s ? sps_scale(ir->s) : SPOFS_TMP; Reg dest = ir->r; if (ra_hasreg(dest)) { ra_free(as, dest); ra_modified(as, dest); emit_fai(as, PPCI_LFD, dest, RID_SP, ofs); } emit_tai(as, PPCI_STW, RID_RETHI, RID_SP, ofs); emit_tai(as, PPCI_STW, RID_RETLO, RID_SP, ofs+4); } else { ra_destreg(as, ir, RID_FPRET); } } else if (hiop) { ra_destpair(as, ir); } else { ra_destreg(as, ir, RID_RET); } } } static void asm_callx(ASMState *as, IRIns *ir) { IRRef args[CCI_NARGS_MAX*2]; CCallInfo ci; IRRef func; IRIns *irf; ci.flags = asm_callx_flags(as, ir); asm_collectargs(as, ir, &ci, args); asm_setupresult(as, ir, &ci); func = ir->op2; irf = IR(func); if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } if (irref_isk(func)) { /* Call to constant address. */ ci.func = (ASMFunction)(void *)(intptr_t)(irf->i); } else { /* Need a non-argument register for indirect calls. */ RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1); Reg freg = ra_alloc1(as, func, allow); *--as->mcp = PPCI_BCTRL; *--as->mcp = PPCI_MTCTR | PPCF_T(freg); ci.func = (ASMFunction)(void *)0; } asm_gencall(as, &ci, args); } /* -- Returns ------------------------------------------------------------- */ /* Return to lower frame. Guard that it goes to the right spot. */ static void asm_retf(ASMState *as, IRIns *ir) { Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); void *pc = ir_kptr(IR(ir->op2)); int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); as->topslot -= (BCReg)delta; if ((int32_t)as->topslot < 0) as->topslot = 0; irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ emit_setgl(as, base, jit_base); emit_addptr(as, base, -8*delta); asm_guardcc(as, CC_NE); emit_ab(as, PPCI_CMPW, RID_TMP, ra_allock(as, i32ptr(pc), rset_exclude(RSET_GPR, base))); emit_tai(as, PPCI_LWZ, RID_TMP, base, -8); } /* -- Buffer operations --------------------------------------------------- */ #if LJ_HASBUFFER static void asm_bufhdr_write(ASMState *as, Reg sb) { Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); IRIns irgc; irgc.ot = IRT(0, IRT_PGC); /* GC type. */ emit_storeofs(as, &irgc, RID_TMP, sb, offsetof(SBuf, L)); emit_rot(as, PPCI_RLWIMI, RID_TMP, tmp, 0, 31-lj_fls(SBUF_MASK_FLAG), 31); emit_getgl(as, RID_TMP, cur_L); emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); } #endif /* -- Type conversions ---------------------------------------------------- */ #if !LJ_SOFTFP static void asm_tointg(ASMState *as, IRIns *ir, Reg left) { RegSet allow = RSET_FPR; Reg tmp = ra_scratch(as, rset_clear(allow, left)); Reg fbias = ra_scratch(as, rset_clear(allow, tmp)); Reg dest = ra_dest(as, ir, RSET_GPR); Reg hibias = ra_allock(as, 0x43300000, rset_exclude(RSET_GPR, dest)); asm_guardcc(as, CC_NE); emit_fab(as, PPCI_FCMPU, 0, tmp, left); emit_fab(as, PPCI_FSUB, tmp, tmp, fbias); emit_fai(as, PPCI_LFD, tmp, RID_SP, SPOFS_TMP); emit_tai(as, PPCI_STW, RID_TMP, RID_SP, SPOFS_TMPLO); emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); emit_asi(as, PPCI_XORIS, RID_TMP, dest, 0x8000); emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); emit_lsptr(as, PPCI_LFS, (fbias & 31), (void *)&as->J->k32[LJ_K32_2P52_2P31], RSET_GPR); emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); emit_fb(as, PPCI_FCTIWZ, tmp, left); } static void asm_tobit(ASMState *as, IRIns *ir) { RegSet allow = RSET_FPR; Reg dest = ra_dest(as, ir, RSET_GPR); Reg left = ra_alloc1(as, ir->op1, allow); Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left)); Reg tmp = ra_scratch(as, rset_clear(allow, right)); emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); emit_fab(as, PPCI_FADD, tmp, left, right); } #endif static void asm_conv(ASMState *as, IRIns *ir) { IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); #if !LJ_SOFTFP int stfp = (st == IRT_NUM || st == IRT_FLOAT); #endif IRRef lref = ir->op1; /* 64 bit integer conversions are handled by SPLIT. */ lj_assertA(!(irt_isint64(ir->t) || (st == IRT_I64 || st == IRT_U64)), "IR %04d has unsplit 64 bit type", (int)(ir - as->ir) - REF_BIAS); #if LJ_SOFTFP /* FP conversions are handled by SPLIT. */ lj_assertA(!irt_isfp(ir->t) && !(st == IRT_NUM || st == IRT_FLOAT), "IR %04d has FP type", (int)(ir - as->ir) - REF_BIAS); /* Can't check for same types: SPLIT uses CONV int.int + BXOR for sfp NEG. */ #else lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); if (irt_isfp(ir->t)) { Reg dest = ra_dest(as, ir, RSET_FPR); if (stfp) { /* FP to FP conversion. */ if (st == IRT_NUM) /* double -> float conversion. */ emit_fb(as, PPCI_FRSP, dest, ra_alloc1(as, lref, RSET_FPR)); else /* float -> double conversion is a no-op on PPC. */ ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ } else { /* Integer to FP conversion. */ /* IRT_INT: Flip hibit, bias with 2^52, subtract 2^52+2^31. */ /* IRT_U32: Bias with 2^52, subtract 2^52. */ RegSet allow = RSET_GPR; Reg left = ra_alloc1(as, lref, allow); Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, left)); Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); if (irt_isfloat(ir->t)) emit_fb(as, PPCI_FRSP, dest, dest); emit_fab(as, PPCI_FSUB, dest, dest, fbias); emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); emit_lsptr(as, PPCI_LFS, (fbias & 31), &as->J->k32[st == IRT_U32 ? LJ_K32_2P52 : LJ_K32_2P52_2P31], rset_clear(allow, hibias)); emit_tai(as, PPCI_STW, st == IRT_U32 ? left : RID_TMP, RID_SP, SPOFS_TMPLO); emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); if (st != IRT_U32) emit_asi(as, PPCI_XORIS, RID_TMP, left, 0x8000); } } else if (stfp) { /* FP to integer conversion. */ if (irt_isguard(ir->t)) { /* Checked conversions are only supported from number to int. */ lj_assertA(irt_isint(ir->t) && st == IRT_NUM, "bad type for checked CONV"); asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); } else { Reg dest = ra_dest(as, ir, RSET_GPR); Reg left = ra_alloc1(as, lref, RSET_FPR); Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); if (irt_isu32(ir->t)) { /* Convert both x and x-2^31 to int and merge results. */ Reg tmpi = ra_scratch(as, rset_exclude(RSET_GPR, dest)); emit_asb(as, PPCI_OR, dest, dest, tmpi); /* Select with mask idiom. */ emit_asb(as, PPCI_AND, tmpi, tmpi, RID_TMP); emit_asb(as, PPCI_ANDC, dest, dest, RID_TMP); emit_tai(as, PPCI_LWZ, tmpi, RID_SP, SPOFS_TMPLO); /* tmp = (int)(x) */ emit_tai(as, PPCI_ADDIS, dest, dest, 0x8000); /* dest += 2^31 */ emit_asb(as, PPCI_SRAWI, RID_TMP, dest, 31); /* mask = -(dest < 0) */ emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); /* dest = (int)(x-2^31) */ emit_fb(as, PPCI_FCTIWZ, tmp, left); emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); emit_fb(as, PPCI_FCTIWZ, tmp, tmp); emit_fab(as, PPCI_FSUB, tmp, left, tmp); emit_lsptr(as, PPCI_LFS, (tmp & 31), (void *)&as->J->k32[LJ_K32_2P31], RSET_GPR); } else { emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); emit_fb(as, PPCI_FCTIWZ, tmp, left); } } } else #endif { Reg dest = ra_dest(as, ir, RSET_GPR); if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ Reg left = ra_alloc1(as, ir->op1, RSET_GPR); lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); if ((ir->op2 & IRCONV_SEXT)) emit_as(as, st == IRT_I8 ? PPCI_EXTSB : PPCI_EXTSH, dest, left); else emit_rot(as, PPCI_RLWINM, dest, left, 0, st == IRT_U8 ? 24 : 16, 31); } else { /* 32/64 bit integer conversions. */ /* Only need to handle 32/32 bit no-op (cast) on 32 bit archs. */ ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ } } } static void asm_strto(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; IRRef args[2]; int32_t ofs = SPOFS_TMP; #if LJ_SOFTFP ra_evictset(as, RSET_SCRATCH); if (ra_used(ir)) { if (ra_hasspill(ir->s) && ra_hasspill((ir+1)->s) && (ir->s & 1) == LJ_BE && (ir->s ^ 1) == (ir+1)->s) { int i; for (i = 0; i < 2; i++) { Reg r = (ir+i)->r; if (ra_hasreg(r)) { ra_free(as, r); ra_modified(as, r); emit_spload(as, ir+i, r, sps_scale((ir+i)->s)); } } ofs = sps_scale(ir->s & ~1); } else { Reg rhi = ra_dest(as, ir+1, RSET_GPR); Reg rlo = ra_dest(as, ir, rset_exclude(RSET_GPR, rhi)); emit_tai(as, PPCI_LWZ, rhi, RID_SP, ofs); emit_tai(as, PPCI_LWZ, rlo, RID_SP, ofs+4); } } #else RegSet drop = RSET_SCRATCH; if (ra_hasreg(ir->r)) rset_set(drop, ir->r); /* Spill dest reg (if any). */ ra_evictset(as, drop); if (ir->s) ofs = sps_scale(ir->s); #endif asm_guardcc(as, CC_EQ); emit_ai(as, PPCI_CMPWI, RID_RET, 0); /* Test return status. */ args[0] = ir->op1; /* GCstr *str */ args[1] = ASMREF_TMP1; /* TValue *n */ asm_gencall(as, ci, args); /* Store the result to the spill slot or temp slots. */ emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_SP, ofs); } /* -- Memory references --------------------------------------------------- */ /* Get pointer to TValue. */ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) { int32_t tmpofs = (int32_t)(offsetof(global_State, tmptv)-32768); if ((mode & IRTMPREF_IN1)) { IRIns *ir = IR(ref); if (irt_isnum(ir->t)) { if ((mode & IRTMPREF_OUT1)) { #if LJ_SOFTFP lj_assertA(irref_isk(ref), "unsplit FP op"); emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); emit_setgl(as, ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, RSET_GPR), tmptv.u32.lo); emit_setgl(as, ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, RSET_GPR), tmptv.u32.hi); #else Reg src = ra_alloc1(as, ref, RSET_FPR); emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); emit_fai(as, PPCI_STFD, src, RID_JGL, tmpofs); #endif } else if (irref_isk(ref)) { /* Use the number constant itself as a TValue. */ ra_allockreg(as, i32ptr(ir_knum(ir)), dest); } else { #if LJ_SOFTFP lj_assertA(0, "unsplit FP op"); #else /* Otherwise force a spill and use the spill slot. */ emit_tai(as, PPCI_ADDI, dest, RID_SP, ra_spill(as, ir)); #endif } } else { /* Otherwise use g->tmptv to hold the TValue. */ Reg type; emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); if (!irt_ispri(ir->t)) { Reg src = ra_alloc1(as, ref, RSET_GPR); emit_setgl(as, src, tmptv.gcr); } if (LJ_SOFTFP && (ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)) type = ra_alloc1(as, ref+1, RSET_GPR); else type = ra_allock(as, irt_toitype(ir->t), RSET_GPR); emit_setgl(as, type, tmptv.it); } } else { emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); } } static void asm_aref(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); Reg idx, base; if (irref_isk(ir->op2)) { IRRef tab = IR(ir->op1)->op1; int32_t ofs = asm_fuseabase(as, tab); IRRef refa = ofs ? tab : ir->op1; ofs += 8*IR(ir->op2)->i; if (checki16(ofs)) { base = ra_alloc1(as, refa, RSET_GPR); emit_tai(as, PPCI_ADDI, dest, base, ofs); return; } } base = ra_alloc1(as, ir->op1, RSET_GPR); idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); emit_tab(as, PPCI_ADD, dest, RID_TMP, base); emit_slwi(as, RID_TMP, idx, 3); } /* Inlined hash lookup. Specialized for key type and for const keys. ** The equivalent C code is: ** Node *n = hashkey(t, key); ** do { ** if (lj_obj_equal(&n->key, key)) return &n->val; ** } while ((n = nextnode(n))); ** return niltv(L); */ static void asm_href(ASMState *as, IRIns *ir, IROp merge) { RegSet allow = RSET_GPR; int destused = ra_used(ir); Reg dest = ra_dest(as, ir, allow); Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); Reg key = RID_NONE, tmp1 = RID_TMP, tmp2; Reg tisnum = RID_NONE, tmpnum = RID_NONE; IRRef refkey = ir->op2; IRIns *irkey = IR(refkey); int isk = irref_isk(refkey); IRType1 kt = irkey->t; uint32_t khash; MCLabel l_end, l_loop, l_next; rset_clear(allow, tab); #if LJ_SOFTFP if (!isk) { key = ra_alloc1(as, refkey, allow); rset_clear(allow, key); if (irkey[1].o == IR_HIOP) { if (ra_hasreg((irkey+1)->r)) { tmpnum = (irkey+1)->r; ra_noweak(as, tmpnum); } else { tmpnum = ra_allocref(as, refkey+1, allow); } rset_clear(allow, tmpnum); } } #else if (irt_isnum(kt)) { key = ra_alloc1(as, refkey, RSET_FPR); tmpnum = ra_scratch(as, rset_exclude(RSET_FPR, key)); tisnum = ra_allock(as, (int32_t)LJ_TISNUM, allow); rset_clear(allow, tisnum); } else if (!irt_ispri(kt)) { key = ra_alloc1(as, refkey, allow); rset_clear(allow, key); } #endif tmp2 = ra_scratch(as, allow); rset_clear(allow, tmp2); /* Key not found in chain: jump to exit (if merged) or load niltv. */ l_end = emit_label(as); as->invmcp = NULL; if (merge == IR_NE) asm_guardcc(as, CC_EQ); else if (destused) emit_loada(as, dest, niltvg(J2G(as->J))); /* Follow hash chain until the end. */ l_loop = --as->mcp; emit_ai(as, PPCI_CMPWI, dest, 0); emit_tai(as, PPCI_LWZ, dest, dest, (int32_t)offsetof(Node, next)); l_next = emit_label(as); /* Type and value comparison. */ if (merge == IR_EQ) asm_guardcc(as, CC_EQ); else emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); if (!LJ_SOFTFP && irt_isnum(kt)) { emit_fab(as, PPCI_FCMPU, 0, tmpnum, key); emit_condbranch(as, PPCI_BC, CC_GE, l_next); emit_ab(as, PPCI_CMPLW, tmp1, tisnum); emit_fai(as, PPCI_LFD, tmpnum, dest, (int32_t)offsetof(Node, key.n)); } else { if (!irt_ispri(kt)) { emit_ab(as, PPCI_CMPW, tmp2, key); emit_condbranch(as, PPCI_BC, CC_NE, l_next); } if (LJ_SOFTFP && ra_hasreg(tmpnum)) emit_ab(as, PPCI_CMPW, tmp1, tmpnum); else emit_ai(as, PPCI_CMPWI, tmp1, irt_toitype(irkey->t)); if (!irt_ispri(kt)) emit_tai(as, PPCI_LWZ, tmp2, dest, (int32_t)offsetof(Node, key.gcr)); } emit_tai(as, PPCI_LWZ, tmp1, dest, (int32_t)offsetof(Node, key.it)); *l_loop = PPCI_BC | PPCF_Y | PPCF_CC(CC_NE) | (((char *)as->mcp-(char *)l_loop) & 0xffffu); /* Load main position relative to tab->node into dest. */ khash = isk ? ir_khash(as, irkey) : 1; if (khash == 0) { emit_tai(as, PPCI_LWZ, dest, tab, (int32_t)offsetof(GCtab, node)); } else { Reg tmphash = tmp1; if (isk) tmphash = ra_allock(as, khash, allow); emit_tab(as, PPCI_ADD, dest, dest, tmp1); emit_tai(as, PPCI_MULLI, tmp1, tmp1, sizeof(Node)); emit_asb(as, PPCI_AND, tmp1, tmp2, tmphash); emit_tai(as, PPCI_LWZ, dest, tab, (int32_t)offsetof(GCtab, node)); emit_tai(as, PPCI_LWZ, tmp2, tab, (int32_t)offsetof(GCtab, hmask)); if (isk) { /* Nothing to do. */ } else if (irt_isstr(kt)) { emit_tai(as, PPCI_LWZ, tmp1, key, (int32_t)offsetof(GCstr, sid)); } else { /* Must match with hash*() in lj_tab.c. */ emit_tab(as, PPCI_SUBF, tmp1, tmp2, tmp1); emit_rotlwi(as, tmp2, tmp2, HASH_ROT3); emit_asb(as, PPCI_XOR, tmp1, tmp1, tmp2); emit_rotlwi(as, tmp1, tmp1, (HASH_ROT2+HASH_ROT1)&31); emit_tab(as, PPCI_SUBF, tmp2, dest, tmp2); if (LJ_SOFTFP ? (irkey[1].o == IR_HIOP) : irt_isnum(kt)) { #if LJ_SOFTFP emit_asb(as, PPCI_XOR, tmp2, key, tmp1); emit_rotlwi(as, dest, tmp1, HASH_ROT1); emit_tab(as, PPCI_ADD, tmp1, tmpnum, tmpnum); #else int32_t ofs = ra_spill(as, irkey); emit_asb(as, PPCI_XOR, tmp2, tmp2, tmp1); emit_rotlwi(as, dest, tmp1, HASH_ROT1); emit_tab(as, PPCI_ADD, tmp1, tmp1, tmp1); emit_tai(as, PPCI_LWZ, tmp2, RID_SP, ofs+4); emit_tai(as, PPCI_LWZ, tmp1, RID_SP, ofs); #endif } else { emit_asb(as, PPCI_XOR, tmp2, key, tmp1); emit_rotlwi(as, dest, tmp1, HASH_ROT1); emit_tai(as, PPCI_ADDI, tmp1, tmp2, HASH_BIAS); emit_tai(as, PPCI_ADDIS, tmp2, key, (HASH_BIAS + 32768)>>16); } } } } static void asm_hrefk(ASMState *as, IRIns *ir) { IRIns *kslot = IR(ir->op2); IRIns *irkey = IR(kslot->op1); int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); int32_t kofs = ofs + (int32_t)offsetof(Node, key); Reg dest = (ra_used(ir)||ofs > 32736) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; Reg node = ra_alloc1(as, ir->op1, RSET_GPR); Reg key = RID_NONE, type = RID_TMP, idx = node; RegSet allow = rset_exclude(RSET_GPR, node); lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); if (ofs > 32736) { idx = dest; rset_clear(allow, dest); kofs = (int32_t)offsetof(Node, key); } else if (ra_hasreg(dest)) { emit_tai(as, PPCI_ADDI, dest, node, ofs); } asm_guardcc(as, CC_NE); if (!irt_ispri(irkey->t)) { key = ra_scratch(as, allow); rset_clear(allow, key); } rset_clear(allow, type); if (irt_isnum(irkey->t)) { emit_cmpi(as, key, (int32_t)ir_knum(irkey)->u32.lo); asm_guardcc(as, CC_NE); emit_cmpi(as, type, (int32_t)ir_knum(irkey)->u32.hi); } else { if (ra_hasreg(key)) { emit_cmpi(as, key, irkey->i); /* May use RID_TMP, i.e. type. */ asm_guardcc(as, CC_NE); } emit_ai(as, PPCI_CMPWI, type, irt_toitype(irkey->t)); } if (ra_hasreg(key)) emit_tai(as, PPCI_LWZ, key, idx, kofs+4); emit_tai(as, PPCI_LWZ, type, idx, kofs); if (ofs > 32736) { emit_tai(as, PPCI_ADDIS, dest, dest, (ofs + 32768) >> 16); emit_tai(as, PPCI_ADDI, dest, node, ofs); } } static void asm_uref(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); if (irref_isk(ir->op1)) { GCfunc *fn = ir_kfunc(IR(ir->op1)); MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; emit_lsptr(as, PPCI_LWZ, dest, v, RSET_GPR); } else { Reg uv = ra_scratch(as, RSET_GPR); Reg func = ra_alloc1(as, ir->op1, RSET_GPR); if (ir->o == IR_UREFC) { asm_guardcc(as, CC_NE); emit_ai(as, PPCI_CMPWI, RID_TMP, 1); emit_tai(as, PPCI_ADDI, dest, uv, (int32_t)offsetof(GCupval, tv)); emit_tai(as, PPCI_LBZ, RID_TMP, uv, (int32_t)offsetof(GCupval, closed)); } else { emit_tai(as, PPCI_LWZ, dest, uv, (int32_t)offsetof(GCupval, v)); } emit_tai(as, PPCI_LWZ, uv, func, (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8)); } } static void asm_fref(ASMState *as, IRIns *ir) { UNUSED(as); UNUSED(ir); lj_assertA(!ra_used(ir), "unfused FREF"); } static void asm_strref(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); IRRef ref = ir->op2, refk = ir->op1; int32_t ofs = (int32_t)sizeof(GCstr); Reg r; if (irref_isk(ref)) { IRRef tmp = refk; refk = ref; ref = tmp; } else if (!irref_isk(refk)) { Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); IRIns *irr = IR(ir->op2); if (ra_hasreg(irr->r)) { ra_noweak(as, irr->r); right = irr->r; } else if (mayfuse(as, irr->op2) && irr->o == IR_ADD && irref_isk(irr->op2) && checki16(ofs + IR(irr->op2)->i)) { ofs += IR(irr->op2)->i; right = ra_alloc1(as, irr->op1, rset_exclude(RSET_GPR, left)); } else { right = ra_allocref(as, ir->op2, rset_exclude(RSET_GPR, left)); } emit_tai(as, PPCI_ADDI, dest, dest, ofs); emit_tab(as, PPCI_ADD, dest, left, right); return; } r = ra_alloc1(as, ref, RSET_GPR); ofs += IR(refk)->i; if (checki16(ofs)) emit_tai(as, PPCI_ADDI, dest, r, ofs); else emit_tab(as, PPCI_ADD, dest, r, ra_allock(as, ofs, rset_exclude(RSET_GPR, r))); } /* -- Loads and stores ---------------------------------------------------- */ static PPCIns asm_fxloadins(ASMState *as, IRIns *ir) { UNUSED(as); switch (irt_type(ir->t)) { case IRT_I8: return PPCI_LBZ; /* Needs sign-extension. */ case IRT_U8: return PPCI_LBZ; case IRT_I16: return PPCI_LHA; case IRT_U16: return PPCI_LHZ; case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return PPCI_LFD; case IRT_FLOAT: if (!LJ_SOFTFP) return PPCI_LFS; default: return PPCI_LWZ; } } static PPCIns asm_fxstoreins(ASMState *as, IRIns *ir) { UNUSED(as); switch (irt_type(ir->t)) { case IRT_I8: case IRT_U8: return PPCI_STB; case IRT_I16: case IRT_U16: return PPCI_STH; case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return PPCI_STFD; case IRT_FLOAT: if (!LJ_SOFTFP) return PPCI_STFS; default: return PPCI_STW; } } static void asm_fload(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); PPCIns pi = asm_fxloadins(as, ir); Reg idx; int32_t ofs; if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ idx = RID_JGL; ofs = (ir->op2 << 2) - 32768 - GG_OFS(g); } else { idx = ra_alloc1(as, ir->op1, RSET_GPR); if (ir->op2 == IRFL_TAB_ARRAY) { ofs = asm_fuseabase(as, ir->op1); if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ emit_tai(as, PPCI_ADDI, dest, idx, ofs); return; } } ofs = field_ofs[ir->op2]; } lj_assertA(!irt_isi8(ir->t), "unsupported FLOAD I8"); emit_tai(as, pi, dest, idx, ofs); } static void asm_fstore(ASMState *as, IRIns *ir) { if (ir->r != RID_SINK) { Reg src = ra_alloc1(as, ir->op2, RSET_GPR); IRIns *irf = IR(ir->op1); Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src)); int32_t ofs = field_ofs[irf->op2]; PPCIns pi = asm_fxstoreins(as, ir); emit_tai(as, pi, src, idx, ofs); } } static void asm_xload(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); lj_assertA(!(ir->op2 & IRXLOAD_UNALIGNED), "unaligned XLOAD"); if (irt_isi8(ir->t)) emit_as(as, PPCI_EXTSB, dest, dest); asm_fusexref(as, asm_fxloadins(as, ir), dest, ir->op1, RSET_GPR, 0); } static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs) { IRIns *irb; if (ir->r == RID_SINK) return; if (ofs == 0 && mayfuse(as, ir->op2) && (irb = IR(ir->op2))->o == IR_BSWAP && ra_noreg(irb->r) && (irt_isint(ir->t) || irt_isu32(ir->t))) { /* Fuse BSWAP with XSTORE to stwbrx. */ Reg src = ra_alloc1(as, irb->op1, RSET_GPR); asm_fusexrefx(as, PPCI_STWBRX, src, ir->op1, rset_exclude(RSET_GPR, src)); } else { Reg src = ra_alloc1(as, ir->op2, (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); asm_fusexref(as, asm_fxstoreins(as, ir), src, ir->op1, rset_exclude(RSET_GPR, src), ofs); } } #define asm_xstore(as, ir) asm_xstore_(as, ir, 0) static void asm_ahuvload(ASMState *as, IRIns *ir) { IRType1 t = ir->t; Reg dest = RID_NONE, type = RID_TMP, tmp = RID_TMP, idx; RegSet allow = RSET_GPR; int32_t ofs = AHUREF_LSX; if (LJ_SOFTFP && (ir+1)->o == IR_HIOP) { t.irt = IRT_NUM; if (ra_used(ir+1)) { type = ra_dest(as, ir+1, allow); rset_clear(allow, type); } ofs = 0; } if (ra_used(ir)) { lj_assertA((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) || irt_isint(ir->t) || irt_isaddr(ir->t), "bad load type %d", irt_type(ir->t)); if (LJ_SOFTFP || !irt_isnum(t)) ofs = 0; dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); rset_clear(allow, dest); } idx = asm_fuseahuref(as, ir->op1, &ofs, allow); if (ir->o == IR_VLOAD) { ofs = ofs != AHUREF_LSX ? ofs + 8 * ir->op2 : ir->op2 ? 8 * ir->op2 : AHUREF_LSX; } if (irt_isnum(t)) { Reg tisnum = ra_allock(as, (int32_t)LJ_TISNUM, rset_exclude(allow, idx)); asm_guardcc(as, CC_GE); emit_ab(as, PPCI_CMPLW, type, tisnum); if (ra_hasreg(dest)) { if (!LJ_SOFTFP && ofs == AHUREF_LSX) { tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, (idx&255)), (idx>>8))); emit_fab(as, PPCI_LFDX, dest, (idx&255), tmp); } else { emit_fai(as, LJ_SOFTFP ? PPCI_LWZ : PPCI_LFD, dest, idx, ofs+4*LJ_SOFTFP); } } } else { asm_guardcc(as, CC_NE); emit_ai(as, PPCI_CMPWI, type, irt_toitype(t)); if (ra_hasreg(dest)) emit_tai(as, PPCI_LWZ, dest, idx, ofs+4); } if (ofs == AHUREF_LSX) { emit_tab(as, PPCI_LWZX, type, (idx&255), tmp); emit_slwi(as, tmp, (idx>>8), 3); } else { emit_tai(as, PPCI_LWZ, type, idx, ofs); } } static void asm_ahustore(ASMState *as, IRIns *ir) { RegSet allow = RSET_GPR; Reg idx, src = RID_NONE, type = RID_NONE; int32_t ofs = AHUREF_LSX; if (ir->r == RID_SINK) return; if (!LJ_SOFTFP && irt_isnum(ir->t)) { src = ra_alloc1(as, ir->op2, RSET_FPR); } else { if (!irt_ispri(ir->t)) { src = ra_alloc1(as, ir->op2, allow); rset_clear(allow, src); ofs = 0; } if (LJ_SOFTFP && (ir+1)->o == IR_HIOP) type = ra_alloc1(as, (ir+1)->op2, allow); else type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); rset_clear(allow, type); } idx = asm_fuseahuref(as, ir->op1, &ofs, allow); if (!LJ_SOFTFP && irt_isnum(ir->t)) { if (ofs == AHUREF_LSX) { emit_fab(as, PPCI_STFDX, src, (idx&255), RID_TMP); emit_slwi(as, RID_TMP, (idx>>8), 3); } else { emit_fai(as, PPCI_STFD, src, idx, ofs); } } else { if (ra_hasreg(src)) emit_tai(as, PPCI_STW, src, idx, ofs+4); if (ofs == AHUREF_LSX) { emit_tab(as, PPCI_STWX, type, (idx&255), RID_TMP); emit_slwi(as, RID_TMP, (idx>>8), 3); } else { emit_tai(as, PPCI_STW, type, idx, ofs); } } } static void asm_sload(ASMState *as, IRIns *ir) { int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 0 : 4); IRType1 t = ir->t; Reg dest = RID_NONE, type = RID_NONE, base; RegSet allow = RSET_GPR; int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); if (hiop) t.irt = IRT_NUM; lj_assertA(!(ir->op2 & IRSLOAD_PARENT), "bad parent SLOAD"); /* Handled by asm_head_side(). */ lj_assertA(irt_isguard(ir->t) || !(ir->op2 & IRSLOAD_TYPECHECK), "inconsistent SLOAD variant"); lj_assertA(LJ_DUALNUM || !irt_isint(t) || (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME|IRSLOAD_KEYINDEX)), "bad SLOAD type"); #if LJ_SOFTFP lj_assertA(!(ir->op2 & IRSLOAD_CONVERT), "unsplit SLOAD convert"); /* Handled by LJ_SOFTFP SPLIT. */ if (hiop && ra_used(ir+1)) { type = ra_dest(as, ir+1, allow); rset_clear(allow, type); } #else if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { dest = ra_scratch(as, RSET_FPR); asm_tointg(as, ir, dest); t.irt = IRT_NUM; /* Continue with a regular number type check. */ } else #endif if (ra_used(ir)) { lj_assertA(irt_isnum(t) || irt_isint(t) || irt_isaddr(t), "bad SLOAD type %d", irt_type(ir->t)); dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); rset_clear(allow, dest); base = ra_alloc1(as, REF_BASE, allow); rset_clear(allow, base); if (!LJ_SOFTFP && (ir->op2 & IRSLOAD_CONVERT)) { if (irt_isint(t)) { emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); dest = ra_scratch(as, RSET_FPR); emit_fai(as, PPCI_STFD, dest, RID_SP, SPOFS_TMP); emit_fb(as, PPCI_FCTIWZ, dest, dest); t.irt = IRT_NUM; /* Check for original type. */ } else { Reg tmp = ra_scratch(as, allow); Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, tmp)); Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); emit_fab(as, PPCI_FSUB, dest, dest, fbias); emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); emit_lsptr(as, PPCI_LFS, (fbias & 31), (void *)&as->J->k32[LJ_K32_2P52_2P31], rset_clear(allow, hibias)); emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPLO); emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); emit_asi(as, PPCI_XORIS, tmp, tmp, 0x8000); dest = tmp; t.irt = IRT_INT; /* Check for original type. */ } } goto dotypecheck; } base = ra_alloc1(as, REF_BASE, allow); rset_clear(allow, base); dotypecheck: if (irt_isnum(t)) { if ((ir->op2 & IRSLOAD_TYPECHECK)) { Reg tisnum = ra_allock(as, (int32_t)LJ_TISNUM, allow); asm_guardcc(as, CC_GE); #if !LJ_SOFTFP type = RID_TMP; #endif emit_ab(as, PPCI_CMPLW, type, tisnum); } if (ra_hasreg(dest)) emit_fai(as, LJ_SOFTFP ? PPCI_LWZ : PPCI_LFD, dest, base, ofs-(LJ_SOFTFP?0:4)); } else { if ((ir->op2 & IRSLOAD_TYPECHECK)) { asm_guardcc(as, CC_NE); emit_ai(as, PPCI_CMPWI, RID_TMP, irt_toitype(t)); type = RID_TMP; } if (ra_hasreg(dest)) emit_tai(as, PPCI_LWZ, dest, base, ofs); } if (ra_hasreg(type)) emit_tai(as, PPCI_LWZ, type, base, ofs-4); } /* -- Allocations --------------------------------------------------------- */ #if LJ_HASFFI static void asm_cnew(ASMState *as, IRIns *ir) { CTState *cts = ctype_ctsG(J2G(as->J)); CTypeID id = (CTypeID)IR(ir->op1)->i; CTSize sz; CTInfo info = lj_ctype_info(cts, id, &sz); const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; IRRef args[4]; RegSet drop = RSET_SCRATCH; lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), "bad CNEW/CNEWI operands"); as->gcsteps++; if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); /* Dest reg handled below. */ ra_evictset(as, drop); if (ra_used(ir)) ra_destreg(as, ir, RID_RET); /* GCcdata * */ /* Initialize immutable cdata object. */ if (ir->o == IR_CNEWI) { RegSet allow = (RSET_GPR & ~RSET_SCRATCH); int32_t ofs = sizeof(GCcdata); lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); if (sz == 8) { ofs += 4; lj_assertA((ir+1)->o == IR_HIOP, "expected HIOP for CNEWI"); } for (;;) { Reg r = ra_alloc1(as, ir->op2, allow); emit_tai(as, PPCI_STW, r, RID_RET, ofs); rset_clear(allow, r); if (ofs == sizeof(GCcdata)) break; ofs -= 4; ir++; } } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; args[0] = ASMREF_L; /* lua_State *L */ args[1] = ir->op1; /* CTypeID id */ args[2] = ir->op2; /* CTSize sz */ args[3] = ASMREF_TMP1; /* CTSize align */ asm_gencall(as, ci, args); emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); return; } /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ emit_tai(as, PPCI_STB, RID_RET+1, RID_RET, offsetof(GCcdata, gct)); emit_tai(as, PPCI_STH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid)); emit_ti(as, PPCI_LI, RID_RET+1, ~LJ_TCDATA); emit_ti(as, PPCI_LI, RID_TMP, id); /* Lower 16 bit used. Sign-ext ok. */ args[0] = ASMREF_L; /* lua_State *L */ args[1] = ASMREF_TMP1; /* MSize size */ asm_gencall(as, ci, args); ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), ra_releasetmp(as, ASMREF_TMP1)); } #endif /* -- Write barriers ------------------------------------------------------ */ static void asm_tbar(ASMState *as, IRIns *ir) { Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); Reg mark = ra_scratch(as, rset_exclude(RSET_GPR, tab)); Reg link = RID_TMP; MCLabel l_end = emit_label(as); emit_tai(as, PPCI_STW, link, tab, (int32_t)offsetof(GCtab, gclist)); emit_tai(as, PPCI_STB, mark, tab, (int32_t)offsetof(GCtab, marked)); emit_setgl(as, tab, gc.grayagain); lj_assertA(LJ_GC_BLACK == 0x04, "bad LJ_GC_BLACK"); emit_rot(as, PPCI_RLWINM, mark, mark, 0, 30, 28); /* Clear black bit. */ emit_getgl(as, link, gc.grayagain); emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); emit_asi(as, PPCI_ANDIDOT, RID_TMP, mark, LJ_GC_BLACK); emit_tai(as, PPCI_LBZ, mark, tab, (int32_t)offsetof(GCtab, marked)); } static void asm_obar(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; IRRef args[2]; MCLabel l_end; Reg obj, val, tmp; /* No need for other object barriers (yet). */ lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); ra_evictset(as, RSET_SCRATCH); l_end = emit_label(as); args[0] = ASMREF_TMP1; /* global_State *g */ args[1] = ir->op1; /* TValue *tv */ asm_gencall(as, ci, args); emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); obj = IR(ir->op1)->r; tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); emit_asi(as, PPCI_ANDIDOT, tmp, tmp, LJ_GC_BLACK); emit_condbranch(as, PPCI_BC, CC_EQ, l_end); emit_asi(as, PPCI_ANDIDOT, RID_TMP, RID_TMP, LJ_GC_WHITES); val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj)); emit_tai(as, PPCI_LBZ, tmp, obj, (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); emit_tai(as, PPCI_LBZ, RID_TMP, val, (int32_t)offsetof(GChead, marked)); } /* -- Arithmetic and logic operations ------------------------------------- */ #if !LJ_SOFTFP static void asm_fparith(ASMState *as, IRIns *ir, PPCIns pi) { Reg dest = ra_dest(as, ir, RSET_FPR); Reg right, left = ra_alloc2(as, ir, RSET_FPR); right = (left >> 8); left &= 255; if (pi == PPCI_FMUL) emit_fac(as, pi, dest, left, right); else emit_fab(as, pi, dest, left, right); } static void asm_fpunary(ASMState *as, IRIns *ir, PPCIns pi) { Reg dest = ra_dest(as, ir, RSET_FPR); Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR); emit_fb(as, pi, dest, left); } static void asm_fpmath(ASMState *as, IRIns *ir) { if (ir->op2 == IRFPM_SQRT && (as->flags & JIT_F_SQRT)) asm_fpunary(as, ir, PPCI_FSQRT); else asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2); } #endif static void asm_add(ASMState *as, IRIns *ir) { #if !LJ_SOFTFP if (irt_isnum(ir->t)) { if (!asm_fusemadd(as, ir, PPCI_FMADD, PPCI_FMADD)) asm_fparith(as, ir, PPCI_FADD); } else #endif { Reg dest = ra_dest(as, ir, RSET_GPR); Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); PPCIns pi; if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (checki16(k)) { pi = PPCI_ADDI; /* May fail due to spills/restores above, but simplifies the logic. */ if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi = PPCI_ADDICDOT; } emit_tai(as, pi, dest, left, k); return; } else if ((k & 0xffff) == 0) { emit_tai(as, PPCI_ADDIS, dest, left, (k >> 16)); return; } else if (!as->sectref) { emit_tai(as, PPCI_ADDIS, dest, dest, (k + 32768) >> 16); emit_tai(as, PPCI_ADDI, dest, left, k); return; } } pi = PPCI_ADD; /* May fail due to spills/restores above, but simplifies the logic. */ if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_tab(as, pi, dest, left, right); } } static void asm_sub(ASMState *as, IRIns *ir) { #if !LJ_SOFTFP if (irt_isnum(ir->t)) { if (!asm_fusemadd(as, ir, PPCI_FMSUB, PPCI_FNMSUB)) asm_fparith(as, ir, PPCI_FSUB); } else #endif { PPCIns pi = PPCI_SUBF; Reg dest = ra_dest(as, ir, RSET_GPR); Reg left, right; if (irref_isk(ir->op1)) { int32_t k = IR(ir->op1)->i; if (checki16(k)) { right = ra_alloc1(as, ir->op2, RSET_GPR); emit_tai(as, PPCI_SUBFIC, dest, right, k); return; } } /* May fail due to spills/restores above, but simplifies the logic. */ if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_tab(as, pi, dest, right, left); /* Subtract right _from_ left. */ } } static void asm_mul(ASMState *as, IRIns *ir) { #if !LJ_SOFTFP if (irt_isnum(ir->t)) { asm_fparith(as, ir, PPCI_FMUL); } else #endif { PPCIns pi = PPCI_MULLW; Reg dest = ra_dest(as, ir, RSET_GPR); Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (checki16(k)) { emit_tai(as, PPCI_MULLI, dest, left, k); return; } } /* May fail due to spills/restores above, but simplifies the logic. */ if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_tab(as, pi, dest, left, right); } } #define asm_fpdiv(as, ir) asm_fparith(as, ir, PPCI_FDIV) static void asm_neg(ASMState *as, IRIns *ir) { #if !LJ_SOFTFP if (irt_isnum(ir->t)) { asm_fpunary(as, ir, PPCI_FNEG); } else #endif { Reg dest, left; PPCIns pi = PPCI_NEG; if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } dest = ra_dest(as, ir, RSET_GPR); left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); emit_tab(as, pi, dest, left, 0); } } #define asm_abs(as, ir) asm_fpunary(as, ir, PPCI_FABS) static void asm_arithov(ASMState *as, IRIns *ir, PPCIns pi) { Reg dest, left, right; if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; } asm_guardcc(as, CC_SO); dest = ra_dest(as, ir, RSET_GPR); left = ra_alloc2(as, ir, RSET_GPR); right = (left >> 8); left &= 255; if (pi == PPCI_SUBFO) { Reg tmp = left; left = right; right = tmp; } emit_tab(as, pi|PPCF_DOT, dest, left, right); } #define asm_addov(as, ir) asm_arithov(as, ir, PPCI_ADDO) #define asm_subov(as, ir) asm_arithov(as, ir, PPCI_SUBFO) #define asm_mulov(as, ir) asm_arithov(as, ir, PPCI_MULLWO) #if LJ_HASFFI static void asm_add64(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); PPCIns pi = PPCI_ADDE; if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (k == 0) pi = PPCI_ADDZE; else if (k == -1) pi = PPCI_ADDME; else goto needright; right = 0; } else { needright: right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); } emit_tab(as, pi, dest, left, right); ir--; dest = ra_dest(as, ir, RSET_GPR); left = ra_alloc1(as, ir->op1, RSET_GPR); if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (checki16(k)) { emit_tai(as, PPCI_ADDIC, dest, left, k); return; } } right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_tab(as, PPCI_ADDC, dest, left, right); } static void asm_sub64(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); Reg left, right = ra_alloc1(as, ir->op2, RSET_GPR); PPCIns pi = PPCI_SUBFE; if (irref_isk(ir->op1)) { int32_t k = IR(ir->op1)->i; if (k == 0) pi = PPCI_SUBFZE; else if (k == -1) pi = PPCI_SUBFME; else goto needleft; left = 0; } else { needleft: left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, right)); } emit_tab(as, pi, dest, right, left); /* Subtract right _from_ left. */ ir--; dest = ra_dest(as, ir, RSET_GPR); right = ra_alloc1(as, ir->op2, RSET_GPR); if (irref_isk(ir->op1)) { int32_t k = IR(ir->op1)->i; if (checki16(k)) { emit_tai(as, PPCI_SUBFIC, dest, right, k); return; } } left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, right)); emit_tab(as, PPCI_SUBFC, dest, right, left); } static void asm_neg64(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); Reg left = ra_alloc1(as, ir->op1, RSET_GPR); emit_tab(as, PPCI_SUBFZE, dest, left, 0); ir--; dest = ra_dest(as, ir, RSET_GPR); left = ra_alloc1(as, ir->op1, RSET_GPR); emit_tai(as, PPCI_SUBFIC, dest, left, 0); } #endif static void asm_bnot(ASMState *as, IRIns *ir) { Reg dest, left, right; PPCIns pi = PPCI_NOR; if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } dest = ra_dest(as, ir, RSET_GPR); if (mayfuse(as, ir->op1)) { IRIns *irl = IR(ir->op1); if (irl->o == IR_BAND) pi ^= (PPCI_NOR ^ PPCI_NAND); else if (irl->o == IR_BXOR) pi ^= (PPCI_NOR ^ PPCI_EQV); else if (irl->o != IR_BOR) goto nofuse; left = ra_hintalloc(as, irl->op1, dest, RSET_GPR); right = ra_alloc1(as, irl->op2, rset_exclude(RSET_GPR, left)); } else { nofuse: left = right = ra_hintalloc(as, ir->op1, dest, RSET_GPR); } emit_asb(as, pi, dest, left, right); } static void asm_bswap(ASMState *as, IRIns *ir) { Reg dest = ra_dest(as, ir, RSET_GPR); IRIns *irx; if (mayfuse(as, ir->op1) && (irx = IR(ir->op1))->o == IR_XLOAD && ra_noreg(irx->r) && (irt_isint(irx->t) || irt_isu32(irx->t))) { /* Fuse BSWAP with XLOAD to lwbrx. */ asm_fusexrefx(as, PPCI_LWBRX, dest, irx->op1, RSET_GPR); } else { Reg left = ra_alloc1(as, ir->op1, RSET_GPR); Reg tmp = dest; if (tmp == left) { tmp = RID_TMP; emit_mr(as, dest, RID_TMP); } emit_rot(as, PPCI_RLWIMI, tmp, left, 24, 16, 23); emit_rot(as, PPCI_RLWIMI, tmp, left, 24, 0, 7); emit_rotlwi(as, tmp, left, 8); } } /* Fuse BAND with contiguous bitmask and a shift to rlwinm. */ static void asm_fuseandsh(ASMState *as, PPCIns pi, int32_t mask, IRRef ref) { IRIns *ir; Reg left; if (mayfuse(as, ref) && (ir = IR(ref), ra_noreg(ir->r)) && irref_isk(ir->op2) && ir->o >= IR_BSHL && ir->o <= IR_BROR) { int32_t sh = (IR(ir->op2)->i & 31); switch (ir->o) { case IR_BSHL: if ((mask & ((1u<<sh)-1))) goto nofuse; break; case IR_BSHR: if ((mask & ~((~0u)>>sh))) goto nofuse; sh = ((32-sh)&31); break; case IR_BROL: break; default: goto nofuse; } left = ra_alloc1(as, ir->op1, RSET_GPR); *--as->mcp = pi | PPCF_T(left) | PPCF_B(sh); return; } nofuse: left = ra_alloc1(as, ref, RSET_GPR); *--as->mcp = pi | PPCF_T(left); } static void asm_band(ASMState *as, IRIns *ir) { Reg dest, left, right; IRRef lref = ir->op1; PPCIns dot = 0; IRRef op2; if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; dot = PPCF_DOT; } dest = ra_dest(as, ir, RSET_GPR); if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (k) { /* First check for a contiguous bitmask as used by rlwinm. */ uint32_t s1 = lj_ffs((uint32_t)k); uint32_t k1 = ((uint32_t)k >> s1); if ((k1 & (k1+1)) == 0) { asm_fuseandsh(as, PPCI_RLWINM|dot | PPCF_A(dest) | PPCF_MB(31-lj_fls((uint32_t)k)) | PPCF_ME(31-s1), k, lref); return; } if (~(uint32_t)k) { uint32_t s2 = lj_ffs(~(uint32_t)k); uint32_t k2 = (~(uint32_t)k >> s2); if ((k2 & (k2+1)) == 0) { asm_fuseandsh(as, PPCI_RLWINM|dot | PPCF_A(dest) | PPCF_MB(32-s2) | PPCF_ME(30-lj_fls(~(uint32_t)k)), k, lref); return; } } } if (checku16(k)) { left = ra_alloc1(as, lref, RSET_GPR); emit_asi(as, PPCI_ANDIDOT, dest, left, k); return; } else if ((k & 0xffff) == 0) { left = ra_alloc1(as, lref, RSET_GPR); emit_asi(as, PPCI_ANDISDOT, dest, left, (k >> 16)); return; } } op2 = ir->op2; if (mayfuse(as, op2) && IR(op2)->o == IR_BNOT && ra_noreg(IR(op2)->r)) { dot ^= (PPCI_AND ^ PPCI_ANDC); op2 = IR(op2)->op1; } left = ra_hintalloc(as, lref, dest, RSET_GPR); right = ra_alloc1(as, op2, rset_exclude(RSET_GPR, left)); emit_asb(as, PPCI_AND ^ dot, dest, left, right); } static void asm_bitop(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik) { Reg dest = ra_dest(as, ir, RSET_GPR); Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); if (irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; Reg tmp = left; if ((checku16(k) || (k & 0xffff) == 0) || (tmp = dest, !as->sectref)) { if (!checku16(k)) { emit_asi(as, pik ^ (PPCI_ORI ^ PPCI_ORIS), dest, tmp, (k >> 16)); if ((k & 0xffff) == 0) return; } emit_asi(as, pik, dest, left, k); return; } } /* May fail due to spills/restores above, but simplifies the logic. */ if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; pi |= PPCF_DOT; } right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_asb(as, pi, dest, left, right); } #define asm_bor(as, ir) asm_bitop(as, ir, PPCI_OR, PPCI_ORI) #define asm_bxor(as, ir) asm_bitop(as, ir, PPCI_XOR, PPCI_XORI) static void asm_bitshift(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik) { Reg dest, left; Reg dot = 0; if (as->flagmcp == as->mcp) { as->flagmcp = NULL; as->mcp++; dot = PPCF_DOT; } dest = ra_dest(as, ir, RSET_GPR); left = ra_alloc1(as, ir->op1, RSET_GPR); if (irref_isk(ir->op2)) { /* Constant shifts. */ int32_t shift = (IR(ir->op2)->i & 31); if (pik == 0) /* SLWI */ emit_rot(as, PPCI_RLWINM|dot, dest, left, shift, 0, 31-shift); else if (pik == 1) /* SRWI */ emit_rot(as, PPCI_RLWINM|dot, dest, left, (32-shift)&31, shift, 31); else emit_asb(as, pik|dot, dest, left, shift); } else { Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); emit_asb(as, pi|dot, dest, left, right); } } #define asm_bshl(as, ir) asm_bitshift(as, ir, PPCI_SLW, 0) #define asm_bshr(as, ir) asm_bitshift(as, ir, PPCI_SRW, 1) #define asm_bsar(as, ir) asm_bitshift(as, ir, PPCI_SRAW, PPCI_SRAWI) #define asm_brol(as, ir) \ asm_bitshift(as, ir, PPCI_RLWNM|PPCF_MB(0)|PPCF_ME(31), \ PPCI_RLWINM|PPCF_MB(0)|PPCF_ME(31)) #define asm_bror(as, ir) lj_assertA(0, "unexpected BROR") #if LJ_SOFTFP static void asm_sfpmin_max(ASMState *as, IRIns *ir) { CCallInfo ci = lj_ir_callinfo[IRCALL_softfp_cmp]; IRRef args[4]; MCLabel l_right, l_end; Reg desthi = ra_dest(as, ir, RSET_GPR), destlo = ra_dest(as, ir+1, RSET_GPR); Reg righthi, lefthi = ra_alloc2(as, ir, RSET_GPR); Reg rightlo, leftlo = ra_alloc2(as, ir+1, RSET_GPR); PPCCC cond = (IROp)ir->o == IR_MIN ? CC_EQ : CC_NE; righthi = (lefthi >> 8); lefthi &= 255; rightlo = (leftlo >> 8); leftlo &= 255; args[0^LJ_BE] = ir->op1; args[1^LJ_BE] = (ir+1)->op1; args[2^LJ_BE] = ir->op2; args[3^LJ_BE] = (ir+1)->op2; l_end = emit_label(as); if (desthi != righthi) emit_mr(as, desthi, righthi); if (destlo != rightlo) emit_mr(as, destlo, rightlo); l_right = emit_label(as); if (l_end != l_right) emit_jmp(as, l_end); if (desthi != lefthi) emit_mr(as, desthi, lefthi); if (destlo != leftlo) emit_mr(as, destlo, leftlo); if (l_right == as->mcp+1) { cond ^= 4; l_right = l_end; ++as->mcp; } emit_condbranch(as, PPCI_BC, cond, l_right); ra_evictset(as, RSET_SCRATCH); emit_cmpi(as, RID_RET, 1); asm_gencall(as, &ci, args); } #endif static void asm_min_max(ASMState *as, IRIns *ir, int ismax) { if (!LJ_SOFTFP && irt_isnum(ir->t)) { Reg dest = ra_dest(as, ir, RSET_FPR); Reg tmp = dest; Reg right, left = ra_alloc2(as, ir, RSET_FPR); right = (left >> 8); left &= 255; if (tmp == left || tmp == right) tmp = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_FPR, dest), left), right)); emit_facb(as, PPCI_FSEL, dest, tmp, left, right); emit_fab(as, PPCI_FSUB, tmp, ismax ? left : right, ismax ? right : left); } else { Reg dest = ra_dest(as, ir, RSET_GPR); Reg tmp1 = RID_TMP, tmp2 = dest; Reg right, left = ra_alloc2(as, ir, RSET_GPR); right = (left >> 8); left &= 255; if (tmp2 == left || tmp2 == right) tmp2 = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_GPR, dest), left), right)); emit_tab(as, PPCI_ADD, dest, tmp2, right); emit_asb(as, ismax ? PPCI_ANDC : PPCI_AND, tmp2, tmp2, tmp1); emit_tab(as, PPCI_SUBFE, tmp1, tmp1, tmp1); emit_tab(as, PPCI_SUBFC, tmp2, tmp2, tmp1); emit_asi(as, PPCI_XORIS, tmp2, right, 0x8000); emit_asi(as, PPCI_XORIS, tmp1, left, 0x8000); } } #define asm_min(as, ir) asm_min_max(as, ir, 0) #define asm_max(as, ir) asm_min_max(as, ir, 1) /* -- Comparisons --------------------------------------------------------- */ #define CC_UNSIGNED 0x08 /* Unsigned integer comparison. */ #define CC_TWO 0x80 /* Check two flags for FP comparison. */ /* Map of comparisons to flags. ORDER IR. */ static const uint8_t asm_compmap[IR_ABC+1] = { /* op int cc FP cc */ /* LT */ CC_GE + (CC_GE<<4), /* GE */ CC_LT + (CC_LE<<4) + CC_TWO, /* LE */ CC_GT + (CC_GE<<4) + CC_TWO, /* GT */ CC_LE + (CC_LE<<4), /* ULT */ CC_GE + CC_UNSIGNED + (CC_GT<<4) + CC_TWO, /* UGE */ CC_LT + CC_UNSIGNED + (CC_LT<<4), /* ULE */ CC_GT + CC_UNSIGNED + (CC_GT<<4), /* UGT */ CC_LE + CC_UNSIGNED + (CC_LT<<4) + CC_TWO, /* EQ */ CC_NE + (CC_NE<<4), /* NE */ CC_EQ + (CC_EQ<<4), /* ABC */ CC_LE + CC_UNSIGNED + (CC_LT<<4) + CC_TWO /* Same as UGT. */ }; static void asm_intcomp_(ASMState *as, IRRef lref, IRRef rref, Reg cr, PPCCC cc) { Reg right, left = ra_alloc1(as, lref, RSET_GPR); if (irref_isk(rref)) { int32_t k = IR(rref)->i; if ((cc & CC_UNSIGNED) == 0) { /* Signed comparison with constant. */ if (checki16(k)) { emit_tai(as, PPCI_CMPWI, cr, left, k); /* Signed comparison with zero and referencing previous ins? */ if (k == 0 && lref == as->curins-1) as->flagmcp = as->mcp; /* Allow elimination of the compare. */ return; } else if ((cc & 3) == (CC_EQ & 3)) { /* Use CMPLWI for EQ or NE. */ if (checku16(k)) { emit_tai(as, PPCI_CMPLWI, cr, left, k); return; } else if (!as->sectref && ra_noreg(IR(rref)->r)) { emit_tai(as, PPCI_CMPLWI, cr, RID_TMP, k); emit_asi(as, PPCI_XORIS, RID_TMP, left, (k >> 16)); return; } } } else { /* Unsigned comparison with constant. */ if (checku16(k)) { emit_tai(as, PPCI_CMPLWI, cr, left, k); return; } } } right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, left)); emit_tab(as, (cc & CC_UNSIGNED) ? PPCI_CMPLW : PPCI_CMPW, cr, left, right); } static void asm_comp(ASMState *as, IRIns *ir) { PPCCC cc = asm_compmap[ir->o]; if (!LJ_SOFTFP && irt_isnum(ir->t)) { Reg right, left = ra_alloc2(as, ir, RSET_FPR); right = (left >> 8); left &= 255; asm_guardcc(as, (cc >> 4)); if ((cc & CC_TWO)) emit_tab(as, PPCI_CROR, ((cc>>4)&3), ((cc>>4)&3), (CC_EQ&3)); emit_fab(as, PPCI_FCMPU, 0, left, right); } else { IRRef lref = ir->op1, rref = ir->op2; if (irref_isk(lref) && !irref_isk(rref)) { /* Swap constants to the right (only for ABC). */ IRRef tmp = lref; lref = rref; rref = tmp; if ((cc & 2) == 0) cc ^= 1; /* LT <-> GT, LE <-> GE */ } asm_guardcc(as, cc); asm_intcomp_(as, lref, rref, 0, cc); } } #define asm_equal(as, ir) asm_comp(as, ir) #if LJ_SOFTFP /* SFP comparisons. */ static void asm_sfpcomp(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp]; RegSet drop = RSET_SCRATCH; Reg r; IRRef args[4]; args[0^LJ_BE] = ir->op1; args[1^LJ_BE] = (ir+1)->op1; args[2^LJ_BE] = ir->op2; args[3^LJ_BE] = (ir+1)->op2; for (r = REGARG_FIRSTGPR; r <= REGARG_FIRSTGPR+3; r++) { if (!rset_test(as->freeset, r) && regcost_ref(as->cost[r]) == args[r-REGARG_FIRSTGPR]) rset_clear(drop, r); } ra_evictset(as, drop); asm_setupresult(as, ir, ci); switch ((IROp)ir->o) { case IR_ULT: asm_guardcc(as, CC_EQ); emit_ai(as, PPCI_CMPWI, RID_RET, 0); case IR_ULE: asm_guardcc(as, CC_EQ); emit_ai(as, PPCI_CMPWI, RID_RET, 1); break; case IR_GE: case IR_GT: asm_guardcc(as, CC_EQ); emit_ai(as, PPCI_CMPWI, RID_RET, 2); default: asm_guardcc(as, (asm_compmap[ir->o] & 0xf)); emit_ai(as, PPCI_CMPWI, RID_RET, 0); break; } asm_gencall(as, ci, args); } #endif #if LJ_HASFFI /* 64 bit integer comparisons. */ static void asm_comp64(ASMState *as, IRIns *ir) { PPCCC cc = asm_compmap[(ir-1)->o]; if ((cc&3) == (CC_EQ&3)) { asm_guardcc(as, cc); emit_tab(as, (cc&4) ? PPCI_CRAND : PPCI_CROR, (CC_EQ&3), (CC_EQ&3), 4+(CC_EQ&3)); } else { asm_guardcc(as, CC_EQ); emit_tab(as, PPCI_CROR, (CC_EQ&3), (CC_EQ&3), ((cc^~(cc>>2))&1)); emit_tab(as, (cc&4) ? PPCI_CRAND : PPCI_CRANDC, (CC_EQ&3), (CC_EQ&3), 4+(cc&3)); } /* Loword comparison sets cr1 and is unsigned, except for equality. */ asm_intcomp_(as, (ir-1)->op1, (ir-1)->op2, 4, cc | ((cc&3) == (CC_EQ&3) ? 0 : CC_UNSIGNED)); /* Hiword comparison sets cr0. */ asm_intcomp_(as, ir->op1, ir->op2, 0, cc); as->flagmcp = NULL; /* Doesn't work here. */ } #endif /* -- Split register ops -------------------------------------------------- */ /* Hiword op of a split 32/32 bit op. Previous op is be the loword op. */ static void asm_hiop(ASMState *as, IRIns *ir) { /* HIOP is marked as a store because it needs its own DCE logic. */ int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; #if LJ_HASFFI || LJ_SOFTFP if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ as->curins--; /* Always skip the CONV. */ #if LJ_HASFFI && !LJ_SOFTFP if (usehi || uselo) asm_conv64(as, ir); return; #endif } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ as->curins--; /* Always skip the loword comparison. */ #if LJ_SOFTFP if (!irt_isint(ir->t)) { asm_sfpcomp(as, ir-1); return; } #endif #if LJ_HASFFI asm_comp64(as, ir); #endif return; #if LJ_SOFTFP } else if ((ir-1)->o == IR_MIN || (ir-1)->o == IR_MAX) { as->curins--; /* Always skip the loword min/max. */ if (uselo || usehi) asm_sfpmin_max(as, ir-1); return; #endif } else if ((ir-1)->o == IR_XSTORE) { as->curins--; /* Handle both stores here. */ if ((ir-1)->r != RID_SINK) { asm_xstore_(as, ir, 0); asm_xstore_(as, ir-1, 4); } return; } #endif if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ switch ((ir-1)->o) { #if LJ_HASFFI case IR_ADD: as->curins--; asm_add64(as, ir); break; case IR_SUB: as->curins--; asm_sub64(as, ir); break; case IR_NEG: as->curins--; asm_neg64(as, ir); break; case IR_CNEWI: /* Nothing to do here. Handled by lo op itself. */ break; #endif #if LJ_SOFTFP case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: case IR_STRTO: if (!uselo) ra_allocref(as, ir->op1, RSET_GPR); /* Mark lo op as used. */ break; case IR_ASTORE: case IR_HSTORE: case IR_USTORE: case IR_TOSTR: case IR_TMPREF: /* Nothing to do here. Handled by lo op itself. */ break; #endif case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS: if (!uselo) ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ break; default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; } } /* -- Profiling ----------------------------------------------------------- */ static void asm_prof(ASMState *as, IRIns *ir) { UNUSED(ir); asm_guardcc(as, CC_NE); emit_asi(as, PPCI_ANDIDOT, RID_TMP, RID_TMP, HOOK_PROFILE); emit_lsglptr(as, PPCI_LBZ, RID_TMP, (int32_t)offsetof(global_State, hookmask)); } /* -- Stack handling ------------------------------------------------------ */ /* Check Lua stack size for overflow. Use exit handler as fallback. */ static void asm_stack_check(ASMState *as, BCReg topslot, IRIns *irp, RegSet allow, ExitNo exitno) { /* Try to get an unused temp. register, otherwise spill/restore RID_RET*. */ Reg tmp, pbase = irp ? (ra_hasreg(irp->r) ? irp->r : RID_TMP) : RID_BASE; rset_clear(allow, pbase); tmp = allow ? rset_pickbot(allow) : (pbase == RID_RETHI ? RID_RETLO : RID_RETHI); emit_condbranch(as, PPCI_BC, CC_LT, asm_exitstub_addr(as, exitno)); if (allow == RSET_EMPTY) /* Restore temp. register. */ emit_tai(as, PPCI_LWZ, tmp, RID_SP, SPOFS_TMPW); else ra_modified(as, tmp); emit_ai(as, PPCI_CMPLWI, RID_TMP, (int32_t)(8*topslot)); emit_tab(as, PPCI_SUBF, RID_TMP, pbase, tmp); emit_tai(as, PPCI_LWZ, tmp, tmp, offsetof(lua_State, maxstack)); if (pbase == RID_TMP) emit_getgl(as, RID_TMP, jit_base); emit_getgl(as, tmp, cur_L); if (allow == RSET_EMPTY) /* Spill temp. register. */ emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPW); } /* Restore Lua stack from on-trace state. */ static void asm_stack_restore(ASMState *as, SnapShot *snap) { SnapEntry *map = &as->T->snapmap[snap->mapofs]; SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1]; MSize n, nent = snap->nent; /* Store the value of all modified slots to the Lua stack. */ for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; BCReg s = snap_slot(sn); int32_t ofs = 8*((int32_t)s-1); IRRef ref = snap_ref(sn); IRIns *ir = IR(ref); if ((sn & SNAP_NORESTORE)) continue; if (irt_isnum(ir->t)) { #if LJ_SOFTFP Reg tmp; RegSet allow = rset_exclude(RSET_GPR, RID_BASE); /* LJ_SOFTFP: must be a number constant. */ lj_assertA(irref_isk(ref), "unsplit FP op"); tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, allow); emit_tai(as, PPCI_STW, tmp, RID_BASE, ofs+(LJ_BE?4:0)); if (rset_test(as->freeset, tmp+1)) allow = RID2RSET(tmp+1); tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, allow); emit_tai(as, PPCI_STW, tmp, RID_BASE, ofs+(LJ_BE?0:4)); #else Reg src = ra_alloc1(as, ref, RSET_FPR); emit_fai(as, PPCI_STFD, src, RID_BASE, ofs); #endif } else { Reg type; RegSet allow = rset_exclude(RSET_GPR, RID_BASE); lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), "restore of IR type %d", irt_type(ir->t)); if (!irt_ispri(ir->t)) { Reg src = ra_alloc1(as, ref, allow); rset_clear(allow, src); emit_tai(as, PPCI_STW, src, RID_BASE, ofs+4); } if ((sn & (SNAP_CONT|SNAP_FRAME))) { if (s == 0) continue; /* Do not overwrite link to previous frame. */ type = ra_allock(as, (int32_t)(*flinks--), allow); #if LJ_SOFTFP } else if ((sn & SNAP_SOFTFPNUM)) { type = ra_alloc1(as, ref+1, rset_exclude(RSET_GPR, RID_BASE)); #endif } else if ((sn & SNAP_KEYINDEX)) { type = ra_allock(as, (int32_t)LJ_KEYINDEX, allow); } else { type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); } emit_tai(as, PPCI_STW, type, RID_BASE, ofs); } checkmclim(as); } lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); } /* -- GC handling --------------------------------------------------------- */ /* Marker to prevent patching the GC check exit. */ #define PPC_NOPATCH_GC_CHECK PPCI_ORIS /* Check GC threshold and do one or more GC steps. */ static void asm_gc_check(ASMState *as) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; IRRef args[2]; MCLabel l_end; Reg tmp; ra_evictset(as, RSET_SCRATCH); l_end = emit_label(as); /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */ *--as->mcp = PPC_NOPATCH_GC_CHECK; emit_ai(as, PPCI_CMPWI, RID_RET, 0); args[0] = ASMREF_TMP1; /* global_State *g */ args[1] = ASMREF_TMP2; /* MSize steps */ asm_gencall(as, ci, args); emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); tmp = ra_releasetmp(as, ASMREF_TMP2); emit_loadi(as, tmp, as->gcsteps); /* Jump around GC step if GC total < GC threshold. */ emit_condbranch(as, PPCI_BC|PPCF_Y, CC_LT, l_end); emit_ab(as, PPCI_CMPLW, RID_TMP, tmp); emit_getgl(as, tmp, gc.threshold); emit_getgl(as, RID_TMP, gc.total); as->gcsteps = 0; checkmclim(as); } /* -- Loop handling ------------------------------------------------------- */ /* Fixup the loop branch. */ static void asm_loop_fixup(ASMState *as) { MCode *p = as->mctop; MCode *target = as->mcp; if (as->loopinv) { /* Inverted loop branch? */ /* asm_guardcc already inverted the cond branch and patched the final b. */ p[-2] = (p[-2] & (0xffff0000u & ~PPCF_Y)) | (((target-p+2) & 0x3fffu) << 2); } else { p[-1] = PPCI_B|(((target-p+1)&0x00ffffffu)<<2); } } /* Fixup the tail of the loop. */ static void asm_loop_tail_fixup(ASMState *as) { UNUSED(as); /* Nothing to do. */ } /* -- Head of trace ------------------------------------------------------- */ /* Coalesce BASE register for a root trace. */ static void asm_head_root_base(ASMState *as) { IRIns *ir = IR(REF_BASE); Reg r = ir->r; if (ra_hasreg(r)) { ra_free(as, r); if (rset_test(as->modset, r) || irt_ismarked(ir->t)) ir->r = RID_INIT; /* No inheritance for modified BASE register. */ if (r != RID_BASE) emit_mr(as, r, RID_BASE); } } /* Coalesce BASE register for a side trace. */ static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow) { IRIns *ir = IR(REF_BASE); Reg r = ir->r; if (ra_hasreg(r)) { ra_free(as, r); if (rset_test(as->modset, r) || irt_ismarked(ir->t)) ir->r = RID_INIT; /* No inheritance for modified BASE register. */ if (irp->r == r) { rset_clear(allow, r); /* Mark same BASE register as coalesced. */ } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { rset_clear(allow, irp->r); emit_mr(as, r, irp->r); /* Move from coalesced parent reg. */ } else { emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ } } return allow; } /* -- Tail of trace ------------------------------------------------------- */ /* Fixup the tail code. */ static void asm_tail_fixup(ASMState *as, TraceNo lnk) { MCode *p = as->mctop; MCode *target; int32_t spadj = as->T->spadjust; if (spadj == 0) { *--p = PPCI_NOP; *--p = PPCI_NOP; as->mctop = p; } else { /* Patch stack adjustment. */ lj_assertA(checki16(CFRAME_SIZE+spadj), "stack adjustment out of range"); p[-3] = PPCI_ADDI | PPCF_T(RID_TMP) | PPCF_A(RID_SP) | (CFRAME_SIZE+spadj); p[-2] = PPCI_STWU | PPCF_T(RID_TMP) | PPCF_A(RID_SP) | spadj; } /* Patch exit branch. */ target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)lj_vm_exit_interp; p[-1] = PPCI_B|(((target-p+1)&0x00ffffffu)<<2); } /* Prepare tail of code. */ static void asm_tail_prep(ASMState *as) { MCode *p = as->mctop - 1; /* Leave room for exit branch. */ if (as->loopref) { as->invmcp = as->mcp = p; } else { as->mcp = p-2; /* Leave room for stack pointer adjustment. */ as->invmcp = NULL; } } /* -- Trace setup --------------------------------------------------------- */ /* Ensure there are enough stack slots for call arguments. */ static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) { IRRef args[CCI_NARGS_MAX*2]; uint32_t i, nargs = CCI_XNARGS(ci); int nslots = 2, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; asm_collectargs(as, ir, ci, args); for (i = 0; i < nargs; i++) if (!LJ_SOFTFP && args[i] && irt_isfp(IR(args[i])->t)) { if (nfpr > 0) nfpr--; else nslots = (nslots+3) & ~1; } else { if (ngpr > 0) ngpr--; else nslots++; } if (nslots > as->evenspill) /* Leave room for args in stack slots. */ as->evenspill = nslots; return (!LJ_SOFTFP && irt_isfp(ir->t)) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET); } static void asm_setup_target(ASMState *as) { asm_exitstub_setup(as, as->T->nsnap + (as->parent ? 1 : 0)); } /* -- Trace patching ------------------------------------------------------ */ /* Patch exit jumps of existing machine code to a new target. */ void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) { MCode *p = T->mcode; MCode *pe = (MCode *)((char *)p + T->szmcode); MCode *px = exitstub_trace_addr(T, exitno); MCode *cstart = NULL; MCode *mcarea = lj_mcode_patch(J, p, 0); int clearso = 0, patchlong = 1; for (; p < pe; p++) { /* Look for exitstub branch, try to replace with branch to target. */ uint32_t ins = *p; if ((ins & 0xfc000000u) == 0x40000000u && ((ins ^ ((char *)px-(char *)p)) & 0xffffu) == 0) { ptrdiff_t delta = (char *)target - (char *)p; if (((ins >> 16) & 3) == (CC_SO&3)) { clearso = sizeof(MCode); delta -= sizeof(MCode); } /* Many, but not all short-range branches can be patched directly. */ if (p[-1] == PPC_NOPATCH_GC_CHECK) { patchlong = 0; } else if (((delta + 0x8000) >> 16) == 0) { *p = (ins & 0xffdf0000u) | ((uint32_t)delta & 0xffffu) | ((delta & 0x8000) * (PPCF_Y/0x8000)); if (!cstart) cstart = p; } } else if ((ins & 0xfc000000u) == PPCI_B && ((ins ^ ((char *)px-(char *)p)) & 0x03ffffffu) == 0) { ptrdiff_t delta = (char *)target - (char *)p; lj_assertJ(((delta + 0x02000000) >> 26) == 0, "branch target out of range"); *p = PPCI_B | ((uint32_t)delta & 0x03ffffffu); if (!cstart) cstart = p; } } /* Always patch long-range branch in exit stub itself. Except, if we can't. */ if (patchlong) { ptrdiff_t delta = (char *)target - (char *)px - clearso; lj_assertJ(((delta + 0x02000000) >> 26) == 0, "branch target out of range"); *px = PPCI_B | ((uint32_t)delta & 0x03ffffffu); } if (!cstart) cstart = px; lj_mcode_sync(cstart, px+1); if (clearso) { /* Extend the current trace. Ugly workaround. */ MCode *pp = J->cur.mcode; J->cur.szmcode += sizeof(MCode); *--pp = PPCI_MCRXR; /* Clear SO flag. */ J->cur.mcode = pp; lj_mcode_sync(pp, pp+1); } lj_mcode_patch(J, mcarea, 1); }
xLua/build/luajit-2.1.0b3/src/lj_asm_ppc.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_asm_ppc.h", "repo_id": "xLua", "token_count": 37473 }
1,939
/* ** String scanning. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_STRSCAN_H #define _LJ_STRSCAN_H #include "lj_obj.h" /* Options for accepted/returned formats. */ #define STRSCAN_OPT_TOINT 0x01 /* Convert to int32_t, if possible. */ #define STRSCAN_OPT_TONUM 0x02 /* Always convert to double. */ #define STRSCAN_OPT_IMAG 0x04 #define STRSCAN_OPT_LL 0x08 #define STRSCAN_OPT_C 0x10 /* Returned format. */ typedef enum { STRSCAN_ERROR, STRSCAN_NUM, STRSCAN_IMAG, STRSCAN_INT, STRSCAN_U32, STRSCAN_I64, STRSCAN_U64, } StrScanFmt; LJ_FUNC StrScanFmt lj_strscan_scan(const uint8_t *p, MSize len, TValue *o, uint32_t opt); LJ_FUNC int LJ_FASTCALL lj_strscan_num(GCstr *str, TValue *o); #if LJ_DUALNUM LJ_FUNC int LJ_FASTCALL lj_strscan_number(GCstr *str, TValue *o); #else #define lj_strscan_number(s, o) lj_strscan_num((s), (o)) #endif /* Check for number or convert string to number/int in-place (!). */ static LJ_AINLINE int lj_strscan_numberobj(TValue *o) { return tvisnumber(o) || (tvisstr(o) && lj_strscan_number(strV(o), o)); } #endif
xLua/build/luajit-2.1.0b3/src/lj_strscan.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_strscan.h", "repo_id": "xLua", "token_count": 501 }
1,940
/* ** VM event handling. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #include <stdio.h> #define lj_vmevent_c #define LUA_CORE #include "lj_obj.h" #include "lj_str.h" #include "lj_tab.h" #include "lj_state.h" #include "lj_dispatch.h" #include "lj_vm.h" #include "lj_vmevent.h" ptrdiff_t lj_vmevent_prepare(lua_State *L, VMEvent ev) { global_State *g = G(L); GCstr *s = lj_str_newlit(L, LJ_VMEVENTS_REGKEY); cTValue *tv = lj_tab_getstr(tabV(registry(L)), s); if (tvistab(tv)) { int hash = VMEVENT_HASH(ev); tv = lj_tab_getint(tabV(tv), hash); if (tv && tvisfunc(tv)) { lj_state_checkstack(L, LUA_MINSTACK); setfuncV(L, L->top++, funcV(tv)); if (LJ_FR2) setnilV(L->top++); return savestack(L, L->top); } } g->vmevmask &= ~VMEVENT_MASK(ev); /* No handler: cache this fact. */ return 0; } void lj_vmevent_call(lua_State *L, ptrdiff_t argbase) { global_State *g = G(L); uint8_t oldmask = g->vmevmask; uint8_t oldh = hook_save(g); int status; g->vmevmask = 0; /* Disable all events. */ hook_vmevent(g); status = lj_vm_pcall(L, restorestack(L, argbase), 0+1, 0); if (LJ_UNLIKELY(status)) { /* Really shouldn't use stderr here, but where else to complain? */ L->top--; fputs("VM handler failed: ", stderr); fputs(tvisstr(L->top) ? strVdata(L->top) : "?", stderr); fputc('\n', stderr); } hook_restore(g, oldh); if (g->vmevmask != VMEVENT_NOCACHE) g->vmevmask = oldmask; /* Restore event mask, but not if not modified. */ }
xLua/build/luajit-2.1.0b3/src/lj_vmevent.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_vmevent.c", "repo_id": "xLua", "token_count": 740 }
1,941
|// Low-level VM code for MIPS CPUs. |// Bytecode interpreter, fast functions and helper functions. |// Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h |// |// MIPS soft-float support contributed by Djordje Kovacevic and |// Stefan Pejic from RT-RK.com, sponsored by Cisco Systems, Inc. | |.arch mips |.section code_op, code_sub | |.actionlist build_actionlist |.globals GLOB_ |.globalnames globnames |.externnames extnames | |// Note: The ragged indentation of the instructions is intentional. |// The starting columns indicate data dependencies. | |//----------------------------------------------------------------------- | |// Fixed register assignments for the interpreter. |// Don't use: r0 = 0, r26/r27 = reserved, r28 = gp, r29 = sp, r31 = ra | |.macro .FPU, a, b |.if FPU | a, b |.endif |.endmacro | |// The following must be C callee-save (but BASE is often refetched). |.define BASE, r16 // Base of current Lua stack frame. |.define KBASE, r17 // Constants of current Lua function. |.define PC, r18 // Next PC. |.define DISPATCH, r19 // Opcode dispatch table. |.define LREG, r20 // Register holding lua_State (also in SAVE_L). |.define MULTRES, r21 // Size of multi-result: (nresults+1)*8. | |.define JGL, r30 // On-trace: global_State + 32768. | |// Constants for type-comparisons, stores and conversions. C callee-save. |.define TISNUM, r22 |.define TISNIL, r30 |.if FPU |.define TOBIT, f30 // 2^52 + 2^51. |.endif | |// The following temporaries are not saved across C calls, except for RA. |.define RA, r23 // Callee-save. |.define RB, r8 |.define RC, r9 |.define RD, r10 |.define INS, r11 | |.define AT, r1 // Assembler temporary. |.define TMP0, r12 |.define TMP1, r13 |.define TMP2, r14 |.define TMP3, r15 | |// MIPS o32 calling convention. |.define CFUNCADDR, r25 |.define CARG1, r4 |.define CARG2, r5 |.define CARG3, r6 |.define CARG4, r7 | |.define CRET1, r2 |.define CRET2, r3 | |.if ENDIAN_LE |.define SFRETLO, CRET1 |.define SFRETHI, CRET2 |.define SFARG1LO, CARG1 |.define SFARG1HI, CARG2 |.define SFARG2LO, CARG3 |.define SFARG2HI, CARG4 |.else |.define SFRETLO, CRET2 |.define SFRETHI, CRET1 |.define SFARG1LO, CARG2 |.define SFARG1HI, CARG1 |.define SFARG2LO, CARG4 |.define SFARG2HI, CARG3 |.endif | |.if FPU |.define FARG1, f12 |.define FARG2, f14 | |.define FRET1, f0 |.define FRET2, f2 |.endif | |// Stack layout while in interpreter. Must match with lj_frame.h. |.if FPU // MIPS32 hard-float. | |.define CFRAME_SPACE, 112 // Delta for sp. | |.define SAVE_ERRF, 124(sp) // 32 bit C frame info. |.define SAVE_NRES, 120(sp) |.define SAVE_CFRAME, 116(sp) |.define SAVE_L, 112(sp) |//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by interpreter. |.define SAVE_GPR_, 72 // .. 72+10*4: 32 bit GPR saves. |.define SAVE_FPR_, 24 // .. 24+6*8: 64 bit FPR saves. | |.else // MIPS32 soft-float | |.define CFRAME_SPACE, 64 // Delta for sp. | |.define SAVE_ERRF, 76(sp) // 32 bit C frame info. |.define SAVE_NRES, 72(sp) |.define SAVE_CFRAME, 68(sp) |.define SAVE_L, 64(sp) |//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by interpreter. |.define SAVE_GPR_, 24 // .. 24+10*4: 32 bit GPR saves. | |.endif | |.define SAVE_PC, 20(sp) |.define ARG5, 16(sp) |.define CSAVE_4, 12(sp) |.define CSAVE_3, 8(sp) |.define CSAVE_2, 4(sp) |.define CSAVE_1, 0(sp) |//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by callee. | |.define ARG5_OFS, 16 |.define SAVE_MULTRES, ARG5 | |//----------------------------------------------------------------------- | |.macro saveregs | addiu sp, sp, -CFRAME_SPACE | sw ra, SAVE_GPR_+9*4(sp) | sw r30, SAVE_GPR_+8*4(sp) | .FPU sdc1 f30, SAVE_FPR_+5*8(sp) | sw r23, SAVE_GPR_+7*4(sp) | sw r22, SAVE_GPR_+6*4(sp) | .FPU sdc1 f28, SAVE_FPR_+4*8(sp) | sw r21, SAVE_GPR_+5*4(sp) | sw r20, SAVE_GPR_+4*4(sp) | .FPU sdc1 f26, SAVE_FPR_+3*8(sp) | sw r19, SAVE_GPR_+3*4(sp) | sw r18, SAVE_GPR_+2*4(sp) | .FPU sdc1 f24, SAVE_FPR_+2*8(sp) | sw r17, SAVE_GPR_+1*4(sp) | sw r16, SAVE_GPR_+0*4(sp) | .FPU sdc1 f22, SAVE_FPR_+1*8(sp) | .FPU sdc1 f20, SAVE_FPR_+0*8(sp) |.endmacro | |.macro restoreregs_ret | lw ra, SAVE_GPR_+9*4(sp) | lw r30, SAVE_GPR_+8*4(sp) | .FPU ldc1 f30, SAVE_FPR_+5*8(sp) | lw r23, SAVE_GPR_+7*4(sp) | lw r22, SAVE_GPR_+6*4(sp) | .FPU ldc1 f28, SAVE_FPR_+4*8(sp) | lw r21, SAVE_GPR_+5*4(sp) | lw r20, SAVE_GPR_+4*4(sp) | .FPU ldc1 f26, SAVE_FPR_+3*8(sp) | lw r19, SAVE_GPR_+3*4(sp) | lw r18, SAVE_GPR_+2*4(sp) | .FPU ldc1 f24, SAVE_FPR_+2*8(sp) | lw r17, SAVE_GPR_+1*4(sp) | lw r16, SAVE_GPR_+0*4(sp) | .FPU ldc1 f22, SAVE_FPR_+1*8(sp) | .FPU ldc1 f20, SAVE_FPR_+0*8(sp) | jr ra | addiu sp, sp, CFRAME_SPACE |.endmacro | |// Type definitions. Some of these are only used for documentation. |.type L, lua_State, LREG |.type GL, global_State |.type TVALUE, TValue |.type GCOBJ, GCobj |.type STR, GCstr |.type TAB, GCtab |.type LFUNC, GCfuncL |.type CFUNC, GCfuncC |.type PROTO, GCproto |.type UPVAL, GCupval |.type NODE, Node |.type NARGS8, int |.type TRACE, GCtrace |.type SBUF, SBuf | |//----------------------------------------------------------------------- | |// Trap for not-yet-implemented parts. |.macro NYI; .long 0xec1cf0f0; .endmacro | |// Macros to mark delay slots. |.macro ., a; a; .endmacro |.macro ., a,b; a,b; .endmacro |.macro ., a,b,c; a,b,c; .endmacro | |//----------------------------------------------------------------------- | |// Endian-specific defines. |.if ENDIAN_LE |.define FRAME_PC, -4 |.define FRAME_FUNC, -8 |.define HI, 4 |.define LO, 0 |.define OFS_RD, 2 |.define OFS_RA, 1 |.define OFS_OP, 0 |.else |.define FRAME_PC, -8 |.define FRAME_FUNC, -4 |.define HI, 0 |.define LO, 4 |.define OFS_RD, 0 |.define OFS_RA, 2 |.define OFS_OP, 3 |.endif | |// Instruction decode. |.macro decode_OP1, dst, ins; andi dst, ins, 0xff; .endmacro |.macro decode_OP4a, dst, ins; andi dst, ins, 0xff; .endmacro |.macro decode_OP4b, dst; sll dst, dst, 2; .endmacro |.macro decode_RC4a, dst, ins; srl dst, ins, 14; .endmacro |.macro decode_RC4b, dst; andi dst, dst, 0x3fc; .endmacro |.macro decode_RD4b, dst; sll dst, dst, 2; .endmacro |.macro decode_RA8a, dst, ins; srl dst, ins, 5; .endmacro |.macro decode_RA8b, dst; andi dst, dst, 0x7f8; .endmacro |.macro decode_RB8a, dst, ins; srl dst, ins, 21; .endmacro |.macro decode_RB8b, dst; andi dst, dst, 0x7f8; .endmacro |.macro decode_RD8a, dst, ins; srl dst, ins, 16; .endmacro |.macro decode_RD8b, dst; sll dst, dst, 3; .endmacro |.macro decode_RDtoRC8, dst, src; andi dst, src, 0x7f8; .endmacro | |// Instruction fetch. |.macro ins_NEXT1 | lw INS, 0(PC) | addiu PC, PC, 4 |.endmacro |// Instruction decode+dispatch. |.macro ins_NEXT2 | decode_OP4a TMP1, INS | decode_OP4b TMP1 | addu TMP0, DISPATCH, TMP1 | decode_RD8a RD, INS | lw AT, 0(TMP0) | decode_RA8a RA, INS | decode_RD8b RD | jr AT | decode_RA8b RA |.endmacro |.macro ins_NEXT | ins_NEXT1 | ins_NEXT2 |.endmacro | |// Instruction footer. |.if 1 | // Replicated dispatch. Less unpredictable branches, but higher I-Cache use. | .define ins_next, ins_NEXT | .define ins_next_, ins_NEXT | .define ins_next1, ins_NEXT1 | .define ins_next2, ins_NEXT2 |.else | // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch. | // Affects only certain kinds of benchmarks (and only with -j off). | .macro ins_next | b ->ins_next | .endmacro | .macro ins_next1 | .endmacro | .macro ins_next2 | b ->ins_next | .endmacro | .macro ins_next_ | ->ins_next: | ins_NEXT | .endmacro |.endif | |// Call decode and dispatch. |.macro ins_callt | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC | lw PC, LFUNC:RB->pc | lw INS, 0(PC) | addiu PC, PC, 4 | decode_OP4a TMP1, INS | decode_RA8a RA, INS | decode_OP4b TMP1 | decode_RA8b RA | addu TMP0, DISPATCH, TMP1 | lw TMP0, 0(TMP0) | jr TMP0 | addu RA, RA, BASE |.endmacro | |.macro ins_call | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, PC = caller PC | sw PC, FRAME_PC(BASE) | ins_callt |.endmacro | |//----------------------------------------------------------------------- | |.macro branch_RD | srl TMP0, RD, 1 | lui AT, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP0, TMP0, AT | addu PC, PC, TMP0 |.endmacro | |// Assumes DISPATCH is relative to GL. #define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field)) #define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field)) #define GG_DISP2GOT (GG_OFS(got) - GG_OFS(dispatch)) #define DISPATCH_GOT(name) (GG_DISP2GOT + 4*LJ_GOT_##name) | #define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto)) | |.macro load_got, func | lw CFUNCADDR, DISPATCH_GOT(func)(DISPATCH) |.endmacro |// Much faster. Sadly, there's no easy way to force the required code layout. |// .macro call_intern, func; bal extern func; .endmacro |.macro call_intern, func; jalr CFUNCADDR; .endmacro |.macro call_extern; jalr CFUNCADDR; .endmacro |.macro jmp_extern; jr CFUNCADDR; .endmacro | |.macro hotcheck, delta, target | srl TMP1, PC, 1 | andi TMP1, TMP1, 126 | addu TMP1, TMP1, DISPATCH | lhu TMP2, GG_DISP2HOT(TMP1) | addiu TMP2, TMP2, -delta | bltz TMP2, target |. sh TMP2, GG_DISP2HOT(TMP1) |.endmacro | |.macro hotloop | hotcheck HOTCOUNT_LOOP, ->vm_hotloop |.endmacro | |.macro hotcall | hotcheck HOTCOUNT_CALL, ->vm_hotcall |.endmacro | |// Set current VM state. Uses TMP0. |.macro li_vmstate, st; li TMP0, ~LJ_VMST_..st; .endmacro |.macro st_vmstate; sw TMP0, DISPATCH_GL(vmstate)(DISPATCH); .endmacro | |// Move table write barrier back. Overwrites mark and tmp. |.macro barrierback, tab, mark, tmp, target | lw tmp, DISPATCH_GL(gc.grayagain)(DISPATCH) | andi mark, mark, ~LJ_GC_BLACK & 255 // black2gray(tab) | sw tab, DISPATCH_GL(gc.grayagain)(DISPATCH) | sb mark, tab->marked | b target |. sw tmp, tab->gclist |.endmacro | |//----------------------------------------------------------------------- /* Generate subroutines used by opcodes and other parts of the VM. */ /* The .code_sub section should be last to help static branch prediction. */ static void build_subroutines(BuildCtx *ctx) { |.code_sub | |//----------------------------------------------------------------------- |//-- Return handling ---------------------------------------------------- |//----------------------------------------------------------------------- | |->vm_returnp: | // See vm_return. Also: TMP2 = previous base. | andi AT, PC, FRAME_P | beqz AT, ->cont_dispatch |. li TMP1, LJ_TTRUE | | // Return from pcall or xpcall fast func. | lw PC, FRAME_PC(TMP2) // Fetch PC of previous frame. | move BASE, TMP2 // Restore caller base. | // Prepending may overwrite the pcall frame, so do it at the end. | sw TMP1, FRAME_PC(RA) // Prepend true to results. | addiu RA, RA, -8 | |->vm_returnc: | addiu RD, RD, 8 // RD = (nresults+1)*8. | andi TMP0, PC, FRAME_TYPE | beqz RD, ->vm_unwind_c_eh |. li CRET1, LUA_YIELD | beqz TMP0, ->BC_RET_Z // Handle regular return to Lua. |. move MULTRES, RD | |->vm_return: | // BASE = base, RA = resultptr, RD/MULTRES = (nresults+1)*8, PC = return | // TMP0 = PC & FRAME_TYPE | li TMP2, -8 | xori AT, TMP0, FRAME_C | and TMP2, PC, TMP2 | bnez AT, ->vm_returnp |. subu TMP2, BASE, TMP2 // TMP2 = previous base. | | addiu TMP1, RD, -8 | sw TMP2, L->base | li_vmstate C | lw TMP2, SAVE_NRES | addiu BASE, BASE, -8 | st_vmstate | beqz TMP1, >2 |. sll TMP2, TMP2, 3 |1: | addiu TMP1, TMP1, -8 | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | addiu RA, RA, 8 | sw SFRETHI, HI(BASE) | sw SFRETLO, LO(BASE) | bnez TMP1, <1 |. addiu BASE, BASE, 8 | |2: | bne TMP2, RD, >6 |3: |. sw BASE, L->top // Store new top. | |->vm_leave_cp: | lw TMP0, SAVE_CFRAME // Restore previous C frame. | move CRET1, r0 // Ok return status for vm_pcall. | sw TMP0, L->cframe | |->vm_leave_unw: | restoreregs_ret | |6: | lw TMP1, L->maxstack | slt AT, TMP2, RD | bnez AT, >7 // Less results wanted? | // More results wanted. Check stack size and fill up results with nil. |. slt AT, BASE, TMP1 | beqz AT, >8 |. nop | sw TISNIL, HI(BASE) | addiu RD, RD, 8 | b <2 |. addiu BASE, BASE, 8 | |7: // Less results wanted. | subu TMP0, RD, TMP2 | subu TMP0, BASE, TMP0 // Either keep top or shrink it. | b <3 |. movn BASE, TMP0, TMP2 // LUA_MULTRET+1 case? | |8: // Corner case: need to grow stack for filling up results. | // This can happen if: | // - A C function grows the stack (a lot). | // - The GC shrinks the stack in between. | // - A return back from a lua_call() with (high) nresults adjustment. | load_got lj_state_growstack | move MULTRES, RD | srl CARG2, TMP2, 3 | call_intern lj_state_growstack // (lua_State *L, int n) |. move CARG1, L | lw TMP2, SAVE_NRES | lw BASE, L->top // Need the (realloced) L->top in BASE. | move RD, MULTRES | b <2 |. sll TMP2, TMP2, 3 | |->vm_unwind_c: // Unwind C stack, return from vm_pcall. | // (void *cframe, int errcode) | move sp, CARG1 | move CRET1, CARG2 |->vm_unwind_c_eh: // Landing pad for external unwinder. | lw L, SAVE_L | li TMP0, ~LJ_VMST_C | lw GL:TMP1, L->glref | b ->vm_leave_unw |. sw TMP0, GL:TMP1->vmstate | |->vm_unwind_ff: // Unwind C stack, return from ff pcall. | // (void *cframe) | li AT, -4 | and sp, CARG1, AT |->vm_unwind_ff_eh: // Landing pad for external unwinder. | lw L, SAVE_L | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). | li TISNUM, LJ_TISNUM // Setup type comparison constants. | li TISNIL, LJ_TNIL | lw BASE, L->base | lw DISPATCH, L->glref // Setup pointer to dispatch table. | .FPU mtc1 TMP3, TOBIT | li TMP1, LJ_TFALSE | li_vmstate INTERP | lw PC, FRAME_PC(BASE) // Fetch PC of previous frame. | .FPU cvt.d.s TOBIT, TOBIT | addiu RA, BASE, -8 // Results start at BASE-8. | addiu DISPATCH, DISPATCH, GG_G2DISP | sw TMP1, HI(RA) // Prepend false to error message. | st_vmstate | b ->vm_returnc |. li RD, 16 // 2 results: false + error message. | |->vm_unwind_stub: // Jump to exit stub from unwinder. | jr CARG1 |. move ra, CARG2 | |//----------------------------------------------------------------------- |//-- Grow stack for calls ----------------------------------------------- |//----------------------------------------------------------------------- | |->vm_growstack_c: // Grow stack for C function. | b >2 |. li CARG2, LUA_MINSTACK | |->vm_growstack_l: // Grow stack for Lua function. | // BASE = new base, RA = BASE+framesize*8, RC = nargs*8, PC = first PC | addu RC, BASE, RC | subu RA, RA, BASE | sw BASE, L->base | addiu PC, PC, 4 // Must point after first instruction. | sw RC, L->top | srl CARG2, RA, 3 |2: | // L->base = new base, L->top = top | load_got lj_state_growstack | sw PC, SAVE_PC | call_intern lj_state_growstack // (lua_State *L, int n) |. move CARG1, L | lw BASE, L->base | lw RC, L->top | lw LFUNC:RB, FRAME_FUNC(BASE) | subu RC, RC, BASE | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC | ins_callt // Just retry the call. | |//----------------------------------------------------------------------- |//-- Entry points into the assembler VM --------------------------------- |//----------------------------------------------------------------------- | |->vm_resume: // Setup C frame and resume thread. | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0) | saveregs | move L, CARG1 | lw DISPATCH, L->glref // Setup pointer to dispatch table. | move BASE, CARG2 | lbu TMP1, L->status | sw L, SAVE_L | li PC, FRAME_CP | addiu TMP0, sp, CFRAME_RESUME | addiu DISPATCH, DISPATCH, GG_G2DISP | sw r0, SAVE_NRES | sw r0, SAVE_ERRF | sw CARG1, SAVE_PC // Any value outside of bytecode is ok. | sw r0, SAVE_CFRAME | beqz TMP1, >3 |. sw TMP0, L->cframe | | // Resume after yield (like a return). | sw L, DISPATCH_GL(cur_L)(DISPATCH) | move RA, BASE | lw BASE, L->base | li TISNUM, LJ_TISNUM // Setup type comparison constants. | lw TMP1, L->top | lw PC, FRAME_PC(BASE) | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). | subu RD, TMP1, BASE | .FPU mtc1 TMP3, TOBIT | sb r0, L->status | .FPU cvt.d.s TOBIT, TOBIT | li_vmstate INTERP | addiu RD, RD, 8 | st_vmstate | move MULTRES, RD | andi TMP0, PC, FRAME_TYPE | beqz TMP0, ->BC_RET_Z |. li TISNIL, LJ_TNIL | b ->vm_return |. nop | |->vm_pcall: // Setup protected C frame and enter VM. | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef) | saveregs | sw CARG4, SAVE_ERRF | b >1 |. li PC, FRAME_CP | |->vm_call: // Setup C frame and enter VM. | // (lua_State *L, TValue *base, int nres1) | saveregs | li PC, FRAME_C | |1: // Entry point for vm_pcall above (PC = ftype). | lw TMP1, L:CARG1->cframe | move L, CARG1 | sw CARG3, SAVE_NRES | lw DISPATCH, L->glref // Setup pointer to dispatch table. | sw CARG1, SAVE_L | move BASE, CARG2 | addiu DISPATCH, DISPATCH, GG_G2DISP | sw CARG1, SAVE_PC // Any value outside of bytecode is ok. | sw TMP1, SAVE_CFRAME | sw sp, L->cframe // Add our C frame to cframe chain. | |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype). | sw L, DISPATCH_GL(cur_L)(DISPATCH) | lw TMP2, L->base // TMP2 = old base (used in vmeta_call). | li TISNUM, LJ_TISNUM // Setup type comparison constants. | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). | lw TMP1, L->top | .FPU mtc1 TMP3, TOBIT | addu PC, PC, BASE | subu NARGS8:RC, TMP1, BASE | subu PC, PC, TMP2 // PC = frame delta + frame type | .FPU cvt.d.s TOBIT, TOBIT | li_vmstate INTERP | li TISNIL, LJ_TNIL | st_vmstate | |->vm_call_dispatch: | // TMP2 = old base, BASE = new base, RC = nargs*8, PC = caller PC | lw TMP0, FRAME_PC(BASE) | li AT, LJ_TFUNC | bne TMP0, AT, ->vmeta_call |. lw LFUNC:RB, FRAME_FUNC(BASE) | |->vm_call_dispatch_f: | ins_call | // BASE = new base, RB = func, RC = nargs*8, PC = caller PC | |->vm_cpcall: // Setup protected C frame, call C. | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp) | saveregs | move L, CARG1 | lw TMP0, L:CARG1->stack | sw CARG1, SAVE_L | lw TMP1, L->top | lw DISPATCH, L->glref // Setup pointer to dispatch table. | sw CARG1, SAVE_PC // Any value outside of bytecode is ok. | subu TMP0, TMP0, TMP1 // Compute -savestack(L, L->top). | lw TMP1, L->cframe | addiu DISPATCH, DISPATCH, GG_G2DISP | sw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame. | sw r0, SAVE_ERRF // No error function. | sw TMP1, SAVE_CFRAME | sw sp, L->cframe // Add our C frame to cframe chain. | sw L, DISPATCH_GL(cur_L)(DISPATCH) | jalr CARG4 // (lua_State *L, lua_CFunction func, void *ud) |. move CFUNCADDR, CARG4 | move BASE, CRET1 | bnez CRET1, <3 // Else continue with the call. |. li PC, FRAME_CP | b ->vm_leave_cp // No base? Just remove C frame. |. nop | |//----------------------------------------------------------------------- |//-- Metamethod handling ------------------------------------------------ |//----------------------------------------------------------------------- | |// The lj_meta_* functions (except for lj_meta_cat) don't reallocate the |// stack, so BASE doesn't need to be reloaded across these calls. | |//-- Continuation dispatch ---------------------------------------------- | |->cont_dispatch: | // BASE = meta base, RA = resultptr, RD = (nresults+1)*8 | lw TMP0, -16+LO(BASE) // Continuation. | move RB, BASE | move BASE, TMP2 // Restore caller BASE. | lw LFUNC:TMP1, FRAME_FUNC(TMP2) |.if FFI | sltiu AT, TMP0, 2 |.endif | lw PC, -16+HI(RB) // Restore PC from [cont|PC]. | addu TMP2, RA, RD |.if FFI | bnez AT, >1 |.endif |. sw TISNIL, -8+HI(TMP2) // Ensure one valid arg. | lw TMP1, LFUNC:TMP1->pc | // BASE = base, RA = resultptr, RB = meta base | jr TMP0 // Jump to continuation. |. lw KBASE, PC2PROTO(k)(TMP1) | |.if FFI |1: | bnez TMP0, ->cont_ffi_callback // cont = 1: return from FFI callback. | // cont = 0: tailcall from C function. |. addiu TMP1, RB, -16 | b ->vm_call_tail |. subu RC, TMP1, BASE |.endif | |->cont_cat: // RA = resultptr, RB = meta base | lw INS, -4(PC) | addiu CARG2, RB, -16 | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | decode_RB8a MULTRES, INS | decode_RA8a RA, INS | decode_RB8b MULTRES | decode_RA8b RA | addu TMP1, BASE, MULTRES | sw BASE, L->base | subu CARG3, CARG2, TMP1 | sw SFRETHI, HI(CARG2) | bne TMP1, CARG2, ->BC_CAT_Z |. sw SFRETLO, LO(CARG2) | addu RA, BASE, RA | sw SFRETHI, HI(RA) | b ->cont_nop |. sw SFRETLO, LO(RA) | |//-- Table indexing metamethods ----------------------------------------- | |->vmeta_tgets1: | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | li TMP0, LJ_TSTR | sw STR:RC, LO(CARG3) | b >1 |. sw TMP0, HI(CARG3) | |->vmeta_tgets: | addiu CARG2, DISPATCH, DISPATCH_GL(tmptv) | li TMP0, LJ_TTAB | sw TAB:RB, LO(CARG2) | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv2) | sw TMP0, HI(CARG2) | li TMP1, LJ_TSTR | sw STR:RC, LO(CARG3) | b >1 |. sw TMP1, HI(CARG3) | |->vmeta_tgetb: // TMP0 = index | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | sw TMP0, LO(CARG3) | sw TISNUM, HI(CARG3) | |->vmeta_tgetv: |1: | load_got lj_meta_tget | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_meta_tget // (lua_State *L, TValue *o, TValue *k) |. move CARG1, L | // Returns TValue * (finished) or NULL (metamethod). | beqz CRET1, >3 |. addiu TMP1, BASE, -FRAME_CONT | lw SFARG1HI, HI(CRET1) | lw SFARG2HI, LO(CRET1) | ins_next1 | sw SFARG1HI, HI(RA) | sw SFARG2HI, LO(RA) | ins_next2 | |3: // Call __index metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k | lw BASE, L->top | sw PC, -16+HI(BASE) // [cont|PC] | subu PC, BASE, TMP1 | lw LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here. | b ->vm_call_dispatch_f |. li NARGS8:RC, 16 // 2 args for func(t, k). | |->vmeta_tgetr: | load_got lj_tab_getinth | call_intern lj_tab_getinth // (GCtab *t, int32_t key) |. nop | // Returns cTValue * or NULL. | beqz CRET1, ->BC_TGETR_Z |. move SFARG2HI, TISNIL | lw SFARG2HI, HI(CRET1) | b ->BC_TGETR_Z |. lw SFARG2LO, LO(CRET1) | |//----------------------------------------------------------------------- | |->vmeta_tsets1: | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | li TMP0, LJ_TSTR | sw STR:RC, LO(CARG3) | b >1 |. sw TMP0, HI(CARG3) | |->vmeta_tsets: | addiu CARG2, DISPATCH, DISPATCH_GL(tmptv) | li TMP0, LJ_TTAB | sw TAB:RB, LO(CARG2) | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv2) | sw TMP0, HI(CARG2) | li TMP1, LJ_TSTR | sw STR:RC, LO(CARG3) | b >1 |. sw TMP1, HI(CARG3) | |->vmeta_tsetb: // TMP0 = index | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | sw TMP0, LO(CARG3) | sw TISNUM, HI(CARG3) | |->vmeta_tsetv: |1: | load_got lj_meta_tset | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_meta_tset // (lua_State *L, TValue *o, TValue *k) |. move CARG1, L | // Returns TValue * (finished) or NULL (metamethod). | lw SFARG1HI, HI(RA) | beqz CRET1, >3 |. lw SFARG1LO, LO(RA) | // NOBARRIER: lj_meta_tset ensures the table is not black. | ins_next1 | sw SFARG1HI, HI(CRET1) | sw SFARG1LO, LO(CRET1) | ins_next2 | |3: // Call __newindex metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k/(v) | addiu TMP1, BASE, -FRAME_CONT | lw BASE, L->top | sw PC, -16+HI(BASE) // [cont|PC] | subu PC, BASE, TMP1 | lw LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here. | sw SFARG1HI, 16+HI(BASE) // Copy value to third argument. | sw SFARG1LO, 16+LO(BASE) | b ->vm_call_dispatch_f |. li NARGS8:RC, 24 // 3 args for func(t, k, v) | |->vmeta_tsetr: | load_got lj_tab_setinth | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key) |. move CARG1, L | // Returns TValue *. | b ->BC_TSETR_Z |. nop | |//-- Comparison metamethods --------------------------------------------- | |->vmeta_comp: | // RA/RD point to o1/o2. | move CARG2, RA | move CARG3, RD | load_got lj_meta_comp | addiu PC, PC, -4 | sw BASE, L->base | sw PC, SAVE_PC | decode_OP1 CARG4, INS | call_intern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op) |. move CARG1, L | // Returns 0/1 or TValue * (metamethod). |3: | sltiu AT, CRET1, 2 | beqz AT, ->vmeta_binop | negu TMP2, CRET1 |4: | lhu RD, OFS_RD(PC) | addiu PC, PC, 4 | lui TMP1, (-(BCBIAS_J*4 >> 16) & 65535) | sll RD, RD, 2 | addu RD, RD, TMP1 | and RD, RD, TMP2 | addu PC, PC, RD |->cont_nop: | ins_next | |->cont_ra: // RA = resultptr | lbu TMP1, -4+OFS_RA(PC) | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | sll TMP1, TMP1, 3 | addu TMP1, BASE, TMP1 | sw SFRETHI, HI(TMP1) | b ->cont_nop |. sw SFRETLO, LO(TMP1) | |->cont_condt: // RA = resultptr | lw TMP0, HI(RA) | sltiu AT, TMP0, LJ_TISTRUECOND | b <4 |. negu TMP2, AT // Branch if result is true. | |->cont_condf: // RA = resultptr | lw TMP0, HI(RA) | sltiu AT, TMP0, LJ_TISTRUECOND | b <4 |. addiu TMP2, AT, -1 // Branch if result is false. | |->vmeta_equal: | // SFARG1LO/SFARG2LO point to o1/o2. TMP0 is set to 0/1. | load_got lj_meta_equal | move CARG2, SFARG1LO | move CARG3, SFARG2LO | move CARG4, TMP0 | addiu PC, PC, -4 | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne) |. move CARG1, L | // Returns 0/1 or TValue * (metamethod). | b <3 |. nop | |->vmeta_equal_cd: |.if FFI | load_got lj_meta_equal_cd | move CARG2, INS | addiu PC, PC, -4 | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_meta_equal_cd // (lua_State *L, BCIns op) |. move CARG1, L | // Returns 0/1 or TValue * (metamethod). | b <3 |. nop |.endif | |->vmeta_istype: | load_got lj_meta_istype | addiu PC, PC, -4 | sw BASE, L->base | srl CARG2, RA, 3 | srl CARG3, RD, 3 | sw PC, SAVE_PC | call_intern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp) |. move CARG1, L | b ->cont_nop |. nop | |//-- Arithmetic metamethods --------------------------------------------- | |->vmeta_unm: | move RC, RB | |->vmeta_arith: | load_got lj_meta_arith | decode_OP1 TMP0, INS | sw BASE, L->base | move CARG2, RA | sw PC, SAVE_PC | move CARG3, RB | move CARG4, RC | sw TMP0, ARG5 | call_intern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op) |. move CARG1, L | // Returns NULL (finished) or TValue * (metamethod). | beqz CRET1, ->cont_nop |. nop | | // Call metamethod for binary op. |->vmeta_binop: | // BASE = old base, CRET1 = new base, stack = cont/func/o1/o2 | subu TMP1, CRET1, BASE | sw PC, -16+HI(CRET1) // [cont|PC] | move TMP2, BASE | addiu PC, TMP1, FRAME_CONT | move BASE, CRET1 | b ->vm_call_dispatch |. li NARGS8:RC, 16 // 2 args for func(o1, o2). | |->vmeta_len: | // CARG2 already set by BC_LEN. #if LJ_52 | move MULTRES, CARG1 #endif | load_got lj_meta_len | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_meta_len // (lua_State *L, TValue *o) |. move CARG1, L | // Returns NULL (retry) or TValue * (metamethod base). #if LJ_52 | bnez CRET1, ->vmeta_binop // Binop call for compatibility. |. nop | b ->BC_LEN_Z |. move CARG1, MULTRES #else | b ->vmeta_binop // Binop call for compatibility. |. nop #endif | |//-- Call metamethod ---------------------------------------------------- | |->vmeta_call: // Resolve and call __call metamethod. | // TMP2 = old base, BASE = new base, RC = nargs*8 | load_got lj_meta_call | sw TMP2, L->base // This is the callers base! | addiu CARG2, BASE, -8 | sw PC, SAVE_PC | addu CARG3, BASE, RC | move MULTRES, NARGS8:RC | call_intern lj_meta_call // (lua_State *L, TValue *func, TValue *top) |. move CARG1, L | lw LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here. | addiu NARGS8:RC, MULTRES, 8 // Got one more argument now. | ins_call | |->vmeta_callt: // Resolve __call for BC_CALLT. | // BASE = old base, RA = new base, RC = nargs*8 | load_got lj_meta_call | sw BASE, L->base | addiu CARG2, RA, -8 | sw PC, SAVE_PC | addu CARG3, RA, RC | move MULTRES, NARGS8:RC | call_intern lj_meta_call // (lua_State *L, TValue *func, TValue *top) |. move CARG1, L | lw TMP1, FRAME_PC(BASE) | lw LFUNC:RB, FRAME_FUNC(RA) // Guaranteed to be a function here. | b ->BC_CALLT_Z |. addiu NARGS8:RC, MULTRES, 8 // Got one more argument now. | |//-- Argument coercion for 'for' statement ------------------------------ | |->vmeta_for: | load_got lj_meta_for | sw BASE, L->base | move CARG2, RA | sw PC, SAVE_PC | move MULTRES, INS | call_intern lj_meta_for // (lua_State *L, TValue *base) |. move CARG1, L |.if JIT | decode_OP1 TMP0, MULTRES | li AT, BC_JFORI |.endif | decode_RA8a RA, MULTRES | decode_RD8a RD, MULTRES | decode_RA8b RA |.if JIT | beq TMP0, AT, =>BC_JFORI |. decode_RD8b RD | b =>BC_FORI |. nop |.else | b =>BC_FORI |. decode_RD8b RD |.endif | |//----------------------------------------------------------------------- |//-- Fast functions ----------------------------------------------------- |//----------------------------------------------------------------------- | |.macro .ffunc, name |->ff_ .. name: |.endmacro | |.macro .ffunc_1, name |->ff_ .. name: | lw SFARG1HI, HI(BASE) | beqz NARGS8:RC, ->fff_fallback |. lw SFARG1LO, LO(BASE) |.endmacro | |.macro .ffunc_2, name |->ff_ .. name: | sltiu AT, NARGS8:RC, 16 | lw SFARG1HI, HI(BASE) | bnez AT, ->fff_fallback |. lw SFARG2HI, 8+HI(BASE) | lw SFARG1LO, LO(BASE) | lw SFARG2LO, 8+LO(BASE) |.endmacro | |.macro .ffunc_n, name // Caveat: has delay slot! |->ff_ .. name: | lw SFARG1HI, HI(BASE) |.if FPU | ldc1 FARG1, 0(BASE) |.else | lw SFARG1LO, LO(BASE) |.endif | beqz NARGS8:RC, ->fff_fallback |. sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->fff_fallback |.endmacro | |.macro .ffunc_nn, name // Caveat: has delay slot! |->ff_ .. name: | sltiu AT, NARGS8:RC, 16 | lw SFARG1HI, HI(BASE) | bnez AT, ->fff_fallback |. lw SFARG2HI, 8+HI(BASE) | sltiu TMP0, SFARG1HI, LJ_TISNUM |.if FPU | ldc1 FARG1, 0(BASE) |.else | lw SFARG1LO, LO(BASE) |.endif | sltiu TMP1, SFARG2HI, LJ_TISNUM |.if FPU | ldc1 FARG2, 8(BASE) |.else | lw SFARG2LO, 8+LO(BASE) |.endif | and TMP0, TMP0, TMP1 | beqz TMP0, ->fff_fallback |.endmacro | |// Inlined GC threshold check. Caveat: uses TMP0 and TMP1 and has delay slot! |.macro ffgccheck | lw TMP0, DISPATCH_GL(gc.total)(DISPATCH) | lw TMP1, DISPATCH_GL(gc.threshold)(DISPATCH) | subu AT, TMP0, TMP1 | bgezal AT, ->fff_gcstep |.endmacro | |//-- Base library: checks ----------------------------------------------- | |.ffunc_1 assert | sltiu AT, SFARG1HI, LJ_TISTRUECOND | beqz AT, ->fff_fallback |. addiu RA, BASE, -8 | lw PC, FRAME_PC(BASE) | addiu RD, NARGS8:RC, 8 // Compute (nresults+1)*8. | addu TMP2, RA, NARGS8:RC | sw SFARG1HI, HI(RA) | addiu TMP1, BASE, 8 | beq BASE, TMP2, ->fff_res // Done if exactly 1 argument. |. sw SFARG1LO, LO(RA) |1: | lw SFRETHI, HI(TMP1) | lw SFRETLO, LO(TMP1) | sw SFRETHI, -8+HI(TMP1) | sw SFRETLO, -8+LO(TMP1) | bne TMP1, TMP2, <1 |. addiu TMP1, TMP1, 8 | b ->fff_res |. nop | |.ffunc type | lw SFARG1HI, HI(BASE) | beqz NARGS8:RC, ->fff_fallback |. sltiu TMP0, SFARG1HI, LJ_TISNUM | movn SFARG1HI, TISNUM, TMP0 | not TMP1, SFARG1HI | sll TMP1, TMP1, 3 | addu TMP1, CFUNC:RB, TMP1 | lw SFARG1HI, CFUNC:TMP1->upvalue[0].u32.hi | b ->fff_restv |. lw SFARG1LO, CFUNC:TMP1->upvalue[0].u32.lo | |//-- Base library: getters and setters --------------------------------- | |.ffunc_1 getmetatable | li AT, LJ_TTAB | bne SFARG1HI, AT, >6 |. li AT, LJ_TUDATA |1: // Field metatable must be at same offset for GCtab and GCudata! | lw TAB:SFARG1LO, TAB:SFARG1LO->metatable |2: | lw STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH) | beqz TAB:SFARG1LO, ->fff_restv |. li SFARG1HI, LJ_TNIL | lw TMP0, TAB:SFARG1LO->hmask | li SFARG1HI, LJ_TTAB // Use metatable as default result. | lw TMP1, STR:RC->sid | lw NODE:TMP2, TAB:SFARG1LO->node | and TMP1, TMP1, TMP0 // idx = str->sid & tab->hmask | sll TMP0, TMP1, 5 | sll TMP1, TMP1, 3 | subu TMP1, TMP0, TMP1 | addu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8) | li AT, LJ_TSTR |3: // Rearranged logic, because we expect _not_ to find the key. | lw CARG4, offsetof(Node, key)+HI(NODE:TMP2) | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) | lw NODE:TMP3, NODE:TMP2->next | bne CARG4, AT, >4 |. lw CARG3, offsetof(Node, val)+HI(NODE:TMP2) | beq TMP0, STR:RC, >5 |. lw TMP1, offsetof(Node, val)+LO(NODE:TMP2) |4: | beqz NODE:TMP3, ->fff_restv // Not found, keep default result. |. move NODE:TMP2, NODE:TMP3 | b <3 |. nop |5: | beq CARG3, TISNIL, ->fff_restv // Ditto for nil value. |. nop | move SFARG1HI, CARG3 // Return value of mt.__metatable. | b ->fff_restv |. move SFARG1LO, TMP1 | |6: | beq SFARG1HI, AT, <1 |. sltu AT, TISNUM, SFARG1HI | movz SFARG1HI, TISNUM, AT | not TMP1, SFARG1HI | sll TMP1, TMP1, 2 | addu TMP1, DISPATCH, TMP1 | b <2 |. lw TAB:SFARG1LO, DISPATCH_GL(gcroot[GCROOT_BASEMT])(TMP1) | |.ffunc_2 setmetatable | // Fast path: no mt for table yet and not clearing the mt. | li AT, LJ_TTAB | bne SFARG1HI, AT, ->fff_fallback |. addiu SFARG2HI, SFARG2HI, -LJ_TTAB | lw TAB:TMP1, TAB:SFARG1LO->metatable | lbu TMP3, TAB:SFARG1LO->marked | or AT, SFARG2HI, TAB:TMP1 | bnez AT, ->fff_fallback |. andi AT, TMP3, LJ_GC_BLACK // isblack(table) | beqz AT, ->fff_restv |. sw TAB:SFARG2LO, TAB:SFARG1LO->metatable | barrierback TAB:SFARG1LO, TMP3, TMP0, ->fff_restv | |.ffunc rawget | lw CARG4, HI(BASE) | sltiu AT, NARGS8:RC, 16 | lw TAB:CARG2, LO(BASE) | load_got lj_tab_get | addiu CARG4, CARG4, -LJ_TTAB | or AT, AT, CARG4 | bnez AT, ->fff_fallback | addiu CARG3, BASE, 8 | call_intern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key) |. move CARG1, L | // Returns cTValue *. | lw SFARG1HI, HI(CRET1) | b ->fff_restv |. lw SFARG1LO, LO(CRET1) | |//-- Base library: conversions ------------------------------------------ | |.ffunc tonumber | // Only handles the number case inline (without a base argument). | lw CARG1, HI(BASE) | xori AT, NARGS8:RC, 8 // Exactly one number argument. | sltu TMP0, TISNUM, CARG1 | or AT, AT, TMP0 | bnez AT, ->fff_fallback |. lw SFARG1HI, HI(BASE) | b ->fff_restv |. lw SFARG1LO, LO(BASE) | |.ffunc_1 tostring | // Only handles the string or number case inline. | li AT, LJ_TSTR | // A __tostring method in the string base metatable is ignored. | beq SFARG1HI, AT, ->fff_restv // String key? | // Handle numbers inline, unless a number base metatable is present. |. lw TMP1, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH) | sltu TMP0, TISNUM, SFARG1HI | or TMP0, TMP0, TMP1 | bnez TMP0, ->fff_fallback |. sw BASE, L->base // Add frame since C call can throw. | ffgccheck |. sw PC, SAVE_PC // Redundant (but a defined value). | load_got lj_strfmt_number | move CARG1, L | call_intern lj_strfmt_number // (lua_State *L, cTValue *o) |. move CARG2, BASE | // Returns GCstr *. | li SFARG1HI, LJ_TSTR | b ->fff_restv |. move SFARG1LO, CRET1 | |//-- Base library: iterators ------------------------------------------- | |.ffunc next | lw CARG2, HI(BASE) | lw TAB:CARG1, LO(BASE) | beqz NARGS8:RC, ->fff_fallback |. addu TMP2, BASE, NARGS8:RC | li AT, LJ_TTAB | sw TISNIL, HI(TMP2) // Set missing 2nd arg to nil. | bne CARG2, AT, ->fff_fallback |. lw PC, FRAME_PC(BASE) | load_got lj_tab_next | addiu CARG2, BASE, 8 | call_intern lj_tab_next // (GCtab *t, cTValue *key, TValue *o) |. addiu CARG3, BASE, -8 | // Returns 1=found, 0=end, -1=error. | addiu RA, BASE, -8 | bgtz CRET1, ->fff_res // Found key/value. |. li RD, (2+1)*8 | beqz CRET1, ->fff_restv // End of traversal: return nil. |. li SFARG1HI, LJ_TNIL | lw CFUNC:RB, FRAME_FUNC(BASE) | b ->fff_fallback // Invalid key. |. li RC, 2*8 | |.ffunc_1 pairs | li AT, LJ_TTAB | bne SFARG1HI, AT, ->fff_fallback |. lw PC, FRAME_PC(BASE) #if LJ_52 | lw TAB:TMP2, TAB:SFARG1LO->metatable | lw TMP0, CFUNC:RB->upvalue[0].u32.hi | lw TMP1, CFUNC:RB->upvalue[0].u32.lo | bnez TAB:TMP2, ->fff_fallback #else | lw TMP0, CFUNC:RB->upvalue[0].u32.hi | lw TMP1, CFUNC:RB->upvalue[0].u32.lo #endif |. addiu RA, BASE, -8 | sw TISNIL, 8+HI(BASE) | sw TMP0, HI(RA) | sw TMP1, LO(RA) | b ->fff_res |. li RD, (3+1)*8 | |.ffunc ipairs_aux | sltiu AT, NARGS8:RC, 16 | lw CARG3, HI(BASE) | lw TAB:CARG1, LO(BASE) | lw CARG4, 8+HI(BASE) | bnez AT, ->fff_fallback |. addiu CARG3, CARG3, -LJ_TTAB | xor CARG4, CARG4, TISNUM | and AT, CARG3, CARG4 | bnez AT, ->fff_fallback |. lw PC, FRAME_PC(BASE) | lw TMP2, 8+LO(BASE) | lw TMP0, TAB:CARG1->asize | lw TMP1, TAB:CARG1->array | addiu TMP2, TMP2, 1 | sw TISNUM, -8+HI(BASE) | sltu AT, TMP2, TMP0 | sw TMP2, -8+LO(BASE) | beqz AT, >2 // Not in array part? |. addiu RA, BASE, -8 | sll TMP3, TMP2, 3 | addu TMP3, TMP1, TMP3 | lw TMP1, HI(TMP3) | lw TMP2, LO(TMP3) |1: | beq TMP1, TISNIL, ->fff_res // End of iteration, return 0 results. |. li RD, (0+1)*8 | sw TMP1, 8+HI(RA) | sw TMP2, 8+LO(RA) | b ->fff_res |. li RD, (2+1)*8 | |2: // Check for empty hash part first. Otherwise call C function. | lw TMP0, TAB:CARG1->hmask | load_got lj_tab_getinth | beqz TMP0, ->fff_res |. li RD, (0+1)*8 | call_intern lj_tab_getinth // (GCtab *t, int32_t key) |. move CARG2, TMP2 | // Returns cTValue * or NULL. | beqz CRET1, ->fff_res |. li RD, (0+1)*8 | lw TMP1, HI(CRET1) | b <1 |. lw TMP2, LO(CRET1) | |.ffunc_1 ipairs | li AT, LJ_TTAB | bne SFARG1HI, AT, ->fff_fallback |. lw PC, FRAME_PC(BASE) #if LJ_52 | lw TAB:TMP2, TAB:SFARG1LO->metatable | lw TMP0, CFUNC:RB->upvalue[0].u32.hi | lw TMP1, CFUNC:RB->upvalue[0].u32.lo | bnez TAB:TMP2, ->fff_fallback #else | lw TMP0, CFUNC:RB->upvalue[0].u32.hi | lw TMP1, CFUNC:RB->upvalue[0].u32.lo #endif |. addiu RA, BASE, -8 | sw TISNUM, 8+HI(BASE) | sw r0, 8+LO(BASE) | sw TMP0, HI(RA) | sw TMP1, LO(RA) | b ->fff_res |. li RD, (3+1)*8 | |//-- Base library: catch errors ---------------------------------------- | |.ffunc pcall | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH) | beqz NARGS8:RC, ->fff_fallback | move TMP2, BASE | addiu BASE, BASE, 8 | // Remember active hook before pcall. | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT | andi TMP3, TMP3, 1 | addiu PC, TMP3, 8+FRAME_PCALL | b ->vm_call_dispatch |. addiu NARGS8:RC, NARGS8:RC, -8 | |.ffunc xpcall | sltiu AT, NARGS8:RC, 16 | lw CARG4, 8+HI(BASE) | bnez AT, ->fff_fallback |. lw CARG3, 8+LO(BASE) | lw CARG1, LO(BASE) | lw CARG2, HI(BASE) | lbu TMP1, DISPATCH_GL(hookmask)(DISPATCH) | li AT, LJ_TFUNC | move TMP2, BASE | bne CARG4, AT, ->fff_fallback // Traceback must be a function. | addiu BASE, BASE, 16 | // Remember active hook before pcall. | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT | sw CARG3, LO(TMP2) // Swap function and traceback. | sw CARG4, HI(TMP2) | andi TMP3, TMP3, 1 | sw CARG1, 8+LO(TMP2) | sw CARG2, 8+HI(TMP2) | addiu PC, TMP3, 16+FRAME_PCALL | b ->vm_call_dispatch |. addiu NARGS8:RC, NARGS8:RC, -16 | |//-- Coroutine library -------------------------------------------------- | |.macro coroutine_resume_wrap, resume |.if resume |.ffunc coroutine_resume | lw CARG3, HI(BASE) | beqz NARGS8:RC, ->fff_fallback |. lw CARG1, LO(BASE) | li AT, LJ_TTHREAD | bne CARG3, AT, ->fff_fallback |.else |.ffunc coroutine_wrap_aux | lw L:CARG1, CFUNC:RB->upvalue[0].gcr |.endif | lbu TMP0, L:CARG1->status | lw TMP1, L:CARG1->cframe | lw CARG2, L:CARG1->top | lw TMP2, L:CARG1->base | addiu TMP3, TMP0, -LUA_YIELD | bgtz TMP3, ->fff_fallback // st > LUA_YIELD? |. xor TMP2, TMP2, CARG2 | bnez TMP1, ->fff_fallback // cframe != 0? |. or AT, TMP2, TMP0 | lw TMP0, L:CARG1->maxstack | beqz AT, ->fff_fallback // base == top && st == 0? |. lw PC, FRAME_PC(BASE) | addu TMP2, CARG2, NARGS8:RC | sltu AT, TMP0, TMP2 | bnez AT, ->fff_fallback // Stack overflow? |. sw PC, SAVE_PC | sw BASE, L->base |1: |.if resume | addiu BASE, BASE, 8 // Keep resumed thread in stack for GC. | addiu NARGS8:RC, NARGS8:RC, -8 | addiu TMP2, TMP2, -8 |.endif | sw TMP2, L:CARG1->top | addu TMP1, BASE, NARGS8:RC | move CARG3, CARG2 | sw BASE, L->top |2: // Move args to coroutine. | lw SFRETHI, HI(BASE) | lw SFRETLO, LO(BASE) | sltu AT, BASE, TMP1 | beqz AT, >3 |. addiu BASE, BASE, 8 | sw SFRETHI, HI(CARG3) | sw SFRETLO, LO(CARG3) | b <2 |. addiu CARG3, CARG3, 8 |3: | bal ->vm_resume // (lua_State *L, TValue *base, 0, 0) |. move L:RA, L:CARG1 | // Returns thread status. |4: | lw TMP2, L:RA->base | sltiu AT, CRET1, LUA_YIELD+1 | lw TMP3, L:RA->top | li_vmstate INTERP | lw BASE, L->base | sw L, DISPATCH_GL(cur_L)(DISPATCH) | st_vmstate | beqz AT, >8 |. subu RD, TMP3, TMP2 | lw TMP0, L->maxstack | beqz RD, >6 // No results? |. addu TMP1, BASE, RD | sltu AT, TMP0, TMP1 | bnez AT, >9 // Need to grow stack? |. addu TMP3, TMP2, RD | sw TMP2, L:RA->top // Clear coroutine stack. | move TMP1, BASE |5: // Move results from coroutine. | lw SFRETHI, HI(TMP2) | lw SFRETLO, LO(TMP2) | addiu TMP2, TMP2, 8 | sltu AT, TMP2, TMP3 | sw SFRETHI, HI(TMP1) | sw SFRETLO, LO(TMP1) | bnez AT, <5 |. addiu TMP1, TMP1, 8 |6: | andi TMP0, PC, FRAME_TYPE |.if resume | li TMP1, LJ_TTRUE | addiu RA, BASE, -8 | sw TMP1, -8+HI(BASE) // Prepend true to results. | addiu RD, RD, 16 |.else | move RA, BASE | addiu RD, RD, 8 |.endif |7: | sw PC, SAVE_PC | beqz TMP0, ->BC_RET_Z |. move MULTRES, RD | b ->vm_return |. nop | |8: // Coroutine returned with error (at co->top-1). |.if resume | addiu TMP3, TMP3, -8 | li TMP1, LJ_TFALSE | lw SFRETHI, HI(TMP3) | lw SFRETLO, LO(TMP3) | sw TMP3, L:RA->top // Remove error from coroutine stack. | li RD, (2+1)*8 | sw TMP1, -8+HI(BASE) // Prepend false to results. | addiu RA, BASE, -8 | sw SFRETHI, HI(BASE) // Copy error message. | sw SFRETLO, LO(BASE) | b <7 |. andi TMP0, PC, FRAME_TYPE |.else | load_got lj_ffh_coroutine_wrap_err | move CARG2, L:RA | call_intern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co) |. move CARG1, L |.endif | |9: // Handle stack expansion on return from yield. | load_got lj_state_growstack | srl CARG2, RD, 3 | call_intern lj_state_growstack // (lua_State *L, int n) |. move CARG1, L | b <4 |. li CRET1, 0 |.endmacro | | coroutine_resume_wrap 1 // coroutine.resume | coroutine_resume_wrap 0 // coroutine.wrap | |.ffunc coroutine_yield | lw TMP0, L->cframe | addu TMP1, BASE, NARGS8:RC | sw BASE, L->base | andi TMP0, TMP0, CFRAME_RESUME | sw TMP1, L->top | beqz TMP0, ->fff_fallback |. li CRET1, LUA_YIELD | sw r0, L->cframe | b ->vm_leave_unw |. sb CRET1, L->status | |//-- Math library ------------------------------------------------------- | |.ffunc_1 math_abs | bne SFARG1HI, TISNUM, >1 |. sra TMP0, SFARG1LO, 31 | xor TMP1, SFARG1LO, TMP0 | subu SFARG1LO, TMP1, TMP0 | bgez SFARG1LO, ->fff_restv |. nop | lui SFARG1HI, 0x41e0 // 2^31 as a double. | b ->fff_restv |. li SFARG1LO, 0 |1: | sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->fff_fallback |. sll SFARG1HI, SFARG1HI, 1 | srl SFARG1HI, SFARG1HI, 1 |// fallthrough | |->fff_restv: | // SFARG1LO/SFARG1HI = TValue result. | lw PC, FRAME_PC(BASE) | sw SFARG1HI, -8+HI(BASE) | addiu RA, BASE, -8 | sw SFARG1LO, -8+LO(BASE) |->fff_res1: | // RA = results, PC = return. | li RD, (1+1)*8 |->fff_res: | // RA = results, RD = (nresults+1)*8, PC = return. | andi TMP0, PC, FRAME_TYPE | bnez TMP0, ->vm_return |. move MULTRES, RD | lw INS, -4(PC) | decode_RB8a RB, INS | decode_RB8b RB |5: | sltu AT, RD, RB | bnez AT, >6 // More results expected? |. decode_RA8a TMP0, INS | decode_RA8b TMP0 | ins_next1 | // Adjust BASE. KBASE is assumed to be set for the calling frame. | subu BASE, RA, TMP0 | ins_next2 | |6: // Fill up results with nil. | addu TMP1, RA, RD | addiu RD, RD, 8 | b <5 |. sw TISNIL, -8+HI(TMP1) | |.macro math_extern, func | .ffunc math_ .. func | lw SFARG1HI, HI(BASE) | beqz NARGS8:RC, ->fff_fallback |. load_got func | sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->fff_fallback |.if FPU |. ldc1 FARG1, 0(BASE) |.else |. lw SFARG1LO, LO(BASE) |.endif | call_extern |. nop | b ->fff_resn |. nop |.endmacro | |.macro math_extern2, func | .ffunc_nn math_ .. func |. load_got func | call_extern |. nop | b ->fff_resn |. nop |.endmacro | |// TODO: Return integer type if result is integer (own sf implementation). |.macro math_round, func |->ff_math_ .. func: | lw SFARG1HI, HI(BASE) | beqz NARGS8:RC, ->fff_fallback |. lw SFARG1LO, LO(BASE) | beq SFARG1HI, TISNUM, ->fff_restv |. sltu AT, SFARG1HI, TISNUM | beqz AT, ->fff_fallback |.if FPU |. ldc1 FARG1, 0(BASE) | bal ->vm_ .. func |.else |. load_got func | call_extern |.endif |. nop | b ->fff_resn |. nop |.endmacro | | math_round floor | math_round ceil | |.ffunc math_log | li AT, 8 | bne NARGS8:RC, AT, ->fff_fallback // Exactly 1 argument. |. lw SFARG1HI, HI(BASE) | sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->fff_fallback |. load_got log |.if FPU | call_extern |. ldc1 FARG1, 0(BASE) |.else | call_extern |. lw SFARG1LO, LO(BASE) |.endif | b ->fff_resn |. nop | | math_extern log10 | math_extern exp | math_extern sin | math_extern cos | math_extern tan | math_extern asin | math_extern acos | math_extern atan | math_extern sinh | math_extern cosh | math_extern tanh | math_extern2 pow | math_extern2 atan2 | math_extern2 fmod | |.if FPU |.ffunc_n math_sqrt |. sqrt.d FRET1, FARG1 |// fallthrough to ->fff_resn |.else | math_extern sqrt |.endif | |->fff_resn: | lw PC, FRAME_PC(BASE) | addiu RA, BASE, -8 |.if FPU | b ->fff_res1 |. sdc1 FRET1, -8(BASE) |.else | sw SFRETHI, -8+HI(BASE) | b ->fff_res1 |. sw SFRETLO, -8+LO(BASE) |.endif | | |.ffunc math_ldexp | sltiu AT, NARGS8:RC, 16 | lw SFARG1HI, HI(BASE) | bnez AT, ->fff_fallback |. lw CARG4, 8+HI(BASE) | bne CARG4, TISNUM, ->fff_fallback | load_got ldexp |. sltu AT, SFARG1HI, TISNUM | beqz AT, ->fff_fallback |.if FPU |. ldc1 FARG1, 0(BASE) |.else |. lw SFARG1LO, LO(BASE) |.endif | call_extern |. lw CARG3, 8+LO(BASE) | b ->fff_resn |. nop | |.ffunc_n math_frexp | load_got frexp | lw PC, FRAME_PC(BASE) | call_extern |. addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | lw TMP1, DISPATCH_GL(tmptv)(DISPATCH) | addiu RA, BASE, -8 |.if FPU | mtc1 TMP1, FARG2 | sdc1 FRET1, 0(RA) | cvt.d.w FARG2, FARG2 | sdc1 FARG2, 8(RA) |.else | sw SFRETLO, LO(RA) | sw SFRETHI, HI(RA) | sw TMP1, 8+LO(RA) | sw TISNUM, 8+HI(RA) |.endif | b ->fff_res |. li RD, (2+1)*8 | |.ffunc_n math_modf | load_got modf | lw PC, FRAME_PC(BASE) | call_extern |. addiu CARG3, BASE, -8 | addiu RA, BASE, -8 |.if FPU | sdc1 FRET1, 0(BASE) |.else | sw SFRETLO, LO(BASE) | sw SFRETHI, HI(BASE) |.endif | b ->fff_res |. li RD, (2+1)*8 | |.macro math_minmax, name, intins, ismax | .ffunc_1 name | addu TMP3, BASE, NARGS8:RC | bne SFARG1HI, TISNUM, >5 |. addiu TMP2, BASE, 8 |1: // Handle integers. |. lw SFARG2HI, HI(TMP2) | beq TMP2, TMP3, ->fff_restv |. lw SFARG2LO, LO(TMP2) | bne SFARG2HI, TISNUM, >3 |. slt AT, SFARG1LO, SFARG2LO | intins SFARG1LO, SFARG2LO, AT | b <1 |. addiu TMP2, TMP2, 8 | |3: // Convert intermediate result to number and continue with number loop. | sltiu AT, SFARG2HI, LJ_TISNUM | beqz AT, ->fff_fallback |.if FPU |. mtc1 SFARG1LO, FRET1 | cvt.d.w FRET1, FRET1 | b >7 |. ldc1 FARG1, 0(TMP2) |.else |. nop | bal ->vm_sfi2d_1 |. nop | b >7 |. nop |.endif | |5: |. sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->fff_fallback |.if FPU |. ldc1 FRET1, 0(BASE) |.endif | |6: // Handle numbers. |. lw SFARG2HI, HI(TMP2) |.if FPU | beq TMP2, TMP3, ->fff_resn |.else | beq TMP2, TMP3, ->fff_restv |.endif |. sltiu AT, SFARG2HI, LJ_TISNUM | beqz AT, >8 |.if FPU |. ldc1 FARG1, 0(TMP2) |.else |. lw SFARG2LO, LO(TMP2) |.endif |7: |.if FPU |.if ismax | c.olt.d FARG1, FRET1 |.else | c.olt.d FRET1, FARG1 |.endif | movf.d FRET1, FARG1 |.else |.if ismax | bal ->vm_sfcmpogt |.else | bal ->vm_sfcmpolt |.endif |. nop | movz SFARG1LO, SFARG2LO, CRET1 | movz SFARG1HI, SFARG2HI, CRET1 |.endif | b <6 |. addiu TMP2, TMP2, 8 | |8: // Convert integer to number and continue with number loop. | bne SFARG2HI, TISNUM, ->fff_fallback |.if FPU |. lwc1 FARG1, LO(TMP2) | b <7 |. cvt.d.w FARG1, FARG1 |.else |. nop | bal ->vm_sfi2d_2 |. nop | b <7 |. nop |.endif | |.endmacro | | math_minmax math_min, movz, 0 | math_minmax math_max, movn, 1 | |//-- String library ----------------------------------------------------- | |.ffunc string_byte // Only handle the 1-arg case here. | lw CARG3, HI(BASE) | lw STR:CARG1, LO(BASE) | xori AT, NARGS8:RC, 8 | addiu CARG3, CARG3, -LJ_TSTR | or AT, AT, CARG3 | bnez AT, ->fff_fallback // Need exactly 1 string argument. |. nop | lw TMP0, STR:CARG1->len | addiu RA, BASE, -8 | lw PC, FRAME_PC(BASE) | sltu RD, r0, TMP0 | lbu TMP1, STR:CARG1[1] // Access is always ok (NUL at end). | addiu RD, RD, 1 | sll RD, RD, 3 // RD = ((str->len != 0)+1)*8 | sw TISNUM, HI(RA) | b ->fff_res |. sw TMP1, LO(RA) | |.ffunc string_char // Only handle the 1-arg case here. | ffgccheck |. nop | lw CARG3, HI(BASE) | lw CARG1, LO(BASE) | li TMP1, 255 | xori AT, NARGS8:RC, 8 // Exactly 1 argument. | xor TMP0, CARG3, TISNUM // Integer. | sltu TMP1, TMP1, CARG1 // !(255 < n). | or AT, AT, TMP0 | or AT, AT, TMP1 | bnez AT, ->fff_fallback |. li CARG3, 1 | addiu CARG2, sp, ARG5_OFS | sb CARG1, ARG5 |->fff_newstr: | load_got lj_str_new | sw BASE, L->base | sw PC, SAVE_PC | call_intern lj_str_new // (lua_State *L, char *str, size_t l) |. move CARG1, L | // Returns GCstr *. | lw BASE, L->base |->fff_resstr: | move SFARG1LO, CRET1 | b ->fff_restv |. li SFARG1HI, LJ_TSTR | |.ffunc string_sub | ffgccheck |. nop | addiu AT, NARGS8:RC, -16 | lw CARG3, 16+HI(BASE) | lw TMP0, HI(BASE) | lw STR:CARG1, LO(BASE) | bltz AT, ->fff_fallback |. lw CARG2, 8+HI(BASE) | beqz AT, >1 |. li CARG4, -1 | bne CARG3, TISNUM, ->fff_fallback |. lw CARG4, 16+LO(BASE) |1: | bne CARG2, TISNUM, ->fff_fallback |. li AT, LJ_TSTR | bne TMP0, AT, ->fff_fallback |. lw CARG3, 8+LO(BASE) | lw CARG2, STR:CARG1->len | // STR:CARG1 = str, CARG2 = str->len, CARG3 = start, CARG4 = end | slt AT, CARG4, r0 | addiu TMP0, CARG2, 1 | addu TMP1, CARG4, TMP0 | slt TMP3, CARG3, r0 | movn CARG4, TMP1, AT // if (end < 0) end += len+1 | addu TMP1, CARG3, TMP0 | movn CARG3, TMP1, TMP3 // if (start < 0) start += len+1 | li TMP2, 1 | slt AT, CARG4, r0 | slt TMP3, r0, CARG3 | movn CARG4, r0, AT // if (end < 0) end = 0 | movz CARG3, TMP2, TMP3 // if (start < 1) start = 1 | slt AT, CARG2, CARG4 | movn CARG4, CARG2, AT // if (end > len) end = len | addu CARG2, STR:CARG1, CARG3 | subu CARG3, CARG4, CARG3 // len = end - start | addiu CARG2, CARG2, sizeof(GCstr)-1 | bgez CARG3, ->fff_newstr |. addiu CARG3, CARG3, 1 // len++ |->fff_emptystr: // Return empty string. | addiu STR:SFARG1LO, DISPATCH, DISPATCH_GL(strempty) | b ->fff_restv |. li SFARG1HI, LJ_TSTR | |.macro ffstring_op, name | .ffunc string_ .. name | ffgccheck |. nop | lw CARG3, HI(BASE) | lw STR:CARG2, LO(BASE) | beqz NARGS8:RC, ->fff_fallback |. li AT, LJ_TSTR | bne CARG3, AT, ->fff_fallback |. addiu SBUF:CARG1, DISPATCH, DISPATCH_GL(tmpbuf) | load_got lj_buf_putstr_ .. name | lw TMP0, SBUF:CARG1->b | sw L, SBUF:CARG1->L | sw BASE, L->base | sw TMP0, SBUF:CARG1->w | call_intern extern lj_buf_putstr_ .. name |. sw PC, SAVE_PC | load_got lj_buf_tostr | call_intern lj_buf_tostr |. move SBUF:CARG1, SBUF:CRET1 | b ->fff_resstr |. lw BASE, L->base |.endmacro | |ffstring_op reverse |ffstring_op lower |ffstring_op upper | |//-- Bit library -------------------------------------------------------- | |->vm_tobit_fb: | beqz TMP1, ->fff_fallback |.if FPU |. ldc1 FARG1, 0(BASE) | add.d FARG1, FARG1, TOBIT | jr ra |. mfc1 CRET1, FARG1 |.else |// FP number to bit conversion for soft-float. |->vm_tobit: | sll TMP0, SFARG1HI, 1 | lui AT, 0x0020 | addu TMP0, TMP0, AT | slt AT, TMP0, r0 | movz SFARG1LO, r0, AT | beqz AT, >2 |. li TMP1, 0x3e0 | not TMP1, TMP1 | sra TMP0, TMP0, 21 | subu TMP0, TMP1, TMP0 | slt AT, TMP0, r0 | bnez AT, >1 |. sll TMP1, SFARG1HI, 11 | lui AT, 0x8000 | or TMP1, TMP1, AT | srl AT, SFARG1LO, 21 | or TMP1, TMP1, AT | slt AT, SFARG1HI, r0 | beqz AT, >2 |. srlv SFARG1LO, TMP1, TMP0 | subu SFARG1LO, r0, SFARG1LO |2: | jr ra |. move CRET1, SFARG1LO |1: | addiu TMP0, TMP0, 21 | srlv TMP1, SFARG1LO, TMP0 | li AT, 20 | subu TMP0, AT, TMP0 | sll SFARG1LO, SFARG1HI, 12 | sllv AT, SFARG1LO, TMP0 | or SFARG1LO, TMP1, AT | slt AT, SFARG1HI, r0 | beqz AT, <2 |. nop | jr ra |. subu CRET1, r0, SFARG1LO |.endif | |.macro .ffunc_bit, name | .ffunc_1 bit_..name | beq SFARG1HI, TISNUM, >6 |. move CRET1, SFARG1LO | bal ->vm_tobit_fb |. sltu TMP1, SFARG1HI, TISNUM |6: |.endmacro | |.macro .ffunc_bit_op, name, ins | .ffunc_bit name | addiu TMP2, BASE, 8 | addu TMP3, BASE, NARGS8:RC |1: | lw SFARG1HI, HI(TMP2) | beq TMP2, TMP3, ->fff_resi |. lw SFARG1LO, LO(TMP2) |.if FPU | bne SFARG1HI, TISNUM, >2 |. addiu TMP2, TMP2, 8 | b <1 |. ins CRET1, CRET1, SFARG1LO |2: | ldc1 FARG1, -8(TMP2) | sltu TMP1, SFARG1HI, TISNUM | beqz TMP1, ->fff_fallback |. add.d FARG1, FARG1, TOBIT | mfc1 SFARG1LO, FARG1 | b <1 |. ins CRET1, CRET1, SFARG1LO |.else | beq SFARG1HI, TISNUM, >2 |. move CRET2, CRET1 | bal ->vm_tobit_fb |. sltu TMP1, SFARG1HI, TISNUM | move SFARG1LO, CRET2 |2: | ins CRET1, CRET1, SFARG1LO | b <1 |. addiu TMP2, TMP2, 8 |.endif |.endmacro | |.ffunc_bit_op band, and |.ffunc_bit_op bor, or |.ffunc_bit_op bxor, xor | |.ffunc_bit bswap | srl TMP0, CRET1, 24 | srl TMP2, CRET1, 8 | sll TMP1, CRET1, 24 | andi TMP2, TMP2, 0xff00 | or TMP0, TMP0, TMP1 | andi CRET1, CRET1, 0xff00 | or TMP0, TMP0, TMP2 | sll CRET1, CRET1, 8 | b ->fff_resi |. or CRET1, TMP0, CRET1 | |.ffunc_bit bnot | b ->fff_resi |. not CRET1, CRET1 | |.macro .ffunc_bit_sh, name, ins, shmod | .ffunc_2 bit_..name | beq SFARG1HI, TISNUM, >1 |. nop | bal ->vm_tobit_fb |. sltu TMP1, SFARG1HI, TISNUM | move SFARG1LO, CRET1 |1: | bne SFARG2HI, TISNUM, ->fff_fallback |. nop |.if shmod == 1 | li AT, 32 | subu TMP0, AT, SFARG2LO | sllv SFARG2LO, SFARG1LO, SFARG2LO | srlv SFARG1LO, SFARG1LO, TMP0 |.elif shmod == 2 | li AT, 32 | subu TMP0, AT, SFARG2LO | srlv SFARG2LO, SFARG1LO, SFARG2LO | sllv SFARG1LO, SFARG1LO, TMP0 |.endif | b ->fff_resi |. ins CRET1, SFARG1LO, SFARG2LO |.endmacro | |.ffunc_bit_sh lshift, sllv, 0 |.ffunc_bit_sh rshift, srlv, 0 |.ffunc_bit_sh arshift, srav, 0 |// Can't use rotrv, since it's only in MIPS32R2. |.ffunc_bit_sh rol, or, 1 |.ffunc_bit_sh ror, or, 2 | |.ffunc_bit tobit |->fff_resi: | lw PC, FRAME_PC(BASE) | addiu RA, BASE, -8 | sw TISNUM, -8+HI(BASE) | b ->fff_res1 |. sw CRET1, -8+LO(BASE) | |//----------------------------------------------------------------------- | |->fff_fallback: // Call fast function fallback handler. | // BASE = new base, RB = CFUNC, RC = nargs*8 | lw TMP3, CFUNC:RB->f | addu TMP1, BASE, NARGS8:RC | lw PC, FRAME_PC(BASE) // Fallback may overwrite PC. | addiu TMP0, TMP1, 8*LUA_MINSTACK | lw TMP2, L->maxstack | sw PC, SAVE_PC // Redundant (but a defined value). | sltu AT, TMP2, TMP0 | sw BASE, L->base | sw TMP1, L->top | bnez AT, >5 // Need to grow stack. |. move CFUNCADDR, TMP3 | jalr TMP3 // (lua_State *L) |. move CARG1, L | // Either throws an error, or recovers and returns -1, 0 or nresults+1. | lw BASE, L->base | sll RD, CRET1, 3 | bgtz CRET1, ->fff_res // Returned nresults+1? |. addiu RA, BASE, -8 |1: // Returned 0 or -1: retry fast path. | lw TMP0, L->top | lw LFUNC:RB, FRAME_FUNC(BASE) | bnez CRET1, ->vm_call_tail // Returned -1? |. subu NARGS8:RC, TMP0, BASE | ins_callt // Returned 0: retry fast path. | |// Reconstruct previous base for vmeta_call during tailcall. |->vm_call_tail: | andi TMP0, PC, FRAME_TYPE | li AT, -4 | bnez TMP0, >3 |. and TMP1, PC, AT | lbu TMP1, OFS_RA(PC) | sll TMP1, TMP1, 3 | addiu TMP1, TMP1, 8 |3: | b ->vm_call_dispatch // Resolve again for tailcall. |. subu TMP2, BASE, TMP1 | |5: // Grow stack for fallback handler. | load_got lj_state_growstack | li CARG2, LUA_MINSTACK | call_intern lj_state_growstack // (lua_State *L, int n) |. move CARG1, L | lw BASE, L->base | b <1 |. li CRET1, 0 // Force retry. | |->fff_gcstep: // Call GC step function. | // BASE = new base, RC = nargs*8 | move MULTRES, ra | load_got lj_gc_step | sw BASE, L->base | addu TMP0, BASE, NARGS8:RC | sw PC, SAVE_PC // Redundant (but a defined value). | sw TMP0, L->top | call_intern lj_gc_step // (lua_State *L) |. move CARG1, L | lw BASE, L->base | move ra, MULTRES | lw TMP0, L->top | lw CFUNC:RB, FRAME_FUNC(BASE) | jr ra |. subu NARGS8:RC, TMP0, BASE | |//----------------------------------------------------------------------- |//-- Special dispatch targets ------------------------------------------- |//----------------------------------------------------------------------- | |->vm_record: // Dispatch target for recording phase. |.if JIT | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH) | andi AT, TMP3, HOOK_VMEVENT // No recording while in vmevent. | bnez AT, >5 | // Decrement the hookcount for consistency, but always do the call. |. lw TMP2, DISPATCH_GL(hookcount)(DISPATCH) | andi AT, TMP3, HOOK_ACTIVE | bnez AT, >1 |. addiu TMP2, TMP2, -1 | andi AT, TMP3, LUA_MASKLINE|LUA_MASKCOUNT | beqz AT, >1 |. nop | b >1 |. sw TMP2, DISPATCH_GL(hookcount)(DISPATCH) |.endif | |->vm_rethook: // Dispatch target for return hooks. | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH) | andi AT, TMP3, HOOK_ACTIVE // Hook already active? | beqz AT, >1 |5: // Re-dispatch to static ins. |. lw AT, GG_DISP2STATIC(TMP0) // Assumes TMP0 holds DISPATCH+OP*4. | jr AT |. nop | |->vm_inshook: // Dispatch target for instr/line hooks. | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH) | lw TMP2, DISPATCH_GL(hookcount)(DISPATCH) | andi AT, TMP3, HOOK_ACTIVE // Hook already active? | bnez AT, <5 |. andi AT, TMP3, LUA_MASKLINE|LUA_MASKCOUNT | beqz AT, <5 |. addiu TMP2, TMP2, -1 | beqz TMP2, >1 |. sw TMP2, DISPATCH_GL(hookcount)(DISPATCH) | andi AT, TMP3, LUA_MASKLINE | beqz AT, <5 |1: |. load_got lj_dispatch_ins | sw MULTRES, SAVE_MULTRES | move CARG2, PC | sw BASE, L->base | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC. | call_intern lj_dispatch_ins // (lua_State *L, const BCIns *pc) |. move CARG1, L |3: | lw BASE, L->base |4: // Re-dispatch to static ins. | lw INS, -4(PC) | decode_OP4a TMP1, INS | decode_OP4b TMP1 | addu TMP0, DISPATCH, TMP1 | decode_RD8a RD, INS | lw AT, GG_DISP2STATIC(TMP0) | decode_RA8a RA, INS | decode_RD8b RD | jr AT | decode_RA8b RA | |->cont_hook: // Continue from hook yield. | addiu PC, PC, 4 | b <4 |. lw MULTRES, -24+LO(RB) // Restore MULTRES for *M ins. | |->vm_hotloop: // Hot loop counter underflow. |.if JIT | lw LFUNC:TMP1, FRAME_FUNC(BASE) | addiu CARG1, DISPATCH, GG_DISP2J | sw PC, SAVE_PC | lw TMP1, LFUNC:TMP1->pc | move CARG2, PC | sw L, DISPATCH_J(L)(DISPATCH) | lbu TMP1, PC2PROTO(framesize)(TMP1) | load_got lj_trace_hot | sw BASE, L->base | sll TMP1, TMP1, 3 | addu TMP1, BASE, TMP1 | call_intern lj_trace_hot // (jit_State *J, const BCIns *pc) |. sw TMP1, L->top | b <3 |. nop |.endif | |->vm_callhook: // Dispatch target for call hooks. |.if JIT | b >1 |.endif |. move CARG2, PC | |->vm_hotcall: // Hot call counter underflow. |.if JIT | ori CARG2, PC, 1 |1: |.endif | load_got lj_dispatch_call | addu TMP0, BASE, RC | sw PC, SAVE_PC | sw BASE, L->base | subu RA, RA, BASE | sw TMP0, L->top | call_intern lj_dispatch_call // (lua_State *L, const BCIns *pc) |. move CARG1, L | // Returns ASMFunction. | lw BASE, L->base | lw TMP0, L->top | sw r0, SAVE_PC // Invalidate for subsequent line hook. | subu NARGS8:RC, TMP0, BASE | addu RA, BASE, RA | lw LFUNC:RB, FRAME_FUNC(BASE) | jr CRET1 |. lw INS, -4(PC) | |->cont_stitch: // Trace stitching. |.if JIT | // RA = resultptr, RB = meta base | lw INS, -4(PC) | lw TMP2, -24+LO(RB) // Save previous trace. | decode_RA8a RC, INS | addiu AT, MULTRES, -8 | decode_RA8b RC | beqz AT, >2 |. addu RC, BASE, RC // Call base. |1: // Move results down. | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | addiu AT, AT, -8 | addiu RA, RA, 8 | sw SFRETHI, HI(RC) | sw SFRETLO, LO(RC) | bnez AT, <1 |. addiu RC, RC, 8 |2: | decode_RA8a RA, INS | decode_RB8a RB, INS | decode_RA8b RA | decode_RB8b RB | addu RA, RA, RB | addu RA, BASE, RA |3: | sltu AT, RC, RA | bnez AT, >9 // More results wanted? |. nop | | lhu TMP3, TRACE:TMP2->traceno | lhu RD, TRACE:TMP2->link | beq RD, TMP3, ->cont_nop // Blacklisted. |. load_got lj_dispatch_stitch | bnez RD, =>BC_JLOOP // Jump to stitched trace. |. sll RD, RD, 3 | | // Stitch a new trace to the previous trace. | sw TMP3, DISPATCH_J(exitno)(DISPATCH) | sw L, DISPATCH_J(L)(DISPATCH) | sw BASE, L->base | addiu CARG1, DISPATCH, GG_DISP2J | call_intern lj_dispatch_stitch // (jit_State *J, const BCIns *pc) |. move CARG2, PC | b ->cont_nop |. lw BASE, L->base | |9: | sw TISNIL, HI(RC) | b <3 |. addiu RC, RC, 8 |.endif | |->vm_profhook: // Dispatch target for profiler hook. #if LJ_HASPROFILE | load_got lj_dispatch_profile | sw MULTRES, SAVE_MULTRES | move CARG2, PC | sw BASE, L->base | call_intern lj_dispatch_profile // (lua_State *L, const BCIns *pc) |. move CARG1, L | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction. | addiu PC, PC, -4 | b ->cont_nop |. lw BASE, L->base #endif | |//----------------------------------------------------------------------- |//-- Trace exit handler ------------------------------------------------- |//----------------------------------------------------------------------- | |.macro savex_, a, b |.if FPU | sdc1 f..a, 16+a*8(sp) | sw r..a, 16+32*8+a*4(sp) | sw r..b, 16+32*8+b*4(sp) |.else | sw r..a, 16+a*4(sp) | sw r..b, 16+b*4(sp) |.endif |.endmacro | |->vm_exit_handler: |.if JIT |.if FPU | addiu sp, sp, -(16+32*8+32*4) |.else | addiu sp, sp, -(16+32*4) |.endif | savex_ 0, 1 | savex_ 2, 3 | savex_ 4, 5 | savex_ 6, 7 | savex_ 8, 9 | savex_ 10, 11 | savex_ 12, 13 | savex_ 14, 15 | savex_ 16, 17 | savex_ 18, 19 | savex_ 20, 21 | savex_ 22, 23 | savex_ 24, 25 | savex_ 26, 27 |.if FPU | sdc1 f28, 16+28*8(sp) | sdc1 f30, 16+30*8(sp) | sw r28, 16+32*8+28*4(sp) | sw r30, 16+32*8+30*4(sp) | sw r0, 16+32*8+31*4(sp) // Clear RID_TMP. | addiu TMP2, sp, 16+32*8+32*4 // Recompute original value of sp. | sw TMP2, 16+32*8+29*4(sp) // Store sp in RID_SP |.else | sw r28, 16+28*4(sp) | sw r30, 16+30*4(sp) | sw r0, 16+31*4(sp) // Clear RID_TMP. | addiu TMP2, sp, 16+32*4 // Recompute original value of sp. | sw TMP2, 16+29*4(sp) // Store sp in RID_SP |.endif | li_vmstate EXIT | addiu DISPATCH, JGL, -GG_DISP2G-32768 | lw TMP1, 0(TMP2) // Load exit number. | st_vmstate | lw L, DISPATCH_GL(cur_L)(DISPATCH) | lw BASE, DISPATCH_GL(jit_base)(DISPATCH) | load_got lj_trace_exit | sw L, DISPATCH_J(L)(DISPATCH) | sw ra, DISPATCH_J(parent)(DISPATCH) // Store trace number. | sw BASE, L->base | sw TMP1, DISPATCH_J(exitno)(DISPATCH) // Store exit number. | addiu CARG1, DISPATCH, GG_DISP2J | sw r0, DISPATCH_GL(jit_base)(DISPATCH) | call_intern lj_trace_exit // (jit_State *J, ExitState *ex) |. addiu CARG2, sp, 16 | // Returns MULTRES (unscaled) or negated error code. | lw TMP1, L->cframe | li AT, -4 | lw BASE, L->base | and sp, TMP1, AT | lw PC, SAVE_PC // Get SAVE_PC. | b >1 |. sw L, SAVE_L // Set SAVE_L (on-trace resume/yield). |.endif |->vm_exit_interp: |.if JIT | // CRET1 = MULTRES or negated error code, BASE, PC and JGL set. | lw L, SAVE_L | addiu DISPATCH, JGL, -GG_DISP2G-32768 | sw BASE, L->base |1: | bltz CRET1, >9 // Check for error from exit. |. lw LFUNC:RB, FRAME_FUNC(BASE) | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). | sll MULTRES, CRET1, 3 | li TISNIL, LJ_TNIL | li TISNUM, LJ_TISNUM // Setup type comparison constants. | sw MULTRES, SAVE_MULTRES | .FPU mtc1 TMP3, TOBIT | lw TMP1, LFUNC:RB->pc | sw r0, DISPATCH_GL(jit_base)(DISPATCH) | lw KBASE, PC2PROTO(k)(TMP1) | .FPU cvt.d.s TOBIT, TOBIT | // Modified copy of ins_next which handles function header dispatch, too. | lw INS, 0(PC) | addiu PC, PC, 4 | // Assumes TISNIL == ~LJ_VMST_INTERP == -1 | sw TISNIL, DISPATCH_GL(vmstate)(DISPATCH) | decode_OP4a TMP1, INS | decode_OP4b TMP1 | sltiu TMP2, TMP1, BC_FUNCF*4 | addu TMP0, DISPATCH, TMP1 | decode_RD8a RD, INS | lw AT, 0(TMP0) | decode_RA8a RA, INS | beqz TMP2, >2 |. decode_RA8b RA | jr AT |. decode_RD8b RD |2: | sltiu TMP2, TMP1, (BC_FUNCC+2)*4 // Fast function? | bnez TMP2, >3 |. lw TMP1, FRAME_PC(BASE) | // Check frame below fast function. | andi TMP0, TMP1, FRAME_TYPE | bnez TMP0, >3 // Trace stitching continuation? |. nop | // Otherwise set KBASE for Lua function below fast function. | lw TMP2, -4(TMP1) | decode_RA8a TMP0, TMP2 | decode_RA8b TMP0 | subu TMP1, BASE, TMP0 | lw LFUNC:TMP2, -8+FRAME_FUNC(TMP1) | lw TMP1, LFUNC:TMP2->pc | lw KBASE, PC2PROTO(k)(TMP1) |3: | addiu RC, MULTRES, -8 | jr AT |. addu RA, RA, BASE | |9: // Rethrow error from the right C frame. | load_got lj_err_trace | sub CARG2, r0, CRET1 | call_intern lj_err_trace // (lua_State *L, int errcode) |. move CARG1, L |.endif | |//----------------------------------------------------------------------- |//-- Math helper functions ---------------------------------------------- |//----------------------------------------------------------------------- | |// Hard-float round to integer. |// Modifies AT, TMP0, FRET1, FRET2, f4. Keeps all others incl. FARG1. |.macro vm_round_hf, func | lui TMP0, 0x4330 // Hiword of 2^52 (double). | mtc1 r0, f4 | mtc1 TMP0, f5 | abs.d FRET2, FARG1 // |x| | mfc1 AT, f13 | c.olt.d 0, FRET2, f4 | add.d FRET1, FRET2, f4 // (|x| + 2^52) - 2^52 | bc1f 0, >1 // Truncate only if |x| < 2^52. |. sub.d FRET1, FRET1, f4 | slt AT, AT, r0 |.if "func" == "ceil" | lui TMP0, 0xbff0 // Hiword of -1 (double). Preserves -0. |.else | lui TMP0, 0x3ff0 // Hiword of +1 (double). |.endif |.if "func" == "trunc" | mtc1 TMP0, f5 | c.olt.d 0, FRET2, FRET1 // |x| < result? | sub.d FRET2, FRET1, f4 | movt.d FRET1, FRET2, 0 // If yes, subtract +1. | neg.d FRET2, FRET1 | jr ra |. movn.d FRET1, FRET2, AT // Merge sign bit back in. |.else | neg.d FRET2, FRET1 | mtc1 TMP0, f5 | movn.d FRET1, FRET2, AT // Merge sign bit back in. |.if "func" == "ceil" | c.olt.d 0, FRET1, FARG1 // x > result? |.else | c.olt.d 0, FARG1, FRET1 // x < result? |.endif | sub.d FRET2, FRET1, f4 // If yes, subtract +-1. | jr ra |. movt.d FRET1, FRET2, 0 |.endif |1: | jr ra |. mov.d FRET1, FARG1 |.endmacro | |.macro vm_round, func |.if FPU | vm_round_hf, func |.endif |.endmacro | |->vm_floor: | vm_round floor |->vm_ceil: | vm_round ceil |->vm_trunc: |.if JIT | vm_round trunc |.endif | |// Soft-float integer to number conversion. |.macro sfi2d, AHI, ALO |.if not FPU | beqz ALO, >9 // Handle zero first. |. sra TMP0, ALO, 31 | xor TMP1, ALO, TMP0 | subu TMP1, TMP1, TMP0 // Absolute value in TMP1. | clz AHI, TMP1 | andi TMP0, TMP0, 0x800 // Mask sign bit. | li AT, 0x3ff+31-1 | sllv TMP1, TMP1, AHI // Align mantissa left with leading 1. | subu AHI, AT, AHI // Exponent - 1 in AHI. | sll ALO, TMP1, 21 | or AHI, AHI, TMP0 // Sign | Exponent. | srl TMP1, TMP1, 11 | sll AHI, AHI, 20 // Align left. | jr ra |. addu AHI, AHI, TMP1 // Add mantissa, increment exponent. |9: | jr ra |. li AHI, 0 |.endif |.endmacro | |// Input SFARG1LO. Output: SFARG1*. Temporaries: AT, TMP0, TMP1. |->vm_sfi2d_1: | sfi2d SFARG1HI, SFARG1LO | |// Input SFARG2LO. Output: SFARG2*. Temporaries: AT, TMP0, TMP1. |->vm_sfi2d_2: | sfi2d SFARG2HI, SFARG2LO | |// Soft-float comparison. Equivalent to c.eq.d. |// Input: SFARG*. Output: CRET1. Temporaries: AT, TMP0, TMP1. |->vm_sfcmpeq: |.if not FPU | sll AT, SFARG1HI, 1 | sll TMP0, SFARG2HI, 1 | or CRET1, SFARG1LO, SFARG2LO | or TMP1, AT, TMP0 | or TMP1, TMP1, CRET1 | beqz TMP1, >8 // Both args +-0: return 1. |. sltu CRET1, r0, SFARG1LO | lui TMP1, 0xffe0 | addu AT, AT, CRET1 | sltu CRET1, r0, SFARG2LO | sltu AT, TMP1, AT | addu TMP0, TMP0, CRET1 | sltu TMP0, TMP1, TMP0 | or TMP1, AT, TMP0 | bnez TMP1, >9 // Either arg is NaN: return 0; |. xor TMP0, SFARG1HI, SFARG2HI | xor TMP1, SFARG1LO, SFARG2LO | or AT, TMP0, TMP1 | jr ra |. sltiu CRET1, AT, 1 // Same values: return 1. |8: | jr ra |. li CRET1, 1 |9: | jr ra |. li CRET1, 0 |.endif | |// Soft-float comparison. Equivalent to c.ult.d and c.olt.d. |// Input: SFARG*. Output: CRET1. Temporaries: AT, TMP0, TMP1, CRET2. |->vm_sfcmpult: |.if not FPU | b >1 |. li CRET2, 1 |.endif | |->vm_sfcmpolt: |.if not FPU | li CRET2, 0 |1: | sll AT, SFARG1HI, 1 | sll TMP0, SFARG2HI, 1 | or CRET1, SFARG1LO, SFARG2LO | or TMP1, AT, TMP0 | or TMP1, TMP1, CRET1 | beqz TMP1, >8 // Both args +-0: return 0. |. sltu CRET1, r0, SFARG1LO | lui TMP1, 0xffe0 | addu AT, AT, CRET1 | sltu CRET1, r0, SFARG2LO | sltu AT, TMP1, AT | addu TMP0, TMP0, CRET1 | sltu TMP0, TMP1, TMP0 | or TMP1, AT, TMP0 | bnez TMP1, >9 // Either arg is NaN: return 0 or 1; |. and AT, SFARG1HI, SFARG2HI | bltz AT, >5 // Both args negative? |. nop | beq SFARG1HI, SFARG2HI, >8 |. sltu CRET1, SFARG1LO, SFARG2LO | jr ra |. slt CRET1, SFARG1HI, SFARG2HI |5: // Swap conditions if both operands are negative. | beq SFARG1HI, SFARG2HI, >8 |. sltu CRET1, SFARG2LO, SFARG1LO | jr ra |. slt CRET1, SFARG2HI, SFARG1HI |8: | jr ra |. nop |9: | jr ra |. move CRET1, CRET2 |.endif | |->vm_sfcmpogt: |.if not FPU | sll AT, SFARG2HI, 1 | sll TMP0, SFARG1HI, 1 | or CRET1, SFARG2LO, SFARG1LO | or TMP1, AT, TMP0 | or TMP1, TMP1, CRET1 | beqz TMP1, >8 // Both args +-0: return 0. |. sltu CRET1, r0, SFARG2LO | lui TMP1, 0xffe0 | addu AT, AT, CRET1 | sltu CRET1, r0, SFARG1LO | sltu AT, TMP1, AT | addu TMP0, TMP0, CRET1 | sltu TMP0, TMP1, TMP0 | or TMP1, AT, TMP0 | bnez TMP1, >9 // Either arg is NaN: return 0 or 1; |. and AT, SFARG2HI, SFARG1HI | bltz AT, >5 // Both args negative? |. nop | beq SFARG2HI, SFARG1HI, >8 |. sltu CRET1, SFARG2LO, SFARG1LO | jr ra |. slt CRET1, SFARG2HI, SFARG1HI |5: // Swap conditions if both operands are negative. | beq SFARG2HI, SFARG1HI, >8 |. sltu CRET1, SFARG1LO, SFARG2LO | jr ra |. slt CRET1, SFARG1HI, SFARG2HI |8: | jr ra |. nop |9: | jr ra |. li CRET1, 0 |.endif | |// Soft-float comparison. Equivalent to c.ole.d a, b or c.ole.d b, a. |// Input: SFARG*, TMP3. Output: CRET1. Temporaries: AT, TMP0, TMP1. |->vm_sfcmpolex: |.if not FPU | sll AT, SFARG1HI, 1 | sll TMP0, SFARG2HI, 1 | or CRET1, SFARG1LO, SFARG2LO | or TMP1, AT, TMP0 | or TMP1, TMP1, CRET1 | beqz TMP1, >8 // Both args +-0: return 1. |. sltu CRET1, r0, SFARG1LO | lui TMP1, 0xffe0 | addu AT, AT, CRET1 | sltu CRET1, r0, SFARG2LO | sltu AT, TMP1, AT | addu TMP0, TMP0, CRET1 | sltu TMP0, TMP1, TMP0 | or TMP1, AT, TMP0 | bnez TMP1, >9 // Either arg is NaN: return 0; |. and AT, SFARG1HI, SFARG2HI | xor AT, AT, TMP3 | bltz AT, >5 // Both args negative? |. nop | beq SFARG1HI, SFARG2HI, >6 |. sltu CRET1, SFARG2LO, SFARG1LO | jr ra |. slt CRET1, SFARG2HI, SFARG1HI |5: // Swap conditions if both operands are negative. | beq SFARG1HI, SFARG2HI, >6 |. sltu CRET1, SFARG1LO, SFARG2LO | slt CRET1, SFARG1HI, SFARG2HI |6: | jr ra |. nop |8: | jr ra |. li CRET1, 1 |9: | jr ra |. li CRET1, 0 |.endif | |.macro sfmin_max, name, fpcall |->vm_sf .. name: |.if JIT and not FPU | move TMP2, ra | bal ->fpcall |. nop | move TMP0, CRET1 | move SFRETHI, SFARG1HI | move SFRETLO, SFARG1LO | move ra, TMP2 | movz SFRETHI, SFARG2HI, TMP0 | jr ra |. movz SFRETLO, SFARG2LO, TMP0 |.endif |.endmacro | | sfmin_max min, vm_sfcmpolt | sfmin_max max, vm_sfcmpogt | |//----------------------------------------------------------------------- |//-- Miscellaneous functions -------------------------------------------- |//----------------------------------------------------------------------- | |.define NEXT_TAB, TAB:CARG1 |.define NEXT_IDX, CARG2 |.define NEXT_ASIZE, CARG3 |.define NEXT_NIL, CARG4 |.define NEXT_TMP0, r12 |.define NEXT_TMP1, r13 |.define NEXT_TMP2, r14 |.define NEXT_RES_VK, CRET1 |.define NEXT_RES_IDX, CRET2 |.define NEXT_RES_PTR, sp |.define NEXT_RES_VAL_I, 0(sp) |.define NEXT_RES_VAL_IT, 4(sp) |.define NEXT_RES_KEY_I, 8(sp) |.define NEXT_RES_KEY_IT, 12(sp) | |// TValue *lj_vm_next(GCtab *t, uint32_t idx) |// Next idx returned in CRET2. |->vm_next: |.if JIT and ENDIAN_LE | lw NEXT_ASIZE, NEXT_TAB->asize | lw NEXT_TMP0, NEXT_TAB->array | li NEXT_NIL, LJ_TNIL |1: // Traverse array part. | sltu AT, NEXT_IDX, NEXT_ASIZE | sll NEXT_TMP1, NEXT_IDX, 3 | beqz AT, >5 |. addu NEXT_TMP1, NEXT_TMP0, NEXT_TMP1 | lw NEXT_TMP2, 4(NEXT_TMP1) | sw NEXT_IDX, NEXT_RES_KEY_I | beq NEXT_TMP2, NEXT_NIL, <1 |. addiu NEXT_IDX, NEXT_IDX, 1 | lw NEXT_TMP0, 0(NEXT_TMP1) | li AT, LJ_TISNUM | sw NEXT_TMP2, NEXT_RES_VAL_IT | sw AT, NEXT_RES_KEY_IT | sw NEXT_TMP0, NEXT_RES_VAL_I | move NEXT_RES_VK, NEXT_RES_PTR | jr ra |. move NEXT_RES_IDX, NEXT_IDX | |5: // Traverse hash part. | subu NEXT_RES_IDX, NEXT_IDX, NEXT_ASIZE | lw NODE:NEXT_RES_VK, NEXT_TAB->node | sll NEXT_TMP2, NEXT_RES_IDX, 5 | lw NEXT_TMP0, NEXT_TAB->hmask | sll AT, NEXT_RES_IDX, 3 | subu AT, NEXT_TMP2, AT | addu NODE:NEXT_RES_VK, NODE:NEXT_RES_VK, AT |6: | sltu AT, NEXT_TMP0, NEXT_RES_IDX | bnez AT, >8 |. nop | lw NEXT_TMP2, NODE:NEXT_RES_VK->val.it | bne NEXT_TMP2, NEXT_NIL, >9 |. addiu NEXT_RES_IDX, NEXT_RES_IDX, 1 | // Skip holes in hash part. | b <6 |. addiu NODE:NEXT_RES_VK, NODE:NEXT_RES_VK, sizeof(Node) | |8: // End of iteration. Set the key to nil (not the value). | sw NEXT_NIL, NEXT_RES_KEY_IT | move NEXT_RES_VK, NEXT_RES_PTR |9: | jr ra |. addu NEXT_RES_IDX, NEXT_RES_IDX, NEXT_ASIZE |.endif | |//----------------------------------------------------------------------- |//-- FFI helper functions ----------------------------------------------- |//----------------------------------------------------------------------- | |// Handler for callback functions. Callback slot number in r1, g in r2. |->vm_ffi_callback: |.if FFI |.type CTSTATE, CTState, PC | saveregs | lw CTSTATE, GL:r2->ctype_state | addiu DISPATCH, r2, GG_G2DISP | load_got lj_ccallback_enter | sw r1, CTSTATE->cb.slot | sw CARG1, CTSTATE->cb.gpr[0] | sw CARG2, CTSTATE->cb.gpr[1] | .FPU sdc1 FARG1, CTSTATE->cb.fpr[0] | sw CARG3, CTSTATE->cb.gpr[2] | sw CARG4, CTSTATE->cb.gpr[3] | .FPU sdc1 FARG2, CTSTATE->cb.fpr[1] | addiu TMP0, sp, CFRAME_SPACE+16 | sw TMP0, CTSTATE->cb.stack | sw r0, SAVE_PC // Any value outside of bytecode is ok. | move CARG2, sp | call_intern lj_ccallback_enter // (CTState *cts, void *cf) |. move CARG1, CTSTATE | // Returns lua_State *. | lw BASE, L:CRET1->base | lw RC, L:CRET1->top | li TISNUM, LJ_TISNUM // Setup type comparison constants. | move L, CRET1 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). | lw LFUNC:RB, FRAME_FUNC(BASE) | .FPU mtc1 TMP3, TOBIT | li_vmstate INTERP | li TISNIL, LJ_TNIL | subu RC, RC, BASE | st_vmstate | .FPU cvt.d.s TOBIT, TOBIT | ins_callt |.endif | |->cont_ffi_callback: // Return from FFI callback. |.if FFI | load_got lj_ccallback_leave | lw CTSTATE, DISPATCH_GL(ctype_state)(DISPATCH) | sw BASE, L->base | sw RB, L->top | sw L, CTSTATE->L | move CARG2, RA | call_intern lj_ccallback_leave // (CTState *cts, TValue *o) |. move CARG1, CTSTATE | .FPU ldc1 FRET1, CTSTATE->cb.fpr[0] | lw CRET1, CTSTATE->cb.gpr[0] | .FPU ldc1 FRET2, CTSTATE->cb.fpr[1] | b ->vm_leave_unw |. lw CRET2, CTSTATE->cb.gpr[1] |.endif | |->vm_ffi_call: // Call C function via FFI. | // Caveat: needs special frame unwinding, see below. |.if FFI | .type CCSTATE, CCallState, CARG1 | lw TMP1, CCSTATE->spadj | lbu CARG2, CCSTATE->nsp | move TMP2, sp | subu sp, sp, TMP1 | sw ra, -4(TMP2) | sll CARG2, CARG2, 2 | sw r16, -8(TMP2) | sw CCSTATE, -12(TMP2) | move r16, TMP2 | addiu TMP1, CCSTATE, offsetof(CCallState, stack) | addiu TMP2, sp, 16 | beqz CARG2, >2 |. addu TMP3, TMP1, CARG2 |1: | lw TMP0, 0(TMP1) | addiu TMP1, TMP1, 4 | sltu AT, TMP1, TMP3 | sw TMP0, 0(TMP2) | bnez AT, <1 |. addiu TMP2, TMP2, 4 |2: | lw CFUNCADDR, CCSTATE->func | lw CARG2, CCSTATE->gpr[1] | lw CARG3, CCSTATE->gpr[2] | lw CARG4, CCSTATE->gpr[3] | .FPU ldc1 FARG1, CCSTATE->fpr[0] | .FPU ldc1 FARG2, CCSTATE->fpr[1] | jalr CFUNCADDR |. lw CARG1, CCSTATE->gpr[0] // Do this last, since CCSTATE is CARG1. | lw CCSTATE:TMP1, -12(r16) | lw TMP2, -8(r16) | lw ra, -4(r16) | sw CRET1, CCSTATE:TMP1->gpr[0] | sw CRET2, CCSTATE:TMP1->gpr[1] |.if FPU | sdc1 FRET1, CCSTATE:TMP1->fpr[0] | sdc1 FRET2, CCSTATE:TMP1->fpr[1] |.else | sw CARG1, CCSTATE:TMP1->gpr[2] // Soft-float: complex double .im part. | sw CARG2, CCSTATE:TMP1->gpr[3] |.endif | move sp, r16 | jr ra |. move r16, TMP2 |.endif |// Note: vm_ffi_call must be the last function in this object file! | |//----------------------------------------------------------------------- } /* Generate the code for a single instruction. */ static void build_ins(BuildCtx *ctx, BCOp op, int defop) { int vk = 0; |=>defop: switch (op) { /* -- Comparison ops ---------------------------------------------------- */ /* Remember: all ops branch for a true comparison, fall through otherwise. */ case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT: | // RA = src1*8, RD = src2*8, JMP with RD = target |.macro bc_comp, FRA, FRD, RAHI, RALO, RDHI, RDLO, movop, fmovop, fcomp, sfcomp | addu RA, BASE, RA | addu RD, BASE, RD | lw RAHI, HI(RA) | lw RDHI, HI(RD) | lhu TMP2, OFS_RD(PC) | addiu PC, PC, 4 | bne RAHI, TISNUM, >2 |. lw RALO, LO(RA) | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | lw RDLO, LO(RD) | bne RDHI, TISNUM, >5 |. decode_RD4b TMP2 | slt AT, SFARG1LO, SFARG2LO | addu TMP2, TMP2, TMP3 | movop TMP2, r0, AT |1: | addu PC, PC, TMP2 | ins_next | |2: // RA is not an integer. | sltiu AT, RAHI, LJ_TISNUM | beqz AT, ->vmeta_comp |. lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | sltiu AT, RDHI, LJ_TISNUM |.if FPU | ldc1 FRA, 0(RA) | ldc1 FRD, 0(RD) |.else | lw RDLO, LO(RD) |.endif | beqz AT, >4 |. decode_RD4b TMP2 |3: // RA and RD are both numbers. |.if FPU | fcomp f20, f22 | addu TMP2, TMP2, TMP3 | b <1 |. fmovop TMP2, r0 |.else | bal sfcomp |. addu TMP2, TMP2, TMP3 | b <1 |. movop TMP2, r0, CRET1 |.endif | |4: // RA is a number, RD is not a number. | bne RDHI, TISNUM, ->vmeta_comp | // RA is a number, RD is an integer. Convert RD to a number. |.if FPU |. lwc1 FRD, LO(RD) | b <3 |. cvt.d.w FRD, FRD |.else |. nop |.if "RDHI" == "SFARG1HI" | bal ->vm_sfi2d_1 |.else | bal ->vm_sfi2d_2 |.endif |. nop | b <3 |. nop |.endif | |5: // RA is an integer, RD is not an integer | sltiu AT, RDHI, LJ_TISNUM | beqz AT, ->vmeta_comp | // RA is an integer, RD is a number. Convert RA to a number. |.if FPU |. mtc1 RALO, FRA | ldc1 FRD, 0(RD) | b <3 | cvt.d.w FRA, FRA |.else |. nop |.if "RAHI" == "SFARG1HI" | bal ->vm_sfi2d_1 |.else | bal ->vm_sfi2d_2 |.endif |. nop | b <3 |. nop |.endif |.endmacro | if (op == BC_ISLT) { | bc_comp f20, f22, SFARG1HI, SFARG1LO, SFARG2HI, SFARG2LO, movz, movf, c.olt.d, ->vm_sfcmpolt } else if (op == BC_ISGE) { | bc_comp f20, f22, SFARG1HI, SFARG1LO, SFARG2HI, SFARG2LO, movn, movt, c.olt.d, ->vm_sfcmpolt } else if (op == BC_ISLE) { | bc_comp f22, f20, SFARG2HI, SFARG2LO, SFARG1HI, SFARG1LO, movn, movt, c.ult.d, ->vm_sfcmpult } else { | bc_comp f22, f20, SFARG2HI, SFARG2LO, SFARG1HI, SFARG1LO, movz, movf, c.ult.d, ->vm_sfcmpult } break; case BC_ISEQV: case BC_ISNEV: vk = op == BC_ISEQV; | // RA = src1*8, RD = src2*8, JMP with RD = target | addu RA, BASE, RA | addiu PC, PC, 4 | addu RD, BASE, RD | lw SFARG1HI, HI(RA) | lhu TMP2, -4+OFS_RD(PC) | lw SFARG2HI, HI(RD) | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | sltu AT, TISNUM, SFARG1HI | sltu TMP0, TISNUM, SFARG2HI | or AT, AT, TMP0 if (vk) { | beqz AT, ->BC_ISEQN_Z } else { | beqz AT, ->BC_ISNEN_Z } |. decode_RD4b TMP2 | // Either or both types are not numbers. | lw SFARG1LO, LO(RA) | lw SFARG2LO, LO(RD) | addu TMP2, TMP2, TMP3 |.if FFI | li TMP3, LJ_TCDATA | beq SFARG1HI, TMP3, ->vmeta_equal_cd |.endif |. sltiu AT, SFARG1HI, LJ_TISPRI // Not a primitive? |.if FFI | beq SFARG2HI, TMP3, ->vmeta_equal_cd |.endif |. xor TMP3, SFARG1LO, SFARG2LO // Same tv? | xor SFARG2HI, SFARG2HI, SFARG1HI // Same type? | sltiu TMP0, SFARG1HI, LJ_TISTABUD+1 // Table or userdata? | movz TMP3, r0, AT // Ignore tv if primitive. | movn TMP0, r0, SFARG2HI // Tab/ud and same type? | or AT, SFARG2HI, TMP3 // Same type && (pri||same tv). | movz TMP0, r0, AT | beqz TMP0, >1 // Done if not tab/ud or not same type or same tv. if (vk) { |. movn TMP2, r0, AT } else { |. movz TMP2, r0, AT } | // Different tables or userdatas. Need to check __eq metamethod. | // Field metatable must be at same offset for GCtab and GCudata! | lw TAB:TMP1, TAB:SFARG1LO->metatable | beqz TAB:TMP1, >1 // No metatable? |. nop | lbu TMP1, TAB:TMP1->nomm | andi TMP1, TMP1, 1<<MM_eq | bnez TMP1, >1 // Or 'no __eq' flag set? |. nop | b ->vmeta_equal // Handle __eq metamethod. |. li TMP0, 1-vk // ne = 0 or 1. |1: | addu PC, PC, TMP2 | ins_next break; case BC_ISEQS: case BC_ISNES: vk = op == BC_ISEQS; | // RA = src*8, RD = str_const*8 (~), JMP with RD = target | addu RA, BASE, RA | addiu PC, PC, 4 | lw TMP0, HI(RA) | srl RD, RD, 1 | lw STR:TMP3, LO(RA) | subu RD, KBASE, RD | lhu TMP2, -4+OFS_RD(PC) |.if FFI | li AT, LJ_TCDATA | beq TMP0, AT, ->vmeta_equal_cd |.endif |. lw STR:TMP1, -4(RD) // KBASE-4-str_const*4 | addiu TMP0, TMP0, -LJ_TSTR | decode_RD4b TMP2 | xor TMP1, STR:TMP1, STR:TMP3 | or TMP0, TMP0, TMP1 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP2, TMP2, TMP3 if (vk) { | movn TMP2, r0, TMP0 } else { | movz TMP2, r0, TMP0 } | addu PC, PC, TMP2 | ins_next break; case BC_ISEQN: case BC_ISNEN: vk = op == BC_ISEQN; | // RA = src*8, RD = num_const*8, JMP with RD = target | addu RA, BASE, RA | addu RD, KBASE, RD | lw SFARG1HI, HI(RA) | lw SFARG2HI, HI(RD) | lhu TMP2, OFS_RD(PC) | addiu PC, PC, 4 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | decode_RD4b TMP2 if (vk) { |->BC_ISEQN_Z: } else { |->BC_ISNEN_Z: } | bne SFARG1HI, TISNUM, >3 |. lw SFARG1LO, LO(RA) | lw SFARG2LO, LO(RD) | addu TMP2, TMP2, TMP3 | bne SFARG2HI, TISNUM, >6 |. xor AT, SFARG1LO, SFARG2LO if (vk) { | movn TMP2, r0, AT |1: | addu PC, PC, TMP2 |2: } else { | movz TMP2, r0, AT |1: |2: | addu PC, PC, TMP2 } | ins_next | |3: // RA is not an integer. | sltiu AT, SFARG1HI, LJ_TISNUM |.if FFI | beqz AT, >8 |.else | beqz AT, <2 |.endif |. addu TMP2, TMP2, TMP3 | sltiu AT, SFARG2HI, LJ_TISNUM |.if FPU | ldc1 f20, 0(RA) | ldc1 f22, 0(RD) |.endif | beqz AT, >5 |. lw SFARG2LO, LO(RD) |4: // RA and RD are both numbers. |.if FPU | c.eq.d f20, f22 | b <1 if (vk) { |. movf TMP2, r0 } else { |. movt TMP2, r0 } |.else | bal ->vm_sfcmpeq |. nop | b <1 if (vk) { |. movz TMP2, r0, CRET1 } else { |. movn TMP2, r0, CRET1 } |.endif | |5: // RA is a number, RD is not a number. |.if FFI | bne SFARG2HI, TISNUM, >9 |.else | bne SFARG2HI, TISNUM, <2 |.endif | // RA is a number, RD is an integer. Convert RD to a number. |.if FPU |. lwc1 f22, LO(RD) | b <4 |. cvt.d.w f22, f22 |.else |. nop | bal ->vm_sfi2d_2 |. nop | b <4 |. nop |.endif | |6: // RA is an integer, RD is not an integer | sltiu AT, SFARG2HI, LJ_TISNUM |.if FFI | beqz AT, >9 |.else | beqz AT, <2 |.endif | // RA is an integer, RD is a number. Convert RA to a number. |.if FPU |. mtc1 SFARG1LO, f20 | ldc1 f22, 0(RD) | b <4 | cvt.d.w f20, f20 |.else |. nop | bal ->vm_sfi2d_1 |. nop | b <4 |. nop |.endif | |.if FFI |8: | li AT, LJ_TCDATA | bne SFARG1HI, AT, <2 |. nop | b ->vmeta_equal_cd |. nop |9: | li AT, LJ_TCDATA | bne SFARG2HI, AT, <2 |. nop | b ->vmeta_equal_cd |. nop |.endif break; case BC_ISEQP: case BC_ISNEP: vk = op == BC_ISEQP; | // RA = src*8, RD = primitive_type*8 (~), JMP with RD = target | addu RA, BASE, RA | srl TMP1, RD, 3 | lw TMP0, HI(RA) | lhu TMP2, OFS_RD(PC) | not TMP1, TMP1 | addiu PC, PC, 4 |.if FFI | li AT, LJ_TCDATA | beq TMP0, AT, ->vmeta_equal_cd |.endif |. xor TMP0, TMP0, TMP1 | decode_RD4b TMP2 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP2, TMP2, TMP3 if (vk) { | movn TMP2, r0, TMP0 } else { | movz TMP2, r0, TMP0 } | addu PC, PC, TMP2 | ins_next break; /* -- Unary test and copy ops ------------------------------------------- */ case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF: | // RA = dst*8 or unused, RD = src*8, JMP with RD = target | addu RD, BASE, RD | lhu TMP2, OFS_RD(PC) | lw TMP0, HI(RD) | addiu PC, PC, 4 if (op == BC_IST || op == BC_ISF) { | sltiu TMP0, TMP0, LJ_TISTRUECOND | decode_RD4b TMP2 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP2, TMP2, TMP3 if (op == BC_IST) { | movz TMP2, r0, TMP0 } else { | movn TMP2, r0, TMP0 } | addu PC, PC, TMP2 } else { | sltiu TMP0, TMP0, LJ_TISTRUECOND | lw SFRETHI, HI(RD) | lw SFRETLO, LO(RD) if (op == BC_ISTC) { | beqz TMP0, >1 } else { | bnez TMP0, >1 } |. addu RA, BASE, RA | decode_RD4b TMP2 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP2, TMP2, TMP3 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | addu PC, PC, TMP2 |1: } | ins_next break; case BC_ISTYPE: | // RA = src*8, RD = -type*8 | addu TMP2, BASE, RA | srl TMP1, RD, 3 | lw TMP0, HI(TMP2) | ins_next1 | addu AT, TMP0, TMP1 | bnez AT, ->vmeta_istype |. ins_next2 break; case BC_ISNUM: | // RA = src*8, RD = -(TISNUM-1)*8 | addu TMP2, BASE, RA | lw TMP0, HI(TMP2) | ins_next1 | sltiu AT, TMP0, LJ_TISNUM | beqz AT, ->vmeta_istype |. ins_next2 break; /* -- Unary ops --------------------------------------------------------- */ case BC_MOV: | // RA = dst*8, RD = src*8 | addu RD, BASE, RD | addu RA, BASE, RA | lw SFRETHI, HI(RD) | lw SFRETLO, LO(RD) | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 break; case BC_NOT: | // RA = dst*8, RD = src*8 | addu RD, BASE, RD | addu RA, BASE, RA | lw TMP0, HI(RD) | li TMP1, LJ_TFALSE | sltiu TMP0, TMP0, LJ_TISTRUECOND | addiu TMP1, TMP0, LJ_TTRUE | ins_next1 | sw TMP1, HI(RA) | ins_next2 break; case BC_UNM: | // RA = dst*8, RD = src*8 | addu RB, BASE, RD | lw SFARG1HI, HI(RB) | addu RA, BASE, RA | bne SFARG1HI, TISNUM, >2 |. lw SFARG1LO, LO(RB) | lui TMP1, 0x8000 | beq SFARG1LO, TMP1, ->vmeta_unm // Meta handler deals with -2^31. |. negu SFARG1LO, SFARG1LO |1: | ins_next1 | sw SFARG1HI, HI(RA) | sw SFARG1LO, LO(RA) | ins_next2 |2: | sltiu AT, SFARG1HI, LJ_TISNUM | beqz AT, ->vmeta_unm |. lui TMP1, 0x8000 | b <1 |. xor SFARG1HI, SFARG1HI, TMP1 break; case BC_LEN: | // RA = dst*8, RD = src*8 | addu CARG2, BASE, RD | addu RA, BASE, RA | lw TMP0, HI(CARG2) | lw CARG1, LO(CARG2) | li AT, LJ_TSTR | bne TMP0, AT, >2 |. li AT, LJ_TTAB | lw CRET1, STR:CARG1->len |1: | ins_next1 | sw TISNUM, HI(RA) | sw CRET1, LO(RA) | ins_next2 |2: | bne TMP0, AT, ->vmeta_len |. nop #if LJ_52 | lw TAB:TMP2, TAB:CARG1->metatable | bnez TAB:TMP2, >9 |. nop |3: #endif |->BC_LEN_Z: | load_got lj_tab_len | call_intern lj_tab_len // (GCtab *t) |. nop | // Returns uint32_t (but less than 2^31). | b <1 |. nop #if LJ_52 |9: | lbu TMP0, TAB:TMP2->nomm | andi TMP0, TMP0, 1<<MM_len | bnez TMP0, <3 // 'no __len' flag set: done. |. nop | b ->vmeta_len |. nop #endif break; /* -- Binary ops -------------------------------------------------------- */ |.macro fpmod, a, b, c | bal ->vm_floor // floor(b/c) |. div.d FARG1, b, c | mul.d a, FRET1, c | sub.d a, b, a // b - floor(b/c)*c |.endmacro |.macro sfpmod | addiu sp, sp, -16 | | load_got __divdf3 | sw SFARG1HI, HI(sp) | sw SFARG1LO, LO(sp) | sw SFARG2HI, 8+HI(sp) | call_extern |. sw SFARG2LO, 8+LO(sp) | | load_got floor | move SFARG1HI, SFRETHI | call_extern |. move SFARG1LO, SFRETLO | | load_got __muldf3 | move SFARG1HI, SFRETHI | move SFARG1LO, SFRETLO | lw SFARG2HI, 8+HI(sp) | call_extern |. lw SFARG2LO, 8+LO(sp) | | load_got __subdf3 | lw SFARG1HI, HI(sp) | lw SFARG1LO, LO(sp) | move SFARG2HI, SFRETHI | call_extern |. move SFARG2LO, SFRETLO | | addiu sp, sp, 16 |.endmacro |.macro ins_arithpre, label ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); | // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8 ||switch (vk) { ||case 0: | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | // RA = dst*8, RB = src1*8, RC = num_const*8 | addu RB, BASE, RB |.if "label" ~= "none" | b label |.endif |. addu RC, KBASE, RC || break; ||case 1: | decode_RB8a RC, INS | decode_RB8b RC | decode_RDtoRC8 RB, RD | // RA = dst*8, RB = num_const*8, RC = src1*8 | addu RC, BASE, RC |.if "label" ~= "none" | b label |.endif |. addu RB, KBASE, RB || break; ||default: | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | // RA = dst*8, RB = src1*8, RC = src2*8 | addu RB, BASE, RB |.if "label" ~= "none" | b label |.endif |. addu RC, BASE, RC || break; ||} |.endmacro | |.macro ins_arith, intins, fpins, fpcall, label | ins_arithpre none | |.if "label" ~= "none" |label: |.endif | | lw SFARG1HI, HI(RB) | lw SFARG2HI, HI(RC) | |.if "intins" ~= "div" | | // Check for two integers. | lw SFARG1LO, LO(RB) | bne SFARG1HI, TISNUM, >5 |. lw SFARG2LO, LO(RC) | bne SFARG2HI, TISNUM, >5 | |.if "intins" == "addu" |. intins CRET1, SFARG1LO, SFARG2LO | xor TMP1, CRET1, SFARG1LO // ((y^a) & (y^b)) < 0: overflow. | xor TMP2, CRET1, SFARG2LO | and TMP1, TMP1, TMP2 | bltz TMP1, ->vmeta_arith |. addu RA, BASE, RA |.elif "intins" == "subu" |. intins CRET1, SFARG1LO, SFARG2LO | xor TMP1, CRET1, SFARG1LO // ((y^a) & (a^b)) < 0: overflow. | xor TMP2, SFARG1LO, SFARG2LO | and TMP1, TMP1, TMP2 | bltz TMP1, ->vmeta_arith |. addu RA, BASE, RA |.elif "intins" == "mult" |. intins SFARG1LO, SFARG2LO | mflo CRET1 | mfhi TMP2 | sra TMP1, CRET1, 31 | bne TMP1, TMP2, ->vmeta_arith |. addu RA, BASE, RA |.else |. load_got lj_vm_modi | beqz SFARG2LO, ->vmeta_arith |. addu RA, BASE, RA |.if ENDIAN_BE | move CARG1, SFARG1LO |.endif | call_extern |. move CARG2, SFARG2LO |.endif | | ins_next1 | sw TISNUM, HI(RA) | sw CRET1, LO(RA) |3: | ins_next2 | |.elif not FPU | | lw SFARG1LO, LO(RB) | lw SFARG2LO, LO(RC) | |.endif | |5: // Check for two numbers. | .FPU ldc1 f20, 0(RB) | sltiu AT, SFARG1HI, LJ_TISNUM | sltiu TMP0, SFARG2HI, LJ_TISNUM | .FPU ldc1 f22, 0(RC) | and AT, AT, TMP0 | beqz AT, ->vmeta_arith |. addu RA, BASE, RA | |.if FPU | fpins FRET1, f20, f22 |.elif "fpcall" == "sfpmod" | sfpmod |.else | load_got fpcall | call_extern |. nop |.endif | | ins_next1 |.if not FPU | sw SFRETHI, HI(RA) |.endif |.if "intins" ~= "div" | b <3 |.endif |.if FPU |. sdc1 FRET1, 0(RA) |.else |. sw SFRETLO, LO(RA) |.endif |.if "intins" == "div" | ins_next2 |.endif | |.endmacro case BC_ADDVN: case BC_ADDNV: case BC_ADDVV: | ins_arith addu, add.d, __adddf3, none break; case BC_SUBVN: case BC_SUBNV: case BC_SUBVV: | ins_arith subu, sub.d, __subdf3, none break; case BC_MULVN: case BC_MULNV: case BC_MULVV: | ins_arith mult, mul.d, __muldf3, none break; case BC_DIVVN: | ins_arith div, div.d, __divdf3, ->BC_DIVVN_Z break; case BC_DIVNV: case BC_DIVVV: | ins_arithpre ->BC_DIVVN_Z break; case BC_MODVN: | ins_arith modi, fpmod, sfpmod, ->BC_MODVN_Z break; case BC_MODNV: case BC_MODVV: | ins_arithpre ->BC_MODVN_Z break; case BC_POW: | ins_arithpre none | lw SFARG1HI, HI(RB) | lw SFARG2HI, HI(RC) | sltiu AT, SFARG1HI, LJ_TISNUM | sltiu TMP0, SFARG2HI, LJ_TISNUM | and AT, AT, TMP0 | load_got pow | beqz AT, ->vmeta_arith |. addu RA, BASE, RA |.if FPU | ldc1 FARG1, 0(RB) | ldc1 FARG2, 0(RC) |.else | lw SFARG1LO, LO(RB) | lw SFARG2LO, LO(RC) |.endif | call_extern |. nop | ins_next1 |.if FPU | sdc1 FRET1, 0(RA) |.else | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) |.endif | ins_next2 break; case BC_CAT: | // RA = dst*8, RB = src_start*8, RC = src_end*8 | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | subu CARG3, RC, RB | sw BASE, L->base | addu CARG2, BASE, RC | move MULTRES, RB |->BC_CAT_Z: | load_got lj_meta_cat | srl CARG3, CARG3, 3 | sw PC, SAVE_PC | call_intern lj_meta_cat // (lua_State *L, TValue *top, int left) |. move CARG1, L | // Returns NULL (finished) or TValue * (metamethod). | bnez CRET1, ->vmeta_binop |. lw BASE, L->base | addu RB, BASE, MULTRES | lw SFRETHI, HI(RB) | lw SFRETLO, LO(RB) | addu RA, BASE, RA | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 break; /* -- Constant ops ------------------------------------------------------ */ case BC_KSTR: | // RA = dst*8, RD = str_const*8 (~) | srl TMP1, RD, 1 | subu TMP1, KBASE, TMP1 | ins_next1 | lw TMP0, -4(TMP1) // KBASE-4-str_const*4 | addu RA, BASE, RA | li TMP2, LJ_TSTR | sw TMP0, LO(RA) | sw TMP2, HI(RA) | ins_next2 break; case BC_KCDATA: |.if FFI | // RA = dst*8, RD = cdata_const*8 (~) | srl TMP1, RD, 1 | subu TMP1, KBASE, TMP1 | ins_next1 | lw TMP0, -4(TMP1) // KBASE-4-cdata_const*4 | addu RA, BASE, RA | li TMP2, LJ_TCDATA | sw TMP0, LO(RA) | sw TMP2, HI(RA) | ins_next2 |.endif break; case BC_KSHORT: | // RA = dst*8, RD = int16_literal*8 | sra RD, INS, 16 | addu RA, BASE, RA | ins_next1 | sw TISNUM, HI(RA) | sw RD, LO(RA) | ins_next2 break; case BC_KNUM: | // RA = dst*8, RD = num_const*8 | addu RD, KBASE, RD | addu RA, BASE, RA | lw SFRETHI, HI(RD) | lw SFRETLO, LO(RD) | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 break; case BC_KPRI: | // RA = dst*8, RD = primitive_type*8 (~) | srl TMP1, RD, 3 | addu RA, BASE, RA | not TMP0, TMP1 | ins_next1 | sw TMP0, HI(RA) | ins_next2 break; case BC_KNIL: | // RA = base*8, RD = end*8 | addu RA, BASE, RA | sw TISNIL, HI(RA) | addiu RA, RA, 8 | addu RD, BASE, RD |1: | sw TISNIL, HI(RA) | slt AT, RA, RD | bnez AT, <1 |. addiu RA, RA, 8 | ins_next_ break; /* -- Upvalue and function ops ------------------------------------------ */ case BC_UGET: | // RA = dst*8, RD = uvnum*8 | lw LFUNC:RB, FRAME_FUNC(BASE) | srl RD, RD, 1 | addu RD, RD, LFUNC:RB | lw UPVAL:RB, LFUNC:RD->uvptr | ins_next1 | lw TMP1, UPVAL:RB->v | lw SFRETHI, HI(TMP1) | lw SFRETLO, LO(TMP1) | addu RA, BASE, RA | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 break; case BC_USETV: | // RA = uvnum*8, RD = src*8 | lw LFUNC:RB, FRAME_FUNC(BASE) | srl RA, RA, 1 | addu RD, BASE, RD | addu RA, RA, LFUNC:RB | lw UPVAL:RB, LFUNC:RA->uvptr | lw SFRETHI, HI(RD) | lw SFRETLO, LO(RD) | lbu TMP3, UPVAL:RB->marked | lw CARG2, UPVAL:RB->v | andi TMP3, TMP3, LJ_GC_BLACK // isblack(uv) | lbu TMP0, UPVAL:RB->closed | sw SFRETHI, HI(CARG2) | sw SFRETLO, LO(CARG2) | li AT, LJ_GC_BLACK|1 | or TMP3, TMP3, TMP0 | beq TMP3, AT, >2 // Upvalue is closed and black? |. addiu TMP2, SFRETHI, -(LJ_TNUMX+1) |1: | ins_next | |2: // Check if new value is collectable. | sltiu AT, TMP2, LJ_TISGCV - (LJ_TNUMX+1) | beqz AT, <1 // tvisgcv(v) |. nop | lbu TMP3, GCOBJ:SFRETLO->gch.marked | andi TMP3, TMP3, LJ_GC_WHITES // iswhite(v) | beqz TMP3, <1 |. load_got lj_gc_barrieruv | // Crossed a write barrier. Move the barrier forward. | call_intern lj_gc_barrieruv // (global_State *g, TValue *tv) |. addiu CARG1, DISPATCH, GG_DISP2G | b <1 |. nop break; case BC_USETS: | // RA = uvnum*8, RD = str_const*8 (~) | lw LFUNC:RB, FRAME_FUNC(BASE) | srl RA, RA, 1 | srl TMP1, RD, 1 | addu RA, RA, LFUNC:RB | subu TMP1, KBASE, TMP1 | lw UPVAL:RB, LFUNC:RA->uvptr | lw STR:TMP1, -4(TMP1) // KBASE-4-str_const*4 | lbu TMP2, UPVAL:RB->marked | lw CARG2, UPVAL:RB->v | lbu TMP3, STR:TMP1->marked | andi AT, TMP2, LJ_GC_BLACK // isblack(uv) | lbu TMP2, UPVAL:RB->closed | li TMP0, LJ_TSTR | sw STR:TMP1, LO(CARG2) | bnez AT, >2 |. sw TMP0, HI(CARG2) |1: | ins_next | |2: // Check if string is white and ensure upvalue is closed. | beqz TMP2, <1 |. andi AT, TMP3, LJ_GC_WHITES // iswhite(str) | beqz AT, <1 |. load_got lj_gc_barrieruv | // Crossed a write barrier. Move the barrier forward. | call_intern lj_gc_barrieruv // (global_State *g, TValue *tv) |. addiu CARG1, DISPATCH, GG_DISP2G | b <1 |. nop break; case BC_USETN: | // RA = uvnum*8, RD = num_const*8 | lw LFUNC:RB, FRAME_FUNC(BASE) | srl RA, RA, 1 | addu RD, KBASE, RD | addu RA, RA, LFUNC:RB | lw UPVAL:RB, LFUNC:RA->uvptr | lw SFRETHI, HI(RD) | lw SFRETLO, LO(RD) | lw TMP1, UPVAL:RB->v | ins_next1 | sw SFRETHI, HI(TMP1) | sw SFRETLO, LO(TMP1) | ins_next2 break; case BC_USETP: | // RA = uvnum*8, RD = primitive_type*8 (~) | lw LFUNC:RB, FRAME_FUNC(BASE) | srl RA, RA, 1 | srl TMP0, RD, 3 | addu RA, RA, LFUNC:RB | not TMP0, TMP0 | lw UPVAL:RB, LFUNC:RA->uvptr | ins_next1 | lw TMP1, UPVAL:RB->v | sw TMP0, HI(TMP1) | ins_next2 break; case BC_UCLO: | // RA = level*8, RD = target | lw TMP2, L->openupval | branch_RD // Do this first since RD is not saved. | load_got lj_func_closeuv | sw BASE, L->base | beqz TMP2, >1 |. move CARG1, L | call_intern lj_func_closeuv // (lua_State *L, TValue *level) |. addu CARG2, BASE, RA | lw BASE, L->base |1: | ins_next break; case BC_FNEW: | // RA = dst*8, RD = proto_const*8 (~) (holding function prototype) | srl TMP1, RD, 1 | load_got lj_func_newL_gc | subu TMP1, KBASE, TMP1 | lw CARG3, FRAME_FUNC(BASE) | lw CARG2, -4(TMP1) // KBASE-4-tab_const*4 | sw BASE, L->base | sw PC, SAVE_PC | // (lua_State *L, GCproto *pt, GCfuncL *parent) | call_intern lj_func_newL_gc |. move CARG1, L | // Returns GCfuncL *. | lw BASE, L->base | li TMP0, LJ_TFUNC | ins_next1 | addu RA, BASE, RA | sw LFUNC:CRET1, LO(RA) | sw TMP0, HI(RA) | ins_next2 break; /* -- Table ops --------------------------------------------------------- */ case BC_TNEW: case BC_TDUP: | // RA = dst*8, RD = (hbits|asize)*8 | tab_const*8 (~) | lw TMP0, DISPATCH_GL(gc.total)(DISPATCH) | lw TMP1, DISPATCH_GL(gc.threshold)(DISPATCH) | sw BASE, L->base | sw PC, SAVE_PC | sltu AT, TMP0, TMP1 | beqz AT, >5 |1: if (op == BC_TNEW) { | load_got lj_tab_new | srl CARG2, RD, 3 | andi CARG2, CARG2, 0x7ff | li TMP0, 0x801 | addiu AT, CARG2, -0x7ff | srl CARG3, RD, 14 | movz CARG2, TMP0, AT | // (lua_State *L, int32_t asize, uint32_t hbits) | call_intern lj_tab_new |. move CARG1, L | // Returns Table *. } else { | load_got lj_tab_dup | srl TMP1, RD, 1 | subu TMP1, KBASE, TMP1 | move CARG1, L | call_intern lj_tab_dup // (lua_State *L, Table *kt) |. lw CARG2, -4(TMP1) // KBASE-4-str_const*4 | // Returns Table *. } | lw BASE, L->base | ins_next1 | addu RA, BASE, RA | li TMP0, LJ_TTAB | sw TAB:CRET1, LO(RA) | sw TMP0, HI(RA) | ins_next2 |5: | load_got lj_gc_step_fixtop | move MULTRES, RD | call_intern lj_gc_step_fixtop // (lua_State *L) |. move CARG1, L | b <1 |. move RD, MULTRES break; case BC_GGET: | // RA = dst*8, RD = str_const*8 (~) case BC_GSET: | // RA = src*8, RD = str_const*8 (~) | lw LFUNC:TMP2, FRAME_FUNC(BASE) | srl TMP1, RD, 1 | subu TMP1, KBASE, TMP1 | lw TAB:RB, LFUNC:TMP2->env | lw STR:RC, -4(TMP1) // KBASE-4-str_const*4 if (op == BC_GGET) { | b ->BC_TGETS_Z } else { | b ->BC_TSETS_Z } |. addu RA, BASE, RA break; case BC_TGETV: | // RA = dst*8, RB = table*8, RC = key*8 | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | addu CARG2, BASE, RB | addu CARG3, BASE, RC | lw TMP1, HI(CARG2) | lw TMP2, HI(CARG3) | lw TAB:RB, LO(CARG2) | li AT, LJ_TTAB | bne TMP1, AT, ->vmeta_tgetv |. addu RA, BASE, RA | bne TMP2, TISNUM, >5 |. lw RC, LO(CARG3) | lw TMP0, TAB:RB->asize | lw TMP1, TAB:RB->array | sltu AT, RC, TMP0 | sll TMP2, RC, 3 | beqz AT, ->vmeta_tgetv // Integer key and in array part? |. addu TMP2, TMP1, TMP2 | lw SFRETHI, HI(TMP2) | beq SFRETHI, TISNIL, >2 |. lw SFRETLO, LO(TMP2) |1: | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 | |2: // Check for __index if table value is nil. | lw TAB:TMP2, TAB:RB->metatable | beqz TAB:TMP2, <1 // No metatable: done. |. nop | lbu TMP0, TAB:TMP2->nomm | andi TMP0, TMP0, 1<<MM_index | bnez TMP0, <1 // 'no __index' flag set: done. |. nop | b ->vmeta_tgetv |. nop | |5: | li AT, LJ_TSTR | bne TMP2, AT, ->vmeta_tgetv |. nop | b ->BC_TGETS_Z // String key? |. nop break; case BC_TGETS: | // RA = dst*8, RB = table*8, RC = str_const*4 (~) | decode_RB8a RB, INS | decode_RB8b RB | addu CARG2, BASE, RB | decode_RC4a RC, INS | lw TMP0, HI(CARG2) | decode_RC4b RC | li AT, LJ_TTAB | lw TAB:RB, LO(CARG2) | subu CARG3, KBASE, RC | lw STR:RC, -4(CARG3) // KBASE-4-str_const*4 | bne TMP0, AT, ->vmeta_tgets1 |. addu RA, BASE, RA |->BC_TGETS_Z: | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = dst*8 | lw TMP0, TAB:RB->hmask | lw TMP1, STR:RC->sid | lw NODE:TMP2, TAB:RB->node | and TMP1, TMP1, TMP0 // idx = str->sid & tab->hmask | sll TMP0, TMP1, 5 | sll TMP1, TMP1, 3 | subu TMP1, TMP0, TMP1 | addu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8) |1: | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2) | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) | lw NODE:TMP1, NODE:TMP2->next | lw SFRETHI, offsetof(Node, val)+HI(NODE:TMP2) | addiu CARG1, CARG1, -LJ_TSTR | xor TMP0, TMP0, STR:RC | or AT, CARG1, TMP0 | bnez AT, >4 |. lw TAB:TMP3, TAB:RB->metatable | beq SFRETHI, TISNIL, >5 // Key found, but nil value? |. lw SFRETLO, offsetof(Node, val)+LO(NODE:TMP2) |3: | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 | |4: // Follow hash chain. | bnez NODE:TMP1, <1 |. move NODE:TMP2, NODE:TMP1 | // End of hash chain: key not found, nil result. | |5: // Check for __index if table value is nil. | beqz TAB:TMP3, <3 // No metatable: done. |. li SFRETHI, LJ_TNIL | lbu TMP0, TAB:TMP3->nomm | andi TMP0, TMP0, 1<<MM_index | bnez TMP0, <3 // 'no __index' flag set: done. |. nop | b ->vmeta_tgets |. nop break; case BC_TGETB: | // RA = dst*8, RB = table*8, RC = index*8 | decode_RB8a RB, INS | decode_RB8b RB | addu CARG2, BASE, RB | decode_RDtoRC8 RC, RD | lw CARG1, HI(CARG2) | li AT, LJ_TTAB | lw TAB:RB, LO(CARG2) | addu RA, BASE, RA | bne CARG1, AT, ->vmeta_tgetb |. srl TMP0, RC, 3 | lw TMP1, TAB:RB->asize | lw TMP2, TAB:RB->array | sltu AT, TMP0, TMP1 | beqz AT, ->vmeta_tgetb |. addu RC, TMP2, RC | lw SFRETHI, HI(RC) | beq SFRETHI, TISNIL, >5 |. lw SFRETLO, LO(RC) |1: | ins_next1 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | ins_next2 | |5: // Check for __index if table value is nil. | lw TAB:TMP2, TAB:RB->metatable | beqz TAB:TMP2, <1 // No metatable: done. |. nop | lbu TMP1, TAB:TMP2->nomm | andi TMP1, TMP1, 1<<MM_index | bnez TMP1, <1 // 'no __index' flag set: done. |. nop | b ->vmeta_tgetb // Caveat: preserve TMP0 and CARG2! |. nop break; case BC_TGETR: | // RA = dst*8, RB = table*8, RC = key*8 | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | addu RB, BASE, RB | addu RC, BASE, RC | lw TAB:CARG1, LO(RB) | lw CARG2, LO(RC) | addu RA, BASE, RA | lw TMP0, TAB:CARG1->asize | lw TMP1, TAB:CARG1->array | sltu AT, CARG2, TMP0 | sll TMP2, CARG2, 3 | beqz AT, ->vmeta_tgetr // In array part? |. addu CRET1, TMP1, TMP2 | lw SFARG2HI, HI(CRET1) | lw SFARG2LO, LO(CRET1) |->BC_TGETR_Z: | ins_next1 | sw SFARG2HI, HI(RA) | sw SFARG2LO, LO(RA) | ins_next2 break; case BC_TSETV: | // RA = src*8, RB = table*8, RC = key*8 | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | addu CARG2, BASE, RB | addu CARG3, BASE, RC | lw TMP1, HI(CARG2) | lw TMP2, HI(CARG3) | lw TAB:RB, LO(CARG2) | li AT, LJ_TTAB | bne TMP1, AT, ->vmeta_tsetv |. addu RA, BASE, RA | bne TMP2, TISNUM, >5 |. lw RC, LO(CARG3) | lw TMP0, TAB:RB->asize | lw TMP1, TAB:RB->array | sltu AT, RC, TMP0 | sll TMP2, RC, 3 | beqz AT, ->vmeta_tsetv // Integer key and in array part? |. addu TMP1, TMP1, TMP2 | lw TMP0, HI(TMP1) | lbu TMP3, TAB:RB->marked | lw SFRETHI, HI(RA) | beq TMP0, TISNIL, >3 |. lw SFRETLO, LO(RA) |1: | andi AT, TMP3, LJ_GC_BLACK // isblack(table) | sw SFRETHI, HI(TMP1) | bnez AT, >7 |. sw SFRETLO, LO(TMP1) |2: | ins_next | |3: // Check for __newindex if previous value is nil. | lw TAB:TMP2, TAB:RB->metatable | beqz TAB:TMP2, <1 // No metatable: done. |. nop | lbu TMP2, TAB:TMP2->nomm | andi TMP2, TMP2, 1<<MM_newindex | bnez TMP2, <1 // 'no __newindex' flag set: done. |. nop | b ->vmeta_tsetv |. nop | |5: | li AT, LJ_TSTR | bne TMP2, AT, ->vmeta_tsetv |. nop | b ->BC_TSETS_Z // String key? |. nop | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMP3, TMP0, <2 break; case BC_TSETS: | // RA = src*8, RB = table*8, RC = str_const*8 (~) | decode_RB8a RB, INS | decode_RB8b RB | addu CARG2, BASE, RB | decode_RC4a RC, INS | lw TMP0, HI(CARG2) | decode_RC4b RC | li AT, LJ_TTAB | subu CARG3, KBASE, RC | lw TAB:RB, LO(CARG2) | lw STR:RC, -4(CARG3) // KBASE-4-str_const*4 | bne TMP0, AT, ->vmeta_tsets1 |. addu RA, BASE, RA |->BC_TSETS_Z: | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = BASE+src*8 | lw TMP0, TAB:RB->hmask | lw TMP1, STR:RC->sid | lw NODE:TMP2, TAB:RB->node | sb r0, TAB:RB->nomm // Clear metamethod cache. | and TMP1, TMP1, TMP0 // idx = str->sid & tab->hmask | sll TMP0, TMP1, 5 | sll TMP1, TMP1, 3 | subu TMP1, TMP0, TMP1 | addu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8) |.if FPU | ldc1 f20, 0(RA) |.else | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) |.endif |1: | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2) | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) | li AT, LJ_TSTR | lw NODE:TMP1, NODE:TMP2->next | bne CARG1, AT, >5 |. lw CARG2, offsetof(Node, val)+HI(NODE:TMP2) | bne TMP0, STR:RC, >5 |. lbu TMP3, TAB:RB->marked | beq CARG2, TISNIL, >4 // Key found, but nil value? |. lw TAB:TMP0, TAB:RB->metatable |2: | andi AT, TMP3, LJ_GC_BLACK // isblack(table) |.if FPU | bnez AT, >7 |. sdc1 f20, NODE:TMP2->val |.else | sw SFRETHI, NODE:TMP2->val.u32.hi | bnez AT, >7 |. sw SFRETLO, NODE:TMP2->val.u32.lo |.endif |3: | ins_next | |4: // Check for __newindex if previous value is nil. | beqz TAB:TMP0, <2 // No metatable: done. |. nop | lbu TMP0, TAB:TMP0->nomm | andi TMP0, TMP0, 1<<MM_newindex | bnez TMP0, <2 // 'no __newindex' flag set: done. |. nop | b ->vmeta_tsets |. nop | |5: // Follow hash chain. | bnez NODE:TMP1, <1 |. move NODE:TMP2, NODE:TMP1 | // End of hash chain: key not found, add a new one | | // But check for __newindex first. | lw TAB:TMP2, TAB:RB->metatable | beqz TAB:TMP2, >6 // No metatable: continue. |. addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) | lbu TMP0, TAB:TMP2->nomm | andi TMP0, TMP0, 1<<MM_newindex | beqz TMP0, ->vmeta_tsets // 'no __newindex' flag NOT set: check. |. li AT, LJ_TSTR |6: | load_got lj_tab_newkey | sw STR:RC, LO(CARG3) | sw AT, HI(CARG3) | sw BASE, L->base | move CARG2, TAB:RB | sw PC, SAVE_PC | call_intern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k |. move CARG1, L | // Returns TValue *. | lw BASE, L->base |.if FPU | b <3 // No 2nd write barrier needed. |. sdc1 f20, 0(CRET1) |.else | lw SFARG1HI, HI(RA) | lw SFARG1LO, LO(RA) | sw SFARG1HI, HI(CRET1) | b <3 // No 2nd write barrier needed. |. sw SFARG1LO, LO(CRET1) |.endif | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMP3, TMP0, <3 break; case BC_TSETB: | // RA = src*8, RB = table*8, RC = index*8 | decode_RB8a RB, INS | decode_RB8b RB | addu CARG2, BASE, RB | decode_RDtoRC8 RC, RD | lw CARG1, HI(CARG2) | li AT, LJ_TTAB | lw TAB:RB, LO(CARG2) | addu RA, BASE, RA | bne CARG1, AT, ->vmeta_tsetb |. srl TMP0, RC, 3 | lw TMP1, TAB:RB->asize | lw TMP2, TAB:RB->array | sltu AT, TMP0, TMP1 | beqz AT, ->vmeta_tsetb |. addu RC, TMP2, RC | lw TMP1, HI(RC) | lbu TMP3, TAB:RB->marked | beq TMP1, TISNIL, >5 |1: |. lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | andi AT, TMP3, LJ_GC_BLACK // isblack(table) | sw SFRETHI, HI(RC) | bnez AT, >7 |. sw SFRETLO, LO(RC) |2: | ins_next | |5: // Check for __newindex if previous value is nil. | lw TAB:TMP2, TAB:RB->metatable | beqz TAB:TMP2, <1 // No metatable: done. |. nop | lbu TMP1, TAB:TMP2->nomm | andi TMP1, TMP1, 1<<MM_newindex | bnez TMP1, <1 // 'no __newindex' flag set: done. |. nop | b ->vmeta_tsetb // Caveat: preserve TMP0 and CARG2! |. nop | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMP3, TMP0, <2 break; case BC_TSETR: | // RA = dst*8, RB = table*8, RC = key*8 | decode_RB8a RB, INS | decode_RB8b RB | decode_RDtoRC8 RC, RD | addu CARG1, BASE, RB | addu CARG3, BASE, RC | lw TAB:CARG2, LO(CARG1) | lw CARG3, LO(CARG3) | lbu TMP3, TAB:CARG2->marked | lw TMP0, TAB:CARG2->asize | lw TMP1, TAB:CARG2->array | andi AT, TMP3, LJ_GC_BLACK // isblack(table) | bnez AT, >7 |. addu RA, BASE, RA |2: | sltu AT, CARG3, TMP0 | sll TMP2, CARG3, 3 | beqz AT, ->vmeta_tsetr // In array part? |. addu CRET1, TMP1, TMP2 |->BC_TSETR_Z: | lw SFARG1HI, HI(RA) | lw SFARG1LO, LO(RA) | ins_next1 | sw SFARG1HI, HI(CRET1) | sw SFARG1LO, LO(CRET1) | ins_next2 | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:CARG2, TMP3, CRET1, <2 break; case BC_TSETM: | // RA = base*8 (table at base-1), RD = num_const*8 (start index) | addu RA, BASE, RA |1: | addu TMP3, KBASE, RD | lw TAB:CARG2, -8+LO(RA) // Guaranteed to be a table. | addiu TMP0, MULTRES, -8 | lw TMP3, LO(TMP3) // Integer constant is in lo-word. | beqz TMP0, >4 // Nothing to copy? |. srl CARG3, TMP0, 3 | addu CARG3, CARG3, TMP3 | lw TMP2, TAB:CARG2->asize | sll TMP1, TMP3, 3 | lbu TMP3, TAB:CARG2->marked | lw CARG1, TAB:CARG2->array | sltu AT, TMP2, CARG3 | bnez AT, >5 |. addu TMP2, RA, TMP0 | addu TMP1, TMP1, CARG1 | andi TMP0, TMP3, LJ_GC_BLACK // isblack(table) |3: // Copy result slots to table. | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | addiu RA, RA, 8 | sltu AT, RA, TMP2 | sw SFRETHI, HI(TMP1) | sw SFRETLO, LO(TMP1) | bnez AT, <3 |. addiu TMP1, TMP1, 8 | bnez TMP0, >7 |. nop |4: | ins_next | |5: // Need to resize array part. | load_got lj_tab_reasize | sw BASE, L->base | sw PC, SAVE_PC | move BASE, RD | call_intern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize) |. move CARG1, L | // Must not reallocate the stack. | move RD, BASE | b <1 |. lw BASE, L->base // Reload BASE for lack of a saved register. | |7: // Possible table write barrier for any value. Skip valiswhite check. | barrierback TAB:CARG2, TMP3, TMP0, <4 break; /* -- Calls and vararg handling ----------------------------------------- */ case BC_CALLM: | // RA = base*8, (RB = (nresults+1)*8,) RC = extra_nargs*8 | decode_RDtoRC8 NARGS8:RC, RD | b ->BC_CALL_Z |. addu NARGS8:RC, NARGS8:RC, MULTRES break; case BC_CALL: | // RA = base*8, (RB = (nresults+1)*8,) RC = (nargs+1)*8 | decode_RDtoRC8 NARGS8:RC, RD |->BC_CALL_Z: | move TMP2, BASE | addu BASE, BASE, RA | li AT, LJ_TFUNC | lw TMP0, HI(BASE) | lw LFUNC:RB, LO(BASE) | addiu BASE, BASE, 8 | bne TMP0, AT, ->vmeta_call |. addiu NARGS8:RC, NARGS8:RC, -8 | ins_call break; case BC_CALLMT: | // RA = base*8, (RB = 0,) RC = extra_nargs*8 | addu NARGS8:RD, NARGS8:RD, MULTRES // BC_CALLT gets RC from RD. | // Fall through. Assumes BC_CALLT follows. break; case BC_CALLT: | // RA = base*8, (RB = 0,) RC = (nargs+1)*8 | addu RA, BASE, RA | li AT, LJ_TFUNC | lw TMP0, HI(RA) | lw LFUNC:RB, LO(RA) | move NARGS8:RC, RD | lw TMP1, FRAME_PC(BASE) | addiu RA, RA, 8 | bne TMP0, AT, ->vmeta_callt |. addiu NARGS8:RC, NARGS8:RC, -8 |->BC_CALLT_Z: | andi TMP0, TMP1, FRAME_TYPE // Caveat: preserve TMP0 until the 'or'. | lbu TMP3, LFUNC:RB->ffid | bnez TMP0, >7 |. xori TMP2, TMP1, FRAME_VARG |1: | sw LFUNC:RB, FRAME_FUNC(BASE) // Copy function down, but keep PC. | sltiu AT, TMP3, 2 // (> FF_C) Calling a fast function? | move TMP2, BASE | beqz NARGS8:RC, >3 |. move TMP3, NARGS8:RC |2: | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | addiu RA, RA, 8 | addiu TMP3, TMP3, -8 | sw SFRETHI, HI(TMP2) | sw SFRETLO, LO(TMP2) | bnez TMP3, <2 |. addiu TMP2, TMP2, 8 |3: | or TMP0, TMP0, AT | beqz TMP0, >5 |. nop |4: | ins_callt | |5: // Tailcall to a fast function with a Lua frame below. | lw INS, -4(TMP1) | decode_RA8a RA, INS | decode_RA8b RA | subu TMP1, BASE, RA | lw LFUNC:TMP1, -8+FRAME_FUNC(TMP1) | lw TMP1, LFUNC:TMP1->pc | b <4 |. lw KBASE, PC2PROTO(k)(TMP1) // Need to prepare KBASE. | |7: // Tailcall from a vararg function. | andi AT, TMP2, FRAME_TYPEP | bnez AT, <1 // Vararg frame below? |. subu TMP2, BASE, TMP2 // Relocate BASE down. | move BASE, TMP2 | lw TMP1, FRAME_PC(TMP2) | b <1 |. andi TMP0, TMP1, FRAME_TYPE break; case BC_ITERC: | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 ((2+1)*8)) | move TMP2, BASE | addu BASE, BASE, RA | li AT, LJ_TFUNC | lw TMP1, -24+HI(BASE) | lw LFUNC:RB, -24+LO(BASE) | lw SFARG1HI, -16+HI(BASE) | lw SFARG1LO, -16+LO(BASE) | lw SFARG2HI, -8+HI(BASE) | lw SFARG2LO, -8+LO(BASE) | sw TMP1, HI(BASE) // Copy callable. | sw LFUNC:RB, LO(BASE) | sw SFARG1HI, 8+HI(BASE) // Copy state. | sw SFARG1LO, 8+LO(BASE) | sw SFARG2HI, 16+HI(BASE) // Copy control var. | sw SFARG2LO, 16+LO(BASE) | addiu BASE, BASE, 8 | bne TMP1, AT, ->vmeta_call |. li NARGS8:RC, 16 // Iterators get 2 arguments. | ins_call break; case BC_ITERN: |.if JIT and ENDIAN_LE | hotloop |.endif |->vm_IITERN: | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 (2+1)*8) | addu RA, BASE, RA | lw TAB:RB, -16+LO(RA) | lw RC, -8+LO(RA) // Get index from control var. | lw TMP0, TAB:RB->asize | lw TMP1, TAB:RB->array | addiu PC, PC, 4 |1: // Traverse array part. | sltu AT, RC, TMP0 | beqz AT, >5 // Index points after array part? |. sll TMP3, RC, 3 | addu TMP3, TMP1, TMP3 | lw SFARG1HI, HI(TMP3) | lw SFARG1LO, LO(TMP3) | lhu RD, -4+OFS_RD(PC) | sw TISNUM, HI(RA) | sw RC, LO(RA) | beq SFARG1HI, TISNIL, <1 // Skip holes in array part. |. addiu RC, RC, 1 | sw SFARG1HI, 8+HI(RA) | sw SFARG1LO, 8+LO(RA) | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | decode_RD4b RD | addu RD, RD, TMP3 | sw RC, -8+LO(RA) // Update control var. | addu PC, PC, RD |3: | ins_next | |5: // Traverse hash part. | lw TMP1, TAB:RB->hmask | subu RC, RC, TMP0 | lw TMP2, TAB:RB->node |6: | sltu AT, TMP1, RC // End of iteration? Branch to ITERL+1. | bnez AT, <3 |. sll TMP3, RC, 5 | sll RB, RC, 3 | subu TMP3, TMP3, RB | addu NODE:TMP3, TMP3, TMP2 | lw SFARG1HI, NODE:TMP3->val.u32.hi | lw SFARG1LO, NODE:TMP3->val.u32.lo | lhu RD, -4+OFS_RD(PC) | beq SFARG1HI, TISNIL, <6 // Skip holes in hash part. |. addiu RC, RC, 1 | lw SFARG2HI, NODE:TMP3->key.u32.hi | lw SFARG2LO, NODE:TMP3->key.u32.lo | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) | sw SFARG1HI, 8+HI(RA) | sw SFARG1LO, 8+LO(RA) | addu RC, RC, TMP0 | decode_RD4b RD | addu RD, RD, TMP3 | sw SFARG2HI, HI(RA) | sw SFARG2LO, LO(RA) | addu PC, PC, RD | b <3 |. sw RC, -8+LO(RA) // Update control var. break; case BC_ISNEXT: | // RA = base*8, RD = target (points to ITERN) | addu RA, BASE, RA | srl TMP0, RD, 1 | lw CARG1, -24+HI(RA) | lw CFUNC:CARG2, -24+LO(RA) | addu TMP0, PC, TMP0 | lw CARG3, -16+HI(RA) | lw CARG4, -8+HI(RA) | li AT, LJ_TFUNC | bne CARG1, AT, >5 |. lui TMP2, (-(BCBIAS_J*4 >> 16) & 65535) | lbu CARG2, CFUNC:CARG2->ffid | addiu CARG3, CARG3, -LJ_TTAB | addiu CARG4, CARG4, -LJ_TNIL | or CARG3, CARG3, CARG4 | addiu CARG2, CARG2, -FF_next_N | or CARG2, CARG2, CARG3 | bnez CARG2, >5 |. lui TMP1, (LJ_KEYINDEX >> 16) | addu PC, TMP0, TMP2 | ori TMP1, TMP1, (LJ_KEYINDEX & 0xffff) | sw r0, -8+LO(RA) // Initialize control var. | sw TMP1, -8+HI(RA) |1: | ins_next |5: // Despecialize bytecode if any of the checks fail. | li TMP3, BC_JMP | li TMP1, BC_ITERC | sb TMP3, -4+OFS_OP(PC) | addu PC, TMP0, TMP2 |.if JIT | lb TMP0, OFS_OP(PC) | li AT, BC_ITERN | bne TMP0, AT, >6 |. lhu TMP2, OFS_RD(PC) |.endif | b <1 |. sb TMP1, OFS_OP(PC) |.if JIT |6: // Unpatch JLOOP. | lw TMP0, DISPATCH_J(trace)(DISPATCH) | sll TMP2, TMP2, 2 | addu TMP0, TMP0, TMP2 | lw TRACE:TMP2, 0(TMP0) | lw TMP0, TRACE:TMP2->startins | li AT, -256 | and TMP0, TMP0, AT | or TMP0, TMP0, TMP1 | b <1 |. sw TMP0, 0(PC) |.endif break; case BC_VARG: | // RA = base*8, RB = (nresults+1)*8, RC = numparams*8 | lw TMP0, FRAME_PC(BASE) | decode_RDtoRC8 RC, RD | decode_RB8a RB, INS | addu RC, BASE, RC | decode_RB8b RB | addu RA, BASE, RA | addiu RC, RC, FRAME_VARG | addu TMP2, RA, RB | addiu TMP3, BASE, -8 // TMP3 = vtop | subu RC, RC, TMP0 // RC = vbase | // Note: RC may now be even _above_ BASE if nargs was < numparams. | beqz RB, >5 // Copy all varargs? |. subu TMP1, TMP3, RC | addiu TMP2, TMP2, -16 |1: // Copy vararg slots to destination slots. | lw CARG1, HI(RC) | sltu AT, RC, TMP3 | lw CARG2, LO(RC) | addiu RC, RC, 8 | movz CARG1, TISNIL, AT | sw CARG1, HI(RA) | sw CARG2, LO(RA) | sltu AT, RA, TMP2 | bnez AT, <1 |. addiu RA, RA, 8 |3: | ins_next | |5: // Copy all varargs. | lw TMP0, L->maxstack | blez TMP1, <3 // No vararg slots? |. li MULTRES, 8 // MULTRES = (0+1)*8 | addu TMP2, RA, TMP1 | sltu AT, TMP0, TMP2 | bnez AT, >7 |. addiu MULTRES, TMP1, 8 |6: | lw SFRETHI, HI(RC) | lw SFRETLO, LO(RC) | addiu RC, RC, 8 | sw SFRETHI, HI(RA) | sw SFRETLO, LO(RA) | sltu AT, RC, TMP3 | bnez AT, <6 // More vararg slots? |. addiu RA, RA, 8 | b <3 |. nop | |7: // Grow stack for varargs. | load_got lj_state_growstack | sw RA, L->top | subu RA, RA, BASE | sw BASE, L->base | subu BASE, RC, BASE // Need delta, because BASE may change. | sw PC, SAVE_PC | srl CARG2, TMP1, 3 | call_intern lj_state_growstack // (lua_State *L, int n) |. move CARG1, L | move RC, BASE | lw BASE, L->base | addu RA, BASE, RA | addu RC, BASE, RC | b <6 |. addiu TMP3, BASE, -8 break; /* -- Returns ----------------------------------------------------------- */ case BC_RETM: | // RA = results*8, RD = extra_nresults*8 | addu RD, RD, MULTRES // MULTRES >= 8, so RD >= 8. | // Fall through. Assumes BC_RET follows. break; case BC_RET: | // RA = results*8, RD = (nresults+1)*8 | lw PC, FRAME_PC(BASE) | addu RA, BASE, RA | move MULTRES, RD |1: | andi TMP0, PC, FRAME_TYPE | bnez TMP0, ->BC_RETV_Z |. xori TMP1, PC, FRAME_VARG | |->BC_RET_Z: | // BASE = base, RA = resultptr, RD = (nresults+1)*8, PC = return | lw INS, -4(PC) | addiu TMP2, BASE, -8 | addiu RC, RD, -8 | decode_RA8a TMP0, INS | decode_RB8a RB, INS | decode_RA8b TMP0 | decode_RB8b RB | addu TMP3, TMP2, RB | beqz RC, >3 |. subu BASE, TMP2, TMP0 |2: | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) | addiu RA, RA, 8 | addiu RC, RC, -8 | sw SFRETHI, HI(TMP2) | sw SFRETLO, LO(TMP2) | bnez RC, <2 |. addiu TMP2, TMP2, 8 |3: | addiu TMP3, TMP3, -8 |5: | sltu AT, TMP2, TMP3 | bnez AT, >6 |. lw LFUNC:TMP1, FRAME_FUNC(BASE) | ins_next1 | lw TMP1, LFUNC:TMP1->pc | lw KBASE, PC2PROTO(k)(TMP1) | ins_next2 | |6: // Fill up results with nil. | sw TISNIL, HI(TMP2) | b <5 |. addiu TMP2, TMP2, 8 | |->BC_RETV_Z: // Non-standard return case. | andi TMP2, TMP1, FRAME_TYPEP | bnez TMP2, ->vm_return |. nop | // Return from vararg function: relocate BASE down. | subu BASE, BASE, TMP1 | b <1 |. lw PC, FRAME_PC(BASE) break; case BC_RET0: case BC_RET1: | // RA = results*8, RD = (nresults+1)*8 | lw PC, FRAME_PC(BASE) | addu RA, BASE, RA | move MULTRES, RD | andi TMP0, PC, FRAME_TYPE | bnez TMP0, ->BC_RETV_Z |. xori TMP1, PC, FRAME_VARG | | lw INS, -4(PC) | addiu TMP2, BASE, -8 if (op == BC_RET1) { | lw SFRETHI, HI(RA) | lw SFRETLO, LO(RA) } | decode_RB8a RB, INS | decode_RA8a RA, INS | decode_RB8b RB | decode_RA8b RA if (op == BC_RET1) { | sw SFRETHI, HI(TMP2) | sw SFRETLO, LO(TMP2) } | subu BASE, TMP2, RA |5: | sltu AT, RD, RB | bnez AT, >6 |. lw LFUNC:TMP1, FRAME_FUNC(BASE) | ins_next1 | lw TMP1, LFUNC:TMP1->pc | lw KBASE, PC2PROTO(k)(TMP1) | ins_next2 | |6: // Fill up results with nil. | addiu TMP2, TMP2, 8 | addiu RD, RD, 8 | b <5 if (op == BC_RET1) { |. sw TISNIL, HI(TMP2) } else { |. sw TISNIL, -8+HI(TMP2) } break; /* -- Loops and branches ------------------------------------------------ */ case BC_FORL: |.if JIT | hotloop |.endif | // Fall through. Assumes BC_IFORL follows. break; case BC_JFORI: case BC_JFORL: #if !LJ_HASJIT break; #endif case BC_FORI: case BC_IFORL: | // RA = base*8, RD = target (after end of loop or start of loop) vk = (op == BC_IFORL || op == BC_JFORL); | addu RA, BASE, RA | lw SFARG1HI, FORL_IDX*8+HI(RA) | lw SFARG1LO, FORL_IDX*8+LO(RA) if (op != BC_JFORL) { | srl RD, RD, 1 | lui TMP2, (-(BCBIAS_J*4 >> 16) & 65535) | addu TMP2, RD, TMP2 } if (!vk) { | lw SFARG2HI, FORL_STOP*8+HI(RA) | lw SFARG2LO, FORL_STOP*8+LO(RA) | bne SFARG1HI, TISNUM, >5 |. lw SFRETHI, FORL_STEP*8+HI(RA) | xor AT, SFARG2HI, TISNUM | lw SFRETLO, FORL_STEP*8+LO(RA) | xor TMP0, SFRETHI, TISNUM | or AT, AT, TMP0 | bnez AT, ->vmeta_for |. slt AT, SFRETLO, r0 | slt CRET1, SFARG2LO, SFARG1LO | slt TMP1, SFARG1LO, SFARG2LO | movn CRET1, TMP1, AT } else { | bne SFARG1HI, TISNUM, >5 |. lw SFARG2LO, FORL_STEP*8+LO(RA) | lw SFRETLO, FORL_STOP*8+LO(RA) | move TMP3, SFARG1LO | addu SFARG1LO, SFARG1LO, SFARG2LO | xor TMP0, SFARG1LO, TMP3 | xor TMP1, SFARG1LO, SFARG2LO | and TMP0, TMP0, TMP1 | slt TMP1, SFARG1LO, SFRETLO | slt CRET1, SFRETLO, SFARG1LO | slt AT, SFARG2LO, r0 | slt TMP0, TMP0, r0 // ((y^a) & (y^b)) < 0: overflow. | movn CRET1, TMP1, AT | or CRET1, CRET1, TMP0 } |1: if (op == BC_FORI) { | movz TMP2, r0, CRET1 | addu PC, PC, TMP2 } else if (op == BC_JFORI) { | addu PC, PC, TMP2 | lhu RD, -4+OFS_RD(PC) } else if (op == BC_IFORL) { | movn TMP2, r0, CRET1 | addu PC, PC, TMP2 } if (vk) { | sw SFARG1HI, FORL_IDX*8+HI(RA) | sw SFARG1LO, FORL_IDX*8+LO(RA) } | ins_next1 | sw SFARG1HI, FORL_EXT*8+HI(RA) | sw SFARG1LO, FORL_EXT*8+LO(RA) |2: if (op == BC_JFORI) { | beqz CRET1, =>BC_JLOOP |. decode_RD8b RD } else if (op == BC_JFORL) { | beqz CRET1, =>BC_JLOOP } | ins_next2 | |5: // FP loop. |.if FPU if (!vk) { | ldc1 f0, FORL_IDX*8(RA) | ldc1 f2, FORL_STOP*8(RA) | sltiu TMP0, SFARG1HI, LJ_TISNUM | sltiu TMP1, SFARG2HI, LJ_TISNUM | sltiu AT, SFRETHI, LJ_TISNUM | and TMP0, TMP0, TMP1 | and AT, AT, TMP0 | beqz AT, ->vmeta_for |. slt TMP3, SFRETHI, r0 | c.ole.d 0, f0, f2 | c.ole.d 1, f2, f0 | li CRET1, 1 | movt CRET1, r0, 0 | movt AT, r0, 1 | b <1 |. movn CRET1, AT, TMP3 } else { | ldc1 f0, FORL_IDX*8(RA) | ldc1 f4, FORL_STEP*8(RA) | ldc1 f2, FORL_STOP*8(RA) | lw SFARG2HI, FORL_STEP*8+HI(RA) | add.d f0, f0, f4 | c.ole.d 0, f0, f2 | c.ole.d 1, f2, f0 | slt TMP3, SFARG2HI, r0 | li CRET1, 1 | li AT, 1 | movt CRET1, r0, 0 | movt AT, r0, 1 | movn CRET1, AT, TMP3 if (op == BC_IFORL) { | movn TMP2, r0, CRET1 | addu PC, PC, TMP2 } | sdc1 f0, FORL_IDX*8(RA) | ins_next1 | b <2 |. sdc1 f0, FORL_EXT*8(RA) } |.else if (!vk) { | sltiu TMP0, SFARG1HI, LJ_TISNUM | sltiu TMP1, SFARG2HI, LJ_TISNUM | sltiu AT, SFRETHI, LJ_TISNUM | and TMP0, TMP0, TMP1 | and AT, AT, TMP0 | beqz AT, ->vmeta_for |. nop | bal ->vm_sfcmpolex |. move TMP3, SFRETHI | b <1 |. nop } else { | lw SFARG2HI, FORL_STEP*8+HI(RA) | load_got __adddf3 | call_extern |. sw TMP2, ARG5 | lw SFARG2HI, FORL_STOP*8+HI(RA) | lw SFARG2LO, FORL_STOP*8+LO(RA) | move SFARG1HI, SFRETHI | move SFARG1LO, SFRETLO | bal ->vm_sfcmpolex |. lw TMP3, FORL_STEP*8+HI(RA) if ( op == BC_JFORL ) { | lhu RD, -4+OFS_RD(PC) | lw TMP2, ARG5 | b <1 |. decode_RD8b RD } else { | b <1 |. lw TMP2, ARG5 } } |.endif break; case BC_ITERL: |.if JIT | hotloop |.endif | // Fall through. Assumes BC_IITERL follows. break; case BC_JITERL: #if !LJ_HASJIT break; #endif case BC_IITERL: | // RA = base*8, RD = target | addu RA, BASE, RA | lw TMP1, HI(RA) | beq TMP1, TISNIL, >1 // Stop if iterator returned nil. |. lw TMP2, LO(RA) if (op == BC_JITERL) { | sw TMP1, -8+HI(RA) | b =>BC_JLOOP |. sw TMP2, -8+LO(RA) } else { | branch_RD // Otherwise save control var + branch. | sw TMP1, -8+HI(RA) | sw TMP2, -8+LO(RA) } |1: | ins_next break; case BC_LOOP: | // RA = base*8, RD = target (loop extent) | // Note: RA/RD is only used by trace recorder to determine scope/extent | // This opcode does NOT jump, it's only purpose is to detect a hot loop. |.if JIT | hotloop |.endif | // Fall through. Assumes BC_ILOOP follows. break; case BC_ILOOP: | // RA = base*8, RD = target (loop extent) | ins_next break; case BC_JLOOP: |.if JIT | // RA = base*8 (ignored), RD = traceno*8 | lw TMP1, DISPATCH_J(trace)(DISPATCH) | srl RD, RD, 1 | li AT, 0 | addu TMP1, TMP1, RD | // Traces on MIPS don't store the trace number, so use 0. | sw AT, DISPATCH_GL(vmstate)(DISPATCH) | lw TRACE:TMP2, 0(TMP1) | sw BASE, DISPATCH_GL(jit_base)(DISPATCH) | lw TMP2, TRACE:TMP2->mcode | sw L, DISPATCH_GL(tmpbuf.L)(DISPATCH) | jr TMP2 |. addiu JGL, DISPATCH, GG_DISP2G+32768 |.endif break; case BC_JMP: | // RA = base*8 (only used by trace recorder), RD = target | branch_RD | ins_next break; /* -- Function headers -------------------------------------------------- */ case BC_FUNCF: |.if JIT | hotcall |.endif case BC_FUNCV: /* NYI: compiled vararg functions. */ | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow. break; case BC_JFUNCF: #if !LJ_HASJIT break; #endif case BC_IFUNCF: | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8 | lw TMP2, L->maxstack | lbu TMP1, -4+PC2PROTO(numparams)(PC) | lw KBASE, -4+PC2PROTO(k)(PC) | sltu AT, TMP2, RA | bnez AT, ->vm_growstack_l |. sll TMP1, TMP1, 3 if (op != BC_JFUNCF) { | ins_next1 } |2: | sltu AT, NARGS8:RC, TMP1 // Check for missing parameters. | bnez AT, >3 |. addu AT, BASE, NARGS8:RC if (op == BC_JFUNCF) { | decode_RD8a RD, INS | b =>BC_JLOOP |. decode_RD8b RD } else { | ins_next2 } | |3: // Clear missing parameters. | sw TISNIL, HI(AT) | b <2 |. addiu NARGS8:RC, NARGS8:RC, 8 break; case BC_JFUNCV: #if !LJ_HASJIT break; #endif | NYI // NYI: compiled vararg functions break; /* NYI: compiled vararg functions. */ case BC_IFUNCV: | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8 | addu TMP1, BASE, RC | lw TMP2, L->maxstack | addu TMP0, RA, RC | sw LFUNC:RB, LO(TMP1) // Store copy of LFUNC. | addiu TMP3, RC, 8+FRAME_VARG | sltu AT, TMP0, TMP2 | lw KBASE, -4+PC2PROTO(k)(PC) | beqz AT, ->vm_growstack_l |. sw TMP3, HI(TMP1) // Store delta + FRAME_VARG. | lbu TMP2, -4+PC2PROTO(numparams)(PC) | move RA, BASE | move RC, TMP1 | ins_next1 | beqz TMP2, >3 |. addiu BASE, TMP1, 8 |1: | lw TMP0, HI(RA) | lw TMP3, LO(RA) | sltu AT, RA, RC // Less args than parameters? | move CARG1, TMP0 | movz TMP0, TISNIL, AT // Clear missing parameters. | movn CARG1, TISNIL, AT // Clear old fixarg slot (help the GC). | sw TMP3, 8+LO(TMP1) | addiu TMP2, TMP2, -1 | sw TMP0, 8+HI(TMP1) | addiu TMP1, TMP1, 8 | sw CARG1, HI(RA) | bnez TMP2, <1 |. addiu RA, RA, 8 |3: | ins_next2 break; case BC_FUNCC: case BC_FUNCCW: | // BASE = new base, RA = BASE+framesize*8, RB = CFUNC, RC = nargs*8 if (op == BC_FUNCC) { | lw CFUNCADDR, CFUNC:RB->f } else { | lw CFUNCADDR, DISPATCH_GL(wrapf)(DISPATCH) } | addu TMP1, RA, NARGS8:RC | lw TMP2, L->maxstack | addu RC, BASE, NARGS8:RC | sw BASE, L->base | sltu AT, TMP2, TMP1 | sw RC, L->top | li_vmstate C if (op == BC_FUNCCW) { | lw CARG2, CFUNC:RB->f } | bnez AT, ->vm_growstack_c // Need to grow stack. |. move CARG1, L | jalr CFUNCADDR // (lua_State *L [, lua_CFunction f]) |. st_vmstate | // Returns nresults. | lw BASE, L->base | sll RD, CRET1, 3 | lw TMP1, L->top | li_vmstate INTERP | lw PC, FRAME_PC(BASE) // Fetch PC of caller. | subu RA, TMP1, RD // RA = L->top - nresults*8 | sw L, DISPATCH_GL(cur_L)(DISPATCH) | b ->vm_returnc |. st_vmstate break; /* ---------------------------------------------------------------------- */ default: fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]); exit(2); break; } } static int build_backend(BuildCtx *ctx) { int op; dasm_growpc(Dst, BC__MAX); build_subroutines(ctx); |.code_op for (op = 0; op < BC__MAX; op++) build_ins(ctx, (BCOp)op, op); return BC__MAX; } /* Emit pseudo frame-info for all assembler functions. */ static void emit_asm_debug(BuildCtx *ctx) { int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code); int i; switch (ctx->mode) { case BUILD_elfasm: fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n"); fprintf(ctx->fp, ".Lframe0:\n" "\t.4byte .LECIE0-.LSCIE0\n" ".LSCIE0:\n" "\t.4byte 0xffffffff\n" "\t.byte 0x1\n" "\t.string \"\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -4\n" "\t.byte 31\n" "\t.byte 0xc\n\t.uleb128 29\n\t.uleb128 0\n" "\t.align 2\n" ".LECIE0:\n\n"); fprintf(ctx->fp, ".LSFDE0:\n" "\t.4byte .LEFDE0-.LASFDE0\n" ".LASFDE0:\n" "\t.4byte .Lframe0\n" "\t.4byte .Lbegin\n" "\t.4byte %d\n" "\t.byte 0xe\n\t.uleb128 %d\n" "\t.byte 0x9f\n\t.sleb128 1\n" "\t.byte 0x9e\n\t.sleb128 2\n", fcofs, CFRAME_SIZE); for (i = 23; i >= 16; i--) fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i); #if !LJ_SOFTFP for (i = 30; i >= 20; i -= 2) fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i); #endif fprintf(ctx->fp, "\t.align 2\n" ".LEFDE0:\n\n"); #if LJ_HASFFI fprintf(ctx->fp, ".LSFDE1:\n" "\t.4byte .LEFDE1-.LASFDE1\n" ".LASFDE1:\n" "\t.4byte .Lframe0\n" "\t.4byte lj_vm_ffi_call\n" "\t.4byte %d\n" "\t.byte 0x9f\n\t.uleb128 1\n" "\t.byte 0x90\n\t.uleb128 2\n" "\t.byte 0xd\n\t.uleb128 0x10\n" "\t.align 2\n" ".LEFDE1:\n\n", (int)ctx->codesz - fcofs); #endif #if !LJ_NO_UNWIND fprintf(ctx->fp, "\t.section .eh_frame,\"aw\",@progbits\n"); fprintf(ctx->fp, "\t.globl lj_err_unwind_dwarf\n" ".Lframe1:\n" "\t.4byte .LECIE1-.LSCIE1\n" ".LSCIE1:\n" "\t.4byte 0\n" "\t.byte 0x1\n" "\t.string \"zPR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -4\n" "\t.byte 31\n" "\t.uleb128 6\n" /* augmentation length */ "\t.byte 0\n" "\t.4byte lj_err_unwind_dwarf\n" "\t.byte 0\n" "\t.byte 0xc\n\t.uleb128 29\n\t.uleb128 0\n" "\t.align 2\n" ".LECIE1:\n\n"); fprintf(ctx->fp, ".LSFDE2:\n" "\t.4byte .LEFDE2-.LASFDE2\n" ".LASFDE2:\n" "\t.4byte .LASFDE2-.Lframe1\n" "\t.4byte .Lbegin\n" "\t.4byte %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0xe\n\t.uleb128 %d\n" "\t.byte 0x9f\n\t.sleb128 1\n" "\t.byte 0x9e\n\t.sleb128 2\n", fcofs, CFRAME_SIZE); for (i = 23; i >= 16; i--) fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i); #if !LJ_SOFTFP for (i = 30; i >= 20; i -= 2) fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i); #endif fprintf(ctx->fp, "\t.align 2\n" ".LEFDE2:\n\n"); #if LJ_HASFFI fprintf(ctx->fp, ".Lframe2:\n" "\t.4byte .LECIE2-.LSCIE2\n" ".LSCIE2:\n" "\t.4byte 0\n" "\t.byte 0x1\n" "\t.string \"zR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -4\n" "\t.byte 31\n" "\t.uleb128 1\n" /* augmentation length */ "\t.byte 0\n" "\t.byte 0xc\n\t.uleb128 29\n\t.uleb128 0\n" "\t.align 2\n" ".LECIE2:\n\n"); fprintf(ctx->fp, ".LSFDE3:\n" "\t.4byte .LEFDE3-.LASFDE3\n" ".LASFDE3:\n" "\t.4byte .LASFDE3-.Lframe2\n" "\t.4byte lj_vm_ffi_call\n" "\t.4byte %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0x9f\n\t.uleb128 1\n" "\t.byte 0x90\n\t.uleb128 2\n" "\t.byte 0xd\n\t.uleb128 0x10\n" "\t.align 2\n" ".LEFDE3:\n\n", (int)ctx->codesz - fcofs); #endif #endif break; default: break; } }
xLua/build/luajit-2.1.0b3/src/vm_mips.dasc/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/vm_mips.dasc", "repo_id": "xLua", "token_count": 78765 }
1,942
local ffi = require "ffi" ffi.cdef[[ #pragma pack(push, 1) typedef struct { char x; double y; } foo; #pragma pack(pop) ]] assert(ffi.sizeof("foo") == 9)
xLua/build/luajit-2.1.0b3/src/x64/test/unit/ffi/test_pragma_pack_pushpop.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/x64/test/unit/ffi/test_pragma_pack_pushpop.lua", "repo_id": "xLua", "token_count": 79 }
1,943
#ifndef LUASOCKET_H #define LUASOCKET_H /*=========================================================================*\ * LuaSocket toolkit * Networking support for the Lua language * Diego Nehab * 9/11/1999 \*=========================================================================*/ #include "lua.h" /*-------------------------------------------------------------------------*\ * Current socket library version \*-------------------------------------------------------------------------*/ #define LUASOCKET_VERSION "LuaSocket 3.0-rc1" #define LUASOCKET_COPYRIGHT "Copyright (C) 1999-2013 Diego Nehab" /*-------------------------------------------------------------------------*\ * Initializes the library. \*-------------------------------------------------------------------------*/ LUA_API int luaopen_socket_core(lua_State *L); #endif /* LUASOCKET_H */
xLua/build/luasocket/luasocket.h/0
{ "file_path": "xLua/build/luasocket/luasocket.h", "repo_id": "xLua", "token_count": 187 }
1,944
#ifndef UDP_H #define UDP_H /*=========================================================================*\ * UDP object * LuaSocket toolkit * * The udp.h module provides LuaSocket with support for UDP protocol * (AF_INET, SOCK_DGRAM). * * Two classes are defined: connected and unconnected. UDP objects are * originally unconnected. They can be "connected" to a given address * with a call to the setpeername function. The same function can be used to * break the connection. \*=========================================================================*/ #include "lua.h" #include "timeout.h" #include "socket.h" /* can't be larger than wsocket.c MAXCHUNK!!! */ #define UDP_DATAGRAMSIZE 8192 typedef struct t_udp_ { t_socket sock; t_timeout tm; int family; } t_udp; typedef t_udp *p_udp; int udp_open(lua_State *L); #endif /* UDP_H */
xLua/build/luasocket/udp.h/0
{ "file_path": "xLua/build/luasocket/udp.h", "repo_id": "xLua", "token_count": 267 }
1,945
cd luajit-2.1.0b3 make clean make CC="gcc -m32" cd .. mkdir -p build_linux32_lj && cd build_linux32_lj cmake -DUSING_LUAJIT=ON -DCMAKE_C_FLAGS=-m32 -DCMAKE_CXX_FLAGS=-m32 -DCMAKE_SHARED_LINKER_FLAGS=-m32 ../ cd .. cmake --build build_linux32_lj --config Release
xLua/build/make_linux32_luajit.sh/0
{ "file_path": "xLua/build/make_linux32_luajit.sh", "repo_id": "xLua", "token_count": 128 }
1,946
@echo off call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" echo Swtich to x64 build env cd %~dp0\luajit-2.1.0b3\src call msvcbuild_mt.bat static cd ..\.. mkdir build_lj64 & pushd build_lj64 cmake -DUSING_LUAJIT=ON -G "Visual Studio 16 2019" -A x64 .. IF %ERRORLEVEL% NEQ 0 cmake -DUSING_LUAJIT=ON -G "Visual Studio 16 2019" -A x64 .. popd cmake --build build_lj64 --config Release md plugin_luajit\Plugins\x86_64 copy /Y build_lj64\Release\xlua.dll plugin_luajit\Plugins\x86_64\xlua.dll pause
xLua/build/make_win64_luajit.bat/0
{ "file_path": "xLua/build/make_win64_luajit.bat", "repo_id": "xLua", "token_count": 228 }
1,947
body, footer, header, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li, form, fieldset, legend, button, input, textarea, th, td { margin: 0; padding: 0; } text-align center { -webkit-text-size-adjust: none; color: #3d9cff; } body, button, input, select, textarea, ol, p, blockquote, dl, dt, dd, ul, li, form, fieldset, legend, th, td { outline: none; font: 1em "Helvetica Neue", "Helvetica", "Lucida Grande", "Arial", "Hiragino Sans GB", "Microsoft Yahei", "WenQuanYi Micro Hei", "sans-serif", arial, sans-serif; text-align: left; color: #3d9cff; } body { background-color: #fff; background-attachment: fixed; } ul, ol { list-style: none; } a { color: #3d9cff; text-decoration: none; } a text-decoration none { transition: all 0.5s; -moz-transition: all 0.5s; -webkit-transition: all 0.5s; -o-transition: all 0.5s; cursor: pointer; } a:hover { text-decoration: underline; outline: 0; color: #3d9cff; } .abs { position: absolute; } .clear:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clear { zoom: 1; } button { border: none; } html { overflow-x: hidden; } body { min-width: 20rem; overflow-x: hidden; } .border { padding-left: 1rem; padding-right: 1rem; } .sidebar ul { padding-bottom: 0.9375rem; } .sidebar ul h3 { color: #525252; font-size: 1.125rem; padding-bottom: 0.625rem; margin-bottom: 0.625rem; padding-top: 1.25rem; font-weight: normal; } .sidebar ul li { font-size: 0.875rem; padding-bottom: 0.5rem; text-indent: 1em; } .sidebar ul li p { padding-left: 1rem; } .sub-nav ul h3 { color: #525252; font-weight: 700; margin-bottom: 1rem; padding-left: 0.5rem; } .sub-nav ul li { margin-bottom: 0.25rem; padding-left: 0.5rem; } .sub-nav ul li p { padding-left: 1rem; } .sub-nav ul li.select { border-left: 0.125rem #f4645f solid; padding-left: 0.375rem; } article { color: #525252; text-align: left; } article h1, article h2 { font-size: 2.25rem; font-weight: 500; margin-bottom: 3rem; } article h3, article h4, article h5 { font-weight: 400; } article h3 { font-size: 1.375rem; margin-top: 3.125rem; margin-bottom: 1.875rem; } article h3:before { content: "#"; margin-right: 0.25rem; color: #3d9cff; opacity: 0.3; } article h4 { font-size: 1rem; margin-top: 2.125rem; margin-bottom: 1.25rem; } article h5 { font-size: 1rem; margin-left: 1.25rem; margin-top: 2.125rem; } article p { font-size: 1rem; margin-bottom: 1.25rem; margin-top: 0.625rem; line-height: 1.8; color: #525252; } article ul { padding-left: 2rem; position: inherit; list-style: disc; font-size: 0.9rem; } article ul li { padding-top: 0.25rem; color: #525252; } article table { width: 100%; border-collapse: collapse; border: 0; border-spacing: 0; margin-bottom: 1rem; margin-top: 1rem; } article table tr:nth-child(even) td { background-color: #f7f7f7; } article table .title-row { background-color: #ededed; } article table tr th, article table tr td { padding: 0.5rem 1rem 0.5rem 1rem; color: #525252; } article table tr th { background-color: #e8e8e8; font-weight: bold; font-size: 0.85rem; } article table tr td { font-size: 0.75rem; } article blockquote { padding: 12px 24px 12px 30px; margin: 2em 0; border-left: 4px solid #3d9cff; background-color: #f8f8f8; position: relative; } article blockquote p { padding: 0; margin: 0; } article blockquote:before { position: absolute; top: 14px; left: -12px; background-color: #3d9cff; color: #fff; content: "!"; width: 20px; height: 20px; border-radius: 100%; text-align: center; line-height: 20px; font-weight: bold; font-family: 'Roboto Mono', Monaco, courier, monospace; font-size: 14px; } article blockquote code { background-color: #efefef; } article blockquote em { color: $medium; } article code { border-radius: 3px; background-color: #f0f2f1; font-size: 0.75rem; line-height: 1.8; padding: 1px 5px 1px 5px; color: #3d9cff; font-family: source-code-pro, monospace; margin-left: 5px; margin-right: 5px; text-shadow: 0px 1px #fff; } article p.tip { background-color: #3d9cff; border-radius: 3px; color: #fff; padding: 10px 15px 10px 15px; margin-bottom: 50px; } article p.tip a { color: #fff; } article p.tip p { color: #fff; margin: 0 auto; } article p.tip p a { text-decoration: underline; color: #fff; } article p.tip p a:hover { color: #fcd8d6; } article ol { list-style-type: none; counter-reset: sectioncounter; padding-left: 1rem; position: inherit; font-size: 0.9rem; } article ol li { color: #525252; padding-top: 0.25rem; } article ol li:before { content: counter(sectioncounter) ". "; counter-increment: sectioncounter; } article hr { height: 1px; border: none; border-top: 1px dashed #dcdcdc; } article figure { margin: 1.2rem 0; } article .highlight { overflow-x: auto; position: relative; padding: 0; background-color: #f8f8f8; padding: 0.8rem 0.8rem 0.4rem; line-height: 1.1rem; border-radius: $radius; font-size: 0.85rem; } article .highlight table, article .highlight tr, article .highlight td { width: 100%; border-collapse: collapse; padding: 0; margin: 0; } article .highlight .gutter { width: 1.5rem; } article .highlight .code { color: #525252; font-size: 0.825rem; } article .highlight .code pre { padding: 1.2rem 1.4rem; line-height: 1.5rem; margin: 0; } article .highlight .code .line { min-height: 1.5rem; } article .highlight.html .code:after, article .highlight.js .code:after, article .highlight.bash .code:after, article .highlight.css .code:after, article .highlight.csharp .code:after, article .highlight.lua .code:after { position: absolute; top: 0; right: 0; color: #ccc; text-align: right; font-size: 0.75rem; padding: 5px 10px 0; line-height: 15px; height: 15px; font-weight: 600; } article .highlight.html .code:after { content: 'HTML'; } article .highlight.csharp .code:after { content: 'C#'; } article .highlight.lua .code:after { content: 'Lua'; } article .highlight.js .code:after { content: 'JS'; } article .highlight.bash .code:after { content: 'Shell'; } article .highlight.css .code:after { content: 'CSS'; } article .gutter pre { color: #999; } article pre { color: #525252; } article pre .function .keyword, article pre .constant { color: #3d9cff; } article pre .keyword, article pre .attribute { color: #3d9cff; } article pre .number, article pre .literal { color: #ae81ff; } article pre .tag, article pre .tag .title, article pre .change, article pre .winutils, article pre .flow, article pre .lisp .title, article pre .clojure .built_in, article pre .nginx .title, article pre .tex .special { color: #2973b7; } article pre .class .title { color: #fff; } article pre .symbol, article pre .symbol .string, article pre .value, article pre .regexp { color: #3d9cff; } article pre .title { color: #2973b7; } article pre .tag .value, article pre .string, article pre .subst, article pre .haskell .type, article pre .preprocessor, article pre .ruby .class .parent, article pre .built_in, article pre .sql .aggregate, article pre .django .template_tag, article pre .django .variable, article pre .smalltalk .class, article pre .javadoc, article pre .django .filter .argument, article pre .smalltalk .localvars, article pre .smalltalk .array, article pre .attr_selector, article pre .pseudo, article pre .addition, article pre .stream, article pre .envvar, article pre .apache .tag, article pre .apache .cbracket, article pre .tex .command, article pre .prompt { color: #3d9cff; } article pre .comment, article pre .java .annotation, article pre .python .decorator, article pre .template_comment, article pre .pi, article pre .doctype, article pre .deletion, article pre .shebang, article pre .apache .sqbracket, article pre .tex .formula { color: #b3b3b3; } article pre .coffeescript .javascript, article pre .javascript .xml, article pre .tex .formula, article pre .xml .javascript, article pre .xml .vbscript, article pre .xml .css, article pre .xml .cdata { opacity: 0.5; } @media screen and (min-width: 960px) { article .highlight { font-size: 1.125rem; } } nav { height: 5rem; background-color: #fafafa; position: absolute; width: 100%; z-index: 9999; } nav img { width: 140px; height: 42px; float: left; position: absolute; margin-top: 1rem; } nav .nav-link li { float: right; padding: 1.75rem 1rem; } nav .nav-link li a { color: #3d9cff; } nav button { float: right; margin-top: 1rem; padding: 0.75rem 1.25rem; background-color: #3d9cff; color: #fff; border-radius: 5px; margin-top: 0.4rem; } .container { margin: 0 auto; max-width: 80rem; padding: 0rem 10rem 3rem 15rem; position: relative; } .sidebar { padding: 2.187rem; padding-top: 7rem; width: 11.25rem; margin-left: -15rem; float: left; } article { padding: 7.75rem 7.75rem 0rem 3.25rem; margin-left: 1.25rem; } .sub-nav { position: absolute; top: 15rem; right: 0; width: 10rem; } .sub-nav dl dt { color: #525252; font-weight: 700; margin-bottom: 1rem; padding-left: 0.5rem; } .sub-nav dl dd { margin-bottom: 0.25rem; padding-left: 0.5rem; overflow: hidden; text-overflow: ellipsis; } .sub-nav dl dd.select { border-left: 0.125rem #f4645f solid; padding-left: 0.375rem; } .footer { text-align: center; margin-top: 2.75rem; color: #c8c8c8; font-size: 0.75rem; } footer { background-color: #343434; height: 3.125rem; padding: 1.875rem; } footer p { text-align: center; color: #aeaeae; font-size: 0.8125rem; line-height: 1.8; } .disable { color: #afafaf; } .disable:hover { color: #afafaf; text-decoration: none; } @media screen and (min-width: 960px) { .hiden-in-pc { display: none; } .hiden-in-phone { display: inline; } nav button { margin-top: 1rem; } nav button:hover { background-color: #dc504b; } footer { padding: 3.125rem; } } @media screen and (max-width: 960px) { .hiden-in-pc { display: inline; } .hiden-in-phone { display: none; } nav { height: 3rem; position: fixed; } nav button { margin-top: 0.4rem; padding: 0.35rem 0.75rem; } nav img { width: 110px; height: 30px; margin-top: 0.5rem; } .container { margin: 0; padding: 0rem 0rem 3rem 0rem; } .sidebar { display: none; } article { padding: 5.5rem 1.75rem 0.2rem 0.2rem; min-height: 35rem; } }
xLua/docs/public/css/page.css/0
{ "file_path": "xLua/docs/public/css/page.css", "repo_id": "xLua", "token_count": 4390 }
1,948
<!DOCTYPE html> <html lang="en"> <head> <title>FAQ — XLua</title> <meta charset="utf-8"> <meta name="description" content="XLua"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="/xLua/public/css/page.css"> <script src="/xLua/public/js/vue.js"></script> <script src="/xLua/public/js/jquery.js"></script> </head> <body> <nav class="nav"> <div class="border"> <img src="/xLua/public/images/logo.png" /> <button class="hiden-in-phone">V2.1</button> <button id="btn-menu" class="hiden-in-pc">菜单</button> <ul class="nav-link hiden-in-phone"> <!--li> <form id="search-form"> <input type="text" id="search-query" class="search-query"> </form> </li!--> <li><a href="https://github.com/Tencent/xLua" class="nav-link-li">下载项目</a></li> <li><a href="/xLua/public/v1/guide/use.html" class="nav-link-li">使用案例</a></li> <li><a href="/xLua/public/v1/guide/version.html" class="nav-link-li">更新记录</a></li> <li><a href="/xLua/public/v1/guide/contribution.html" class="nav-link-li">贡献指南</li> <li><a href="/xLua/public/v1/guide/index.html" class="nav-link-li">教程</a></li> <li><a href="/xLua/public/" class="nav-link-li current">首页</a></li> </ul> </div> </nav> <div id="container" class="container clear"> <section class="sidebar clearfix"> <ul> <li><h3>基础</h3></li> <li> <p><a href="/xLua/public/v1/guide/index.html" class="sidebar-link">介绍</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/version.html" class="sidebar-link">更新记录</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/use.html" class="sidebar-link">商业案例</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/faq.html" class="sidebar-link current">FAQ</a></p> </li> <li><h3>教程</h3></li> <li> <p><a href="/xLua/public/v1/guide/tutorial.html" class="sidebar-link">从零开始</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/configure.html" class="sidebar-link">XLua的配置</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/api.html" class="sidebar-link">C# API</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/crtdel-3rd.html" class="sidebar-link">添加删除第三方库</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/gc-optimization.html" class="sidebar-link">GC优化指南</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/performance-analysis.html" class="sidebar-link">性能分析工具</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/signature.html" class="sidebar-link">数字签名</a></p> </li> <li><h3>其他</h3></li> <li> <p><a href="/xLua/public/v1/guide/hotfix.html" class="sidebar-link">热标识</a></p> </li> <li> <p><a href="/xLua/public/v1/guide/features.html" class="sidebar-link">特性</a></p> </li> </ul> </section> <article class="clearfix"> <h2 id="FAQ"><a href="#FAQ" class="headerlink" title="FAQ"></a>FAQ</h2><h3 id="xLua发布包怎么用?"><a href="#xLua发布包怎么用?" class="headerlink" title="xLua发布包怎么用?"></a>xLua发布包怎么用?</h3><p>xLua目前以zip包形式发布,在工程目录下解压即可。</p> <h3 id="xLua可以放别的目录吗?"><a href="#xLua可以放别的目录吗?" class="headerlink" title="xLua可以放别的目录吗?"></a>xLua可以放别的目录吗?</h3><p>可以,但生成代码目录需要配置一下(默认放<code>Assets\XLua\Gen</code>目录),具体可以看《XLua的配置.doc》的GenPath配置介绍。</p> <h3 id="lua源码只能以txt后缀?"><a href="#lua源码只能以txt后缀?" class="headerlink" title="lua源码只能以txt后缀?"></a>lua源码只能以txt后缀?</h3><p>什么后缀都可以。</p> <p>如果你想以<code>TextAsset</code>打包到安装包(比如放到<code>Resources</code>目录),Unity不认<code>lua</code>后缀,这是Unity的规则。</p> <p>如果你不打包到安装包,就没有后缀的限制:比如自行下载到某个目录(这也是热更的正确姿势),然后通过CustomLoader或者设置package.path去读这个目录。</p> <p>那为啥xLua本身带的lua源码(包括示例)为什么都是txt结尾呢?因为xLua本身就一个库,不含下载功能,也不方便运行时去某个地方下载代码,通过TextAsset是较简单的方式。</p> <h3 id="Plugins源码在哪里可以找到,怎么使用?"><a href="#Plugins源码在哪里可以找到,怎么使用?" class="headerlink" title="Plugins源码在哪里可以找到,怎么使用?"></a>Plugins源码在哪里可以找到,怎么使用?</h3><p>Plugins源码位于<code>xLua_Project_Root/build</code>下。</p> <p>源码编译依赖cmake,安装cmake后执行make_xxxx_yyyy.zz即可,xxxx代表平台,比如ios,android等,yyyy是要集成的虚拟机,有lua53和luajit两者,zz是后缀,windows下是bat,其它平台是sh。</p> <p>windows编译依赖Visual Studio 2015。</p> <p>android编译在linux下执行,依赖NDK,并且需要把脚本中ANDROID_NDK指向NDK的安装目录。</p> <p>ios和osx需要在mac下编译。</p> <h3 id="报类似“xlua-access-no-field-Hitfix0-Update”的错误怎么解决?"><a href="#报类似“xlua-access-no-field-Hitfix0-Update”的错误怎么解决?" class="headerlink" title="报类似“xlua.access, no field __Hitfix0_Update”的错误怎么解决?"></a>报类似“xlua.access, no field __Hitfix0_Update”的错误怎么解决?</h3><p>按<a href="hotfix.html">Hotfix操作指南</a>一步步操作。</p> <h3 id="报“please-install-the-Tools”"><a href="#报“please-install-the-Tools”" class="headerlink" title="报“please install the Tools”"></a>报“please install the Tools”</h3><p>没有把Tools安装到Assets平级目录,安装包,或者master下都能找到这个目录。</p> <h3 id="报“This-delegate-interface-must-add-to-CSharpCallLua-XXX”异常怎么解决?"><a href="#报“This-delegate-interface-must-add-to-CSharpCallLua-XXX”异常怎么解决?" class="headerlink" title="报“This delegate/interface must add to CSharpCallLua : XXX”异常怎么解决?"></a>报“This delegate/interface must add to CSharpCallLua : XXX”异常怎么解决?</h3><p>在编辑器下xLua不生成代码都可以运行,出现这种提示,要么是该类型没加CSharpCallLua,要么是加之前生成过代码,没重新执行生成。</p> <p>解决办法,确认XXX(类型名)加上CSharpCallLua后,清除代码后运行。</p> <h3 id="hotfix下怎么触发一个event"><a href="#hotfix下怎么触发一个event" class="headerlink" title="hotfix下怎么触发一个event"></a>hotfix下怎么触发一个event</h3><p>首先通过xlua.private_accessible开启私有成员访问。</p> <p>跟着通过对象的”&amp;事件名”字段调用delegate,例如self[‘&amp;MyEvent’](),其中MyEvent是事件名。</p> <h3 id="怎么对Unity-Coroutine的实现函数打补丁?"><a href="#怎么对Unity-Coroutine的实现函数打补丁?" class="headerlink" title="怎么对Unity Coroutine的实现函数打补丁?"></a>怎么对Unity Coroutine的实现函数打补丁?</h3><p>见<a href="hotfix.html">Hotfix操作指南</a>相应章节。</p> <h3 id="支持NGUI(或者UGUI-DOTween等等)么?"><a href="#支持NGUI(或者UGUI-DOTween等等)么?" class="headerlink" title="支持NGUI(或者UGUI/DOTween等等)么?"></a>支持NGUI(或者UGUI/DOTween等等)么?</h3><p>支持,xLua最主要的特性是让你原来用C#写的地方可以换成用lua写,你C#能用的插件,基本都能用。</p> <h3 id="如果需要调试,CustomLoader的filepath参数该如何处理?"><a href="#如果需要调试,CustomLoader的filepath参数该如何处理?" class="headerlink" title="如果需要调试,CustomLoader的filepath参数该如何处理?"></a>如果需要调试,CustomLoader的filepath参数该如何处理?</h3><p>lua里头调用require ‘a.b’时,CustomLoader会被调用,并传入字符串”a.b”,你需要理解这字符串,(从文件/内存/网络等)加载好lua文件,返回两个东西,第一个是调试器可以理解的路径,比如:a/b.lua,这个通过设置ref类型的filepath参数返回,第二个是UTF8格式的源码的字节流(byte[]),通过返回值返回。</p> <h3 id="什么是生成代码?"><a href="#什么是生成代码?" class="headerlink" title="什么是生成代码?"></a>什么是生成代码?</h3><p>xLua支持的lua和C#间交互技术之一,这种技术通过生成两者间的适配代码来实现交互,性能较好,是推荐的方式。</p> <p>另一种交互技术是反射,这种方式对安装包的影响更少,可以在性能要求不高或者对安装包大小很敏感的场景下使用。</p> <h3 id="改了接口后,之前生成的代码出现错误怎么办?"><a href="#改了接口后,之前生成的代码出现错误怎么办?" class="headerlink" title="改了接口后,之前生成的代码出现错误怎么办?"></a>改了接口后,之前生成的代码出现错误怎么办?</h3><p>清除掉生成代码(执行“Clear Generated Code”菜单,如果你重启过,会找不到这个菜单,这时你可以手动删除整个生成代码目录),等编译完成后重新生成。</p> <h3 id="应该什么时候生成代码?"><a href="#应该什么时候生成代码?" class="headerlink" title="应该什么时候生成代码?"></a>应该什么时候生成代码?</h3><p>开发期不建议生成代码,可以避免很多由于不一致导致的编译失败,以及生成代码本身的编译等待。</p> <p>build手机版本前必须执行生成代码,建议做成自动化的。</p> <p>做性能调优,性能测试前必须执行生成代码,因为生成和不生成性能的区别还是很大的。</p> <h3 id="CS名字空间下有所有C-API是不是很占内存?"><a href="#CS名字空间下有所有C-API是不是很占内存?" class="headerlink" title="CS名字空间下有所有C# API是不是很占内存?"></a>CS名字空间下有所有C# API是不是很占内存?</h3><p>由于用了lazyload,这个“有”只是个虚拟的概念,比如UnityEngine.GameObject,是访问第一次CS.UnityEngine.GameObject或者第一个实例往lua传送才加载该类型方法,属性等。</p> <h3 id="LuaCallSharp以及CSharpCallLua两种生成各在什么场景下用?"><a href="#LuaCallSharp以及CSharpCallLua两种生成各在什么场景下用?" class="headerlink" title="LuaCallSharp以及CSharpCallLua两种生成各在什么场景下用?"></a>LuaCallSharp以及CSharpCallLua两种生成各在什么场景下用?</h3><p>看调用者和被调用者,比如要在lua调用C#的GameObject.Find函数,或者调用gameobject的实例方法,属性等,GameObject类要加LuaCallSharp,而想把一个lua函数挂到UI回调,这是调用者是C#,被调用的是一个lua函数,所以回调声明的delegate要加CSharpCallLua。</p> <p>有时会比较迷惑人,比如<code>List&lt;int&gt;.Find(Predicate&lt;int&gt; match)</code>的调用,<code>List&lt;int&gt;</code>当然是加LuaCallSharp,而<code>Predicate&lt;int&gt;</code>却要加CSharpCallLua,因为match的调用者在C#,被调用的是一个lua函数。</p> <p>更无脑一点的方式是看到“This delegate/interface must add to CSharpCallLua : XXX”,就把XXX加到CSharpCallLua即可。</p> <h3 id="值类型传递会有gc-alloc么?"><a href="#值类型传递会有gc-alloc么?" class="headerlink" title="值类型传递会有gc alloc么?"></a>值类型传递会有gc alloc么?</h3><p>如果你使用的是delegate调用lua函数,或者用LuaTable、LuaFunction的无gc接口,或者数组的话,以下值类型都是没gc的:</p> <p>1、所有的基本值类型(所有整数,所有浮点数,decimal);</p> <p>2、所有的枚举类型;</p> <p>3、字段只包含值类型的struct,可嵌套其它只包含值类型struct;</p> <p>其中2、3需要把该类型加到GCOptimize。</p> <h3 id="反射在ios下可用吗?"><a href="#反射在ios下可用吗?" class="headerlink" title="反射在ios下可用吗?"></a>反射在ios下可用吗?</h3><p>ios下的限制有两个:1、没有jit;2、代码剪裁(stripping);</p> <p>对于C#通过delegate或者interface调用lua,如果不生成代码是用反射的emit,这依赖jit,所以这目前只在编辑器可用。</p> <p>对于lua调用C#,主要会被代码剪裁影响,这时你可以配置ReflectionUse(不要配LuaCallSharp),执行“Generate Code”,这时不会对该类生成封装代码,而是生成link.xml把该类配置为不剪裁。</p> <p>简而言之,除了CSharpCallLua是必须的(这类生成代码往往不多),LuaCallSharp生成都可以改为用反射。</p> <h3 id="支持泛化方法的调用么?"><a href="#支持泛化方法的调用么?" class="headerlink" title="支持泛化方法的调用么?"></a>支持泛化方法的调用么?</h3><p>不直接支持,但能调用到。如果是静态方法,可以自己写个封装来实例化泛化方法。</p> <p>如果是成员方法,xLua支持扩展方法,你可以添加一个扩展方法来实例化泛化方法。该扩展方法使用起来就和普通成员方法一样。</p> <figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="comment">// C#</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Button <span class="title">GetButton</span>(<span class="params"><span class="keyword">this</span> GameObject go</span>)</span></div><div class="line">&#123;</div><div class="line"> <span class="keyword">return</span> go.GetComponent&lt;Button&gt;();</div><div class="line">&#125;</div></pre></td></tr></table></figure> <figure class="highlight lua"><table><tr><td class="code"><pre><div class="line"><span class="comment">-- lua</span></div><div class="line"><span class="keyword">local</span> go = CS.UnityEngine.GameObject.Find(<span class="string">"button"</span>)</div><div class="line">go:GetButton().onClick:AddListener(<span class="function"><span class="keyword">function</span><span class="params">()</span></span></div><div class="line"> <span class="built_in">print</span>(<span class="string">'onClick'</span>)</div><div class="line"><span class="keyword">end</span>)</div></pre></td></tr></table></figure> <h3 id="支持lua调用C-重载函数吗?"><a href="#支持lua调用C-重载函数吗?" class="headerlink" title="支持lua调用C#重载函数吗?"></a>支持lua调用C#重载函数吗?</h3><p>支持,但没有C#端支持的那么完善,比如重载方法void Foo(int a)和void Foo(short a),由于int和short都对应lua的number,是没法根据参数判断调用的是哪个重载。这时你可以借助扩展方法来为其中一个起一个别名。</p> <h3 id="编辑器下运行正常,打包的时候生成代码报“没有某方法-属性-字段定义”怎么办?"><a href="#编辑器下运行正常,打包的时候生成代码报“没有某方法-属性-字段定义”怎么办?" class="headerlink" title="编辑器下运行正常,打包的时候生成代码报“没有某方法/属性/字段定义”怎么办?"></a>编辑器下运行正常,打包的时候生成代码报“没有某方法/属性/字段定义”怎么办?</h3><p>往往是由于该方法/属性/字段是扩在条件编译里头,只在UNITY_EDITOR下有效,这是可以通过把这方法/属性/字段加到黑名单来解决,加了之后要等编译完成后重新执行代码生成。</p> <h3 id="this-string-field-或者this-object-field-操作符重载为什么在lua无法访问?(比如Dictionary-lt-string-xxx-gt-Dictionary-lt-object-xxx-gt-在lua中无法通过dic-‘abc’-或者dic-abc检索值)"><a href="#this-string-field-或者this-object-field-操作符重载为什么在lua无法访问?(比如Dictionary-lt-string-xxx-gt-Dictionary-lt-object-xxx-gt-在lua中无法通过dic-‘abc’-或者dic-abc检索值)" class="headerlink" title="this[string field]或者this[object field]操作符重载为什么在lua无法访问?(比如Dictionary&lt;string, xxx&gt;, Dictionary&lt;object, xxx&gt;在lua中无法通过dic[‘abc’]或者dic.abc检索值)"></a>this[string field]或者this[object field]操作符重载为什么在lua无法访问?(比如<code>Dictionary&lt;string, xxx&gt;</code>, <code>Dictionary&lt;object, xxx&gt;</code>在lua中无法通过dic[‘abc’]或者dic.abc检索值)</h3><p>在2.1.5~2.1.6版本把这个特性去掉,因为:1、这个特性会导致基类定义的方法、属性、字段等无法访问(比如Animation无法访问到GetComponent方法);2、key为当前类某方法、属性、字段的名字的数据无法检索,比如Dictionary类型,dic[‘TryGetValue’]返回的是一个函数,指向Dictionary的TryGetValue方法。</p> <p>建议直接方法该操作符的等效方法,比如Dictionary的TryGetValue,如果该方法没有提供,可以在C#那通过Extension method封装一个使用。</p> <h3 id="有的Unity对象,在C-为null,在lua为啥不为nil呢?比如一个已经Destroy的GameObject"><a href="#有的Unity对象,在C-为null,在lua为啥不为nil呢?比如一个已经Destroy的GameObject" class="headerlink" title="有的Unity对象,在C#为null,在lua为啥不为nil呢?比如一个已经Destroy的GameObject"></a>有的Unity对象,在C#为null,在lua为啥不为nil呢?比如一个已经Destroy的GameObject</h3><p>其实那C#对象并不为null,是UnityEngine.Object重载的==操作符,当一个对象被Destroy,未初始化等情况,obj == null返回true,但这C#对象并不为null,可以通过System.Object.ReferenceEquals(null, obj)来验证下。</p> <p>对应这种情况,可以为UnityEngine.Object写一个扩展方法:</p> <figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">[<span class="meta">LuaCallCSharp</span>]</div><div class="line">[<span class="meta">ReflectionUse</span>]</div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title">UnityEngineObjectExtention</span></div><div class="line">&#123;</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">bool</span> <span class="title">IsNull</span>(<span class="params"><span class="keyword">this</span> UnityEngine.Object o</span>) <span class="comment">// 或者名字叫IsDestroyed等等</span></span></div><div class="line"> &#123;</div><div class="line"> <span class="keyword">return</span> o == <span class="literal">null</span>;</div><div class="line"> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure> <p>然后在lua那你对所有UnityEngine.Object实例都使用IsNull判断</p> <figure class="highlight lua"><table><tr><td class="code"><pre><div class="line"><span class="built_in">print</span>(go:GetComponent(<span class="string">'Animator'</span>):IsNull())</div></pre></td></tr></table></figure> <h3 id="泛型实例怎么构造"><a href="#泛型实例怎么构造" class="headerlink" title="泛型实例怎么构造"></a>泛型实例怎么构造</h3><p>涉及的类型都在mscorlib,Assembly-CSharp程序集的话,泛型实例的构造和普通类型是一样的,都是CS.namespace.typename(),可能比较特殊的是typename的表达,泛型实例的typename的表达包含了标识符非法符号,最后一部分要换成[“typename”],以<code>List&lt;string&gt;</code>为例</p> <figure class="highlight lua"><table><tr><td class="code"><pre><div class="line"><span class="keyword">local</span> lst = CS.System.Collections.Generic[<span class="string">"List`1[System.String]"</span>]()</div></pre></td></tr></table></figure> <p>如果某个泛型实例的typename不确定,可以在C#测打印下typeof(不确定的类型).ToString()</p> <p>如果涉及mscorlib,Assembly-CSharp程序集之外的类型的话,可以用C#的反射来做:</p> <figure class="highlight lua"><table><tr><td class="code"><pre><div class="line"><span class="keyword">local</span> dic = CS.System.Activator.CreateInstance(CS.System.Type.GetType(<span class="string">'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[UnityEngine.Vector3, UnityEngine]],mscorlib'</span>))</div><div class="line">dic:Add(<span class="string">'a'</span>, CS.UnityEngine.Vector3(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</div><div class="line"><span class="built_in">print</span>(dic:TryGetValue(<span class="string">'a'</span>))</div></pre></td></tr></table></figure> <h3 id="调用LuaEnv-Dispose时,报“try-to-dispose-a-LuaEnv-with-C-callback-”错是什么原因?"><a href="#调用LuaEnv-Dispose时,报“try-to-dispose-a-LuaEnv-with-C-callback-”错是什么原因?" class="headerlink" title="调用LuaEnv.Dispose时,报“try to dispose a LuaEnv with C# callback!”错是什么原因?"></a>调用LuaEnv.Dispose时,报“try to dispose a LuaEnv with C# callback!”错是什么原因?</h3><p>这是由于C#还存在指向lua虚拟机里头某个函数的delegate,为了防止业务在虚拟机释放后调用这些无效(因为其引用的lua函数所在虚拟机都释放了)delegate导致的异常甚至崩溃,做了这个检查。</p> <p>怎么解决?释放这些delegate即可,所谓释放,在C#中,就是没有引用:</p> <p>你是在C#通过LuaTable.Get获取并保存到对象成员,赋值该成员为null;</p> <p>你是在lua那把lua函数注册到一些事件事件回调,反注册这些回调;</p> <p>如果你是通过xlua.hotfix(class, method, func)注入到C#,则通过xlua.hotfix(class, method, nil)删除;</p> <p>要注意以上操作在Dispose之前完成。</p> <h3 id="C-参数(或字段)类型是object时,传递整数默认是以long类型传递,如何指明其它类型?比如int"><a href="#C-参数(或字段)类型是object时,传递整数默认是以long类型传递,如何指明其它类型?比如int" class="headerlink" title="C#参数(或字段)类型是object时,传递整数默认是以long类型传递,如何指明其它类型?比如int"></a>C#参数(或字段)类型是object时,传递整数默认是以long类型传递,如何指明其它类型?比如int</h3><p>看<a href="https://github.com/Tencent/xLua/blob/master/Assets/XLua/Examples/11_RawObject/RawObjectTest.cs">例子11</a></p> <div class="footer"> 发现错误?想参与编辑? <a href="https://github.com/Tencent/xLua/tree/master/docs/source/src/v1/guide/faq.md" target="_blank"> 在 Github 上编辑此页! </a> </div> </article> <div class="sub-nav hiden-in-phone"> <dl id="sub-nav"> <dt>本文内容</dt> <dd v-for="(ele, index) in sub_nav"> <a v-bind:href="ele.href">{{ ele.name }}</a> </dd> </dl> </div> </div> <footer> <div> <p>© Copyright 2017 Tencent All Rights Reserved</p> <p>Tencent 2017</p> </div> </footer> <script> var vm = new Vue({ el : '#container', data: { sub_nav : [ ] }, created:function(){ var obj = []; $("article h3").each(function(){ obj.push({name : $(this).find("a").attr("title") , href : "#"+$(this).attr("id") }); }); this.sub_nav = obj; } }); var isShow = false; $("nav").on("click","#btn-menu" , function(){ if(!isShow){ if($(document).scrollTop() > $(".sidebar").height() - 100){ $('html, body').animate({scrollTop:0} , 300, "swing",function(){ $(".sidebar").fadeIn(); $(".container").animate({"left" : "15rem"}, 500,"swing"); }); }else{ $(".sidebar").fadeIn(); $(".container").animate({"left" : "15rem"}, 500,"swing"); } }else{ $(".sidebar").fadeOut(); $(".container").animate({"left" : "0rem"}, 500,"swing"); } isShow = !isShow; }); $(".container").on("click" , "article" , function(){ if(isShow){ $(".sidebar").fadeOut(); $(".container").animate({"left" : "0rem"}, 500,"swing"); isShow = false; } }); </script> </body> </html>
xLua/docs/public/v1/guide/faq.html/0
{ "file_path": "xLua/docs/public/v1/guide/faq.html", "repo_id": "xLua", "token_count": 15152 }
1,949
module.exports = function(hljs) { var KEYWORDS = { keyword: // Normal keywords. 'abstract as base bool break byte case catch char checked const continue decimal ' + 'default delegate do double enum event explicit extern finally fixed float ' + 'for foreach goto if implicit in int interface internal is lock long nameof ' + 'object operator out override params private protected public readonly ref sbyte ' + 'sealed short sizeof stackalloc static string struct switch this try typeof ' + 'uint ulong unchecked unsafe ushort using virtual void volatile while ' + // Contextual keywords. 'add alias ascending async await by descending dynamic equals from get global group into join ' + 'let on orderby partial remove select set value var where yield', literal: 'null false true' }; var VERBATIM_STRING = { className: 'string', begin: '@"', end: '"', contains: [{begin: '""'}] }; var VERBATIM_STRING_NO_LF = hljs.inherit(VERBATIM_STRING, {illegal: /\n/}); var SUBST = { className: 'subst', begin: '{', end: '}', keywords: KEYWORDS }; var SUBST_NO_LF = hljs.inherit(SUBST, {illegal: /\n/}); var INTERPOLATED_STRING = { className: 'string', begin: /\$"/, end: '"', illegal: /\n/, contains: [{begin: '{{'}, {begin: '}}'}, hljs.BACKSLASH_ESCAPE, SUBST_NO_LF] }; var INTERPOLATED_VERBATIM_STRING = { className: 'string', begin: /\$@"/, end: '"', contains: [{begin: '{{'}, {begin: '}}'}, {begin: '""'}, SUBST] }; var INTERPOLATED_VERBATIM_STRING_NO_LF = hljs.inherit(INTERPOLATED_VERBATIM_STRING, { illegal: /\n/, contains: [{begin: '{{'}, {begin: '}}'}, {begin: '""'}, SUBST_NO_LF] }); SUBST.contains = [ INTERPOLATED_VERBATIM_STRING, INTERPOLATED_STRING, VERBATIM_STRING, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_NUMBER_MODE, hljs.C_BLOCK_COMMENT_MODE ]; SUBST_NO_LF.contains = [ INTERPOLATED_VERBATIM_STRING_NO_LF, INTERPOLATED_STRING, VERBATIM_STRING_NO_LF, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_NUMBER_MODE, hljs.inherit(hljs.C_BLOCK_COMMENT_MODE, {illegal: /\n/}) ]; var STRING = { variants: [ INTERPOLATED_VERBATIM_STRING, INTERPOLATED_STRING, VERBATIM_STRING, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ] }; var TYPE_IDENT_RE = hljs.IDENT_RE + '(<' + hljs.IDENT_RE + '(\\s*,\\s*' + hljs.IDENT_RE + ')*>)?(\\[\\])?'; return { aliases: ['csharp'], keywords: KEYWORDS, illegal: /::/, contains: [ hljs.COMMENT( '///', '$', { returnBegin: true, contains: [ { className: 'doctag', variants: [ { begin: '///', relevance: 0 }, { begin: '<!--|-->' }, { begin: '</?', end: '>' } ] } ] } ), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, { className: 'meta', begin: '#', end: '$', keywords: { 'meta-keyword': 'if else elif endif define undef warning error line region endregion pragma checksum' } }, STRING, hljs.C_NUMBER_MODE, { beginKeywords: 'class interface', end: /[{;=]/, illegal: /[^\s:,]/, contains: [ hljs.TITLE_MODE, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, { beginKeywords: 'namespace', end: /[{;=]/, illegal: /[^\s:]/, contains: [ hljs.inherit(hljs.TITLE_MODE, {begin: '[a-zA-Z](\\.?\\w)*'}), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, { // [Attributes("")] className: 'meta', begin: '^\\s*\\[', excludeBegin: true, end: '\\]', excludeEnd: true, contains: [ {className: 'meta-string', begin: /"/, end: /"/} ] }, { // Expression keywords prevent 'keyword Name(...)' from being // recognized as a function definition beginKeywords: 'new return throw await else', relevance: 0 }, { className: 'function', begin: '(' + TYPE_IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/, excludeEnd: true, keywords: KEYWORDS, contains: [ { begin: hljs.IDENT_RE + '\\s*\\(', returnBegin: true, contains: [hljs.TITLE_MODE], relevance: 0 }, { className: 'params', begin: /\(/, end: /\)/, excludeBegin: true, excludeEnd: true, keywords: KEYWORDS, relevance: 0, contains: [ STRING, hljs.C_NUMBER_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] } ] }; }
xLua/docs/source/patch/highlight.js/lib/languages/cs.js/0
{ "file_path": "xLua/docs/source/patch/highlight.js/lib/languages/cs.js", "repo_id": "xLua", "token_count": 2672 }
1,950
site_description: "XLua" github: https://github.com/Tencent/xLua modify_github: https://github.com/Tencent/xLua/tree/master/docs/source/src/ copyright: © Copyright 2017 Tencent All Rights Reserved copyright_desc: Tencent 2017
xLua/docs/source/themes/catlib/_config.yml/0
{ "file_path": "xLua/docs/source/themes/catlib/_config.yml", "repo_id": "xLua", "token_count": 71 }
1,951
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform sampler2D colorTexture; uniform vec2 enabled; out vec4 fragColor; void main() { int size = 3; float separation = 4.0; float threshold = 0.6; float amount = 0.6; if (enabled.x != 1 || size <= 0) { fragColor = vec4(0); return; } vec2 texSize = textureSize(colorTexture, 0).xy; vec4 result = vec4(0.0); vec4 color = vec4(0.0); float value = 0.0; float count = 0.0; for (int i = -size; i <= size; ++i) { for (int j = -size; j <= size; ++j) { color = texture ( colorTexture , (vec2(i, j) * separation + gl_FragCoord.xy) / texSize ); value = max(color.r, max(color.g, color.b)); if (value < threshold) { color = vec4(0.0); } result += color; count += 1.0; } } result /= count; fragColor = mix(vec4(0.0), result, amount); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/bloom.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/bloom.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 424 }
0
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform struct { vec4 diffuse ; } p3d_Material; out vec4 fragColor; void main() { fragColor = p3d_Material.diffuse; }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/material-diffuse.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/material-diffuse.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 78 }
1
/* (C) 2019 David Lettier lettier.com */ #version 150 #define NUM_SAMPLES 8 #define NUM_NOISE 4 uniform mat4 lensProjection; uniform vec3 samples[NUM_SAMPLES]; uniform vec3 noise[NUM_NOISE]; uniform sampler2D positionTexture; uniform sampler2D normalTexture; uniform vec2 enabled; out vec4 fragColor; void main() { float radius = 0.6; float bias = 0.005; float magnitude = 1.1; float contrast = 1.1; fragColor = vec4(1); if (enabled.x != 1) { return; } vec2 texSize = textureSize(positionTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; vec4 position = texture(positionTexture, texCoord); if (position.a <= 0) { return; } vec3 normal = normalize(texture(normalTexture, texCoord).xyz); int noiseS = int(sqrt(NUM_NOISE)); int noiseX = int(gl_FragCoord.x - 0.5) % noiseS; int noiseY = int(gl_FragCoord.y - 0.5) % noiseS; vec3 random = noise[noiseX + (noiseY * noiseS)]; vec3 tangent = normalize(random - normal * dot(random, normal)); vec3 binormal = cross(normal, tangent); mat3 tbn = mat3(tangent, binormal, normal); float occlusion = NUM_SAMPLES; for (int i = 0; i < NUM_SAMPLES; ++i) { vec3 samplePosition = tbn * samples[i]; samplePosition = position.xyz + samplePosition * radius; vec4 offsetUV = vec4(samplePosition, 1.0); offsetUV = lensProjection * offsetUV; offsetUV.xyz /= offsetUV.w; offsetUV.xy = offsetUV.xy * 0.5 + 0.5; // Config.prc // gl-coordinate-system default // textures-auto-power-2 1 // textures-power-2 down vec4 offsetPosition = texture(positionTexture, offsetUV.xy); float occluded = 0; if (samplePosition.y + bias <= offsetPosition.y) { occluded = 0; } else { occluded = 1; } float intensity = smoothstep ( 0 , 1 , radius / abs(position.y - offsetPosition.y) ); occluded *= intensity; occlusion -= occluded; } occlusion /= NUM_SAMPLES; occlusion = pow(occlusion, magnitude); occlusion = contrast * (occlusion - 0.5) + 0.5; fragColor = vec4(vec3(occlusion), position.a); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/ssao.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/ssao.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 902 }
2
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Outlining | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Outlining | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Outlining | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="flow-mapping.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="depth-of-field.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="outlining">Outlining</h2> <p align="center"> <img src="https://i.imgur.com/EKaZRkR.gif" alt="Outlined Scene" title="Outlined Scene"> </p> <p>Outlining your scene's geometry can give your game a distinctive look, reminiscent of comic books and cartoons.</p> <h3 id="discontinuities">Discontinuities</h3> <p>The process of outlining is the process of finding and labeling discontinuities or differences. Every time you find what you consider a significant difference, you mark it with your line color. As you go about labeling or coloring in the differences, outlines or edges will start to form.</p> <p>Where you choose to search for the discontinuities is up to you. It could be the diffuse colors in your scene, the normals of your models, the depth buffer, or some other scene related data.</p> <p>The demo uses the interpolated vertex positions to render the outlines. However, a less straightforward but more typical way is to use both the scene's normals and depth buffer values to construct the outlines.</p> <h3 id="vertex-positions">Vertex Positions</h3> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a><span class="co">// ...</span></span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a>uniform sampler2D positionTexture;</span> <span id="cb1-4"><a href="#cb1-4"></a></span> <span id="cb1-5"><a href="#cb1-5"></a><span class="co">// ...</span></span></code></pre></div> <p>Like SSAO, you'll need the vertex positions in view space. Referrer back to <a href="ssao.html#vertex-positions">SSAO</a> for details.</p> <h3 id="scene-colors">Scene Colors</h3> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a><span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a>uniform sampler2D colorTexture;</span> <span id="cb2-4"><a href="#cb2-4"></a></span> <span id="cb2-5"><a href="#cb2-5"></a><span class="co">// ...</span></span></code></pre></div> <p>The demo darkens the colors of the scene where there's an outline. This tends to look nicer than a constant color since it provides some color variation to the edges.</p> <h3 id="parameters">Parameters</h3> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a> <span class="dt">float</span> minSeparation = <span class="fl">1.0</span>;</span> <span id="cb3-4"><a href="#cb3-4"></a> <span class="dt">float</span> maxSeparation = <span class="fl">3.0</span>;</span> <span id="cb3-5"><a href="#cb3-5"></a> <span class="dt">float</span> minDistance = <span class="fl">0.5</span>;</span> <span id="cb3-6"><a href="#cb3-6"></a> <span class="dt">float</span> maxDistance = <span class="fl">2.0</span>;</span> <span id="cb3-7"><a href="#cb3-7"></a> <span class="dt">int</span> size = <span class="dv">1</span>;</span> <span id="cb3-8"><a href="#cb3-8"></a> vec3 colorModifier = vec3(<span class="fl">0.324</span>, <span class="fl">0.063</span>, <span class="fl">0.099</span>);</span> <span id="cb3-9"><a href="#cb3-9"></a></span> <span id="cb3-10"><a href="#cb3-10"></a> <span class="co">// ...</span></span></code></pre></div> <p>The min and max separation parameters control the thickness of the outline depending on the fragment's distance from the camera or depth. The min and max distance control the significance of any changes found. The <code>size</code> parameter controls the constant thickness of the line no matter the fragment's position. The outline color is based on <code>colorModifier</code> and the current fragment's color.</p> <h3 id="fragment-position">Fragment Position</h3> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span> <span id="cb4-2"><a href="#cb4-2"></a></span> <span id="cb4-3"><a href="#cb4-3"></a> vec2 texSize = textureSize(colorTexture, <span class="dv">0</span>).xy;</span> <span id="cb4-4"><a href="#cb4-4"></a> vec2 fragCoord = gl_FragCoord.xy;</span> <span id="cb4-5"><a href="#cb4-5"></a> vec2 texCoord = fragCoord / texSize;</span> <span id="cb4-6"><a href="#cb4-6"></a></span> <span id="cb4-7"><a href="#cb4-7"></a> vec4 position = texture(positionTexture, texCoord);</span> <span id="cb4-8"><a href="#cb4-8"></a></span> <span id="cb4-9"><a href="#cb4-9"></a> <span class="co">// ...</span></span></code></pre></div> <p>Sample the position texture for the current fragment's position in the scene. Recall that the position texture is just a screen shaped quad making the UV coordinate the current fragment's screen coordinate divided by the dimensions of the screen.</p> <h3 id="fragment-depth">Fragment Depth</h3> <div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a> <span class="co">// ...</span></span> <span id="cb5-2"><a href="#cb5-2"></a></span> <span id="cb5-3"><a href="#cb5-3"></a> <span class="dt">float</span> depth =</span> <span id="cb5-4"><a href="#cb5-4"></a> clamp</span> <span id="cb5-5"><a href="#cb5-5"></a> ( <span class="fl">1.0</span></span> <span id="cb5-6"><a href="#cb5-6"></a> - ( (far - position.y)</span> <span id="cb5-7"><a href="#cb5-7"></a> / (far - near)</span> <span id="cb5-8"><a href="#cb5-8"></a> )</span> <span id="cb5-9"><a href="#cb5-9"></a> , <span class="fl">0.0</span></span> <span id="cb5-10"><a href="#cb5-10"></a> , <span class="fl">1.0</span></span> <span id="cb5-11"><a href="#cb5-11"></a> );</span> <span id="cb5-12"><a href="#cb5-12"></a></span> <span id="cb5-13"><a href="#cb5-13"></a> <span class="dt">float</span> separation = mix(maxSeparation, minSeparation, depth);</span> <span id="cb5-14"><a href="#cb5-14"></a></span> <span id="cb5-15"><a href="#cb5-15"></a> <span class="co">// ...</span></span></code></pre></div> <p>The fragment's depth ranges from zero to one. When the fragment's view-space y coordinate matches the far clipping plane, the depth is one. When the fragment's view-space y coordinate matches the near clipping plane, the depth is zero. In other words, the depth ranges from zero at the near clipping plane all the way up to one at the far clipping plane.</p> <div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a> <span class="co">// ...</span></span> <span id="cb6-2"><a href="#cb6-2"></a></span> <span id="cb6-3"><a href="#cb6-3"></a> <span class="dt">float</span> separation = mix(maxSeparation, minSeparation, depth);</span> <span id="cb6-4"><a href="#cb6-4"></a></span> <span id="cb6-5"><a href="#cb6-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Converting the position to a depth value isn't necessary but it allows you to vary the thickness of the outline based on how far away the fragment is from the camera. Far away fragments get a thinner line while nearer fragments get a thicker outline. This tends to look nicer than a constant thickness since it gives depth to the outline.</p> <h3 id="finding-the-discontinuities">Finding The Discontinuities</h3> <p align="center"> <img src="https://i.imgur.com/xAMRGhn.gif" alt="Edge Finding" title="Edge Finding"> </p> <div class="sourceCode" id="cb7"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb7-1"><a href="#cb7-1"></a> <span class="co">// ...</span></span> <span id="cb7-2"><a href="#cb7-2"></a></span> <span id="cb7-3"><a href="#cb7-3"></a> <span class="dt">float</span> mx = <span class="fl">0.0</span>;</span> <span id="cb7-4"><a href="#cb7-4"></a></span> <span id="cb7-5"><a href="#cb7-5"></a> <span class="cf">for</span> (<span class="dt">int</span> i = -size; i &lt;= size; ++i) {</span> <span id="cb7-6"><a href="#cb7-6"></a> <span class="cf">for</span> (<span class="dt">int</span> j = -size; j &lt;= size; ++j) {</span> <span id="cb7-7"><a href="#cb7-7"></a> <span class="co">// ...</span></span> <span id="cb7-8"><a href="#cb7-8"></a> }</span> <span id="cb7-9"><a href="#cb7-9"></a> }</span> <span id="cb7-10"><a href="#cb7-10"></a></span> <span id="cb7-11"><a href="#cb7-11"></a> <span class="co">// ...</span></span></code></pre></div> <p>Now that you have the current fragment's position, loop through an i by j grid or window surrounding the current fragment.</p> <div class="sourceCode" id="cb8"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb8-1"><a href="#cb8-1"></a> <span class="co">// ...</span></span> <span id="cb8-2"><a href="#cb8-2"></a></span> <span id="cb8-3"><a href="#cb8-3"></a> texCoord =</span> <span id="cb8-4"><a href="#cb8-4"></a> ( fragCoord</span> <span id="cb8-5"><a href="#cb8-5"></a> + (vec2(i, j) * separation)</span> <span id="cb8-6"><a href="#cb8-6"></a> )</span> <span id="cb8-7"><a href="#cb8-7"></a> / texSize;</span> <span id="cb8-8"><a href="#cb8-8"></a></span> <span id="cb8-9"><a href="#cb8-9"></a> vec4 positionTemp =</span> <span id="cb8-10"><a href="#cb8-10"></a> texture</span> <span id="cb8-11"><a href="#cb8-11"></a> ( positionTexture</span> <span id="cb8-12"><a href="#cb8-12"></a> , texCoord</span> <span id="cb8-13"><a href="#cb8-13"></a> );</span> <span id="cb8-14"><a href="#cb8-14"></a></span> <span id="cb8-15"><a href="#cb8-15"></a> mx = max(mx, abs(position.y - positionTemp.y));</span> <span id="cb8-16"><a href="#cb8-16"></a></span> <span id="cb8-17"><a href="#cb8-17"></a> <span class="co">// ...</span></span></code></pre></div> <p>With each iteration, find the biggest distance between this fragment's and the surrounding fragments' positions.</p> <p align="center"> <img src="https://i.imgur.com/idDZr62.png" alt="smoothstep" title="smoothstep"> </p> <div class="sourceCode" id="cb9"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb9-1"><a href="#cb9-1"></a> <span class="co">// ...</span></span> <span id="cb9-2"><a href="#cb9-2"></a></span> <span id="cb9-3"><a href="#cb9-3"></a> <span class="dt">float</span> diff = smoothstep(minDistance, maxDistance, mx);</span> <span id="cb9-4"><a href="#cb9-4"></a></span> <span id="cb9-5"><a href="#cb9-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Calculate the significance of any difference discovered using the <code>minDistance</code>, <code>maxDistance</code>, and <code>smoothstep</code>. <code>smoothstep</code> returns values from zero to one. The <code>minDistance</code> is the left-most edge. Any difference less than the minimum distance will be zero. The <code>maxDistance</code> is the right-most edge. Any difference greater than the maximum distance will be one. For distances between the edges, the difference will be between zero and one. These values are interpolated along a s-shaped curve.</p> <h3 id="line-color">Line Color</h3> <div class="sourceCode" id="cb10"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb10-1"><a href="#cb10-1"></a> <span class="co">// ...</span></span> <span id="cb10-2"><a href="#cb10-2"></a></span> <span id="cb10-3"><a href="#cb10-3"></a> vec3 lineColor = texture(colorTexture, texCoord).rgb * colorModifier;</span> <span id="cb10-4"><a href="#cb10-4"></a></span> <span id="cb10-5"><a href="#cb10-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>The line color is the current fragment color either darkened or lightened.</p> <h3 id="fragment-color">Fragment Color</h3> <p align="center"> <img src="https://i.imgur.com/yWNdPZe.gif" alt="Outlines" title="Outlines"> </p> <div class="sourceCode" id="cb11"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb11-1"><a href="#cb11-1"></a> <span class="co">// ...</span></span> <span id="cb11-2"><a href="#cb11-2"></a></span> <span id="cb11-3"><a href="#cb11-3"></a> fragColor.rgb = vec4(lineColor, diff);</span> <span id="cb11-4"><a href="#cb11-4"></a></span> <span id="cb11-5"><a href="#cb11-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>The fragment's RGB color is the <code>lineColor</code> and its alpha channel is <code>diff</code>.</p> <h3 id="sketchy">Sketchy</h3> <p align="center"> <img src="https://i.imgur.com/FRBkSm1.gif" alt="Sketchy Outline" title="Sketchy Outline"> </p> <p>For a sketchy outline, you can distort the UV coordinates used to sample the position vectors.</p> <p align="center"> <img src="https://i.imgur.com/qgZNtnN.png" alt="Outline Noise" title="Outline Noise"> </p> <div class="sourceCode" id="cb12"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb12-1"><a href="#cb12-1"></a><span class="co">// ...</span></span> <span id="cb12-2"><a href="#cb12-2"></a></span> <span id="cb12-3"><a href="#cb12-3"></a>uniform sampler2D noiseTexture;</span> <span id="cb12-4"><a href="#cb12-4"></a></span> <span id="cb12-5"><a href="#cb12-5"></a><span class="co">// ...</span></span></code></pre></div> <p>Start by creating a RGB noise texture. A good size is either 128 by 128 or 512 by 512. Be sure to blur it and make it tileable. This will produce a nice wavy, inky outline.</p> <div class="sourceCode" id="cb13"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb13-1"><a href="#cb13-1"></a> <span class="co">// ...</span></span> <span id="cb13-2"><a href="#cb13-2"></a></span> <span id="cb13-3"><a href="#cb13-3"></a> <span class="dt">float</span> noiseScale = <span class="fl">10.0</span>;</span> <span id="cb13-4"><a href="#cb13-4"></a></span> <span id="cb13-5"><a href="#cb13-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>The <code>noiseScale</code> parameter controls how distorted the outline is. The bigger the <code>noiseScale</code>, the sketchier the line.</p> <div class="sourceCode" id="cb14"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb14-1"><a href="#cb14-1"></a> <span class="co">// ...</span></span> <span id="cb14-2"><a href="#cb14-2"></a></span> <span id="cb14-3"><a href="#cb14-3"></a> vec2 fragCoord = gl_FragCoord.xy;</span> <span id="cb14-4"><a href="#cb14-4"></a></span> <span id="cb14-5"><a href="#cb14-5"></a> vec2 noise = texture(noiseTexture, fragCoord / textureSize(noiseTexture, <span class="dv">0</span>).xy).rb;</span> <span id="cb14-6"><a href="#cb14-6"></a> noise = noise * <span class="fl">2.0</span> - <span class="fl">1.0</span>;</span> <span id="cb14-7"><a href="#cb14-7"></a> noise *= noiseScale;</span> <span id="cb14-8"><a href="#cb14-8"></a></span> <span id="cb14-9"><a href="#cb14-9"></a> <span class="co">// ...</span></span></code></pre></div> <p>Sample the noise texture using the current screen/fragment position and the size of the noise texture. Since you're distorting the UV coordinates used to sample the position vectors, you'll only need two of the three color channels. Map the two color channels from <code>[0, 1]</code> to <code>[-1, 1]</code>. Finally, scale the noise by the scale chosen earlier.</p> <div class="sourceCode" id="cb15"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb15-1"><a href="#cb15-1"></a> <span class="co">// ...</span></span> <span id="cb15-2"><a href="#cb15-2"></a></span> <span id="cb15-3"><a href="#cb15-3"></a> vec2 texSize = textureSize(colorTexture, <span class="dv">0</span>).xy;</span> <span id="cb15-4"><a href="#cb15-4"></a> vec2 texCoord = (fragCoord - noise) / texSize;</span> <span id="cb15-5"><a href="#cb15-5"></a></span> <span id="cb15-6"><a href="#cb15-6"></a> vec4 position = texture(positionTexture, texCoord);</span> <span id="cb15-7"><a href="#cb15-7"></a></span> <span id="cb15-8"><a href="#cb15-8"></a> <span class="co">// ...</span></span></code></pre></div> <p>When sampling the current position, subtract the noise vector from the current fragment's coordinates.</p> <p align="center"> <img src="https://i.imgur.com/wk43ybP.png" alt="Squiggly Outline" title="Squiggly Outline"> </p> <p>You could instead add it to the current fragment's coordinates which will create more of a squiggly line that loosely follows the geometry.</p> <div class="sourceCode" id="cb16"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb16-1"><a href="#cb16-1"></a> <span class="co">// ...</span></span> <span id="cb16-2"><a href="#cb16-2"></a></span> <span id="cb16-3"><a href="#cb16-3"></a> texCoord =</span> <span id="cb16-4"><a href="#cb16-4"></a> (vec2(i, j) * separation + fragCoord + noise)</span> <span id="cb16-5"><a href="#cb16-5"></a> / texSize;</span> <span id="cb16-6"><a href="#cb16-6"></a></span> <span id="cb16-7"><a href="#cb16-7"></a> <span class="co">// ...</span></span> <span id="cb16-8"><a href="#cb16-8"></a></span> <span id="cb16-9"><a href="#cb16-9"></a> vec4 positionTemp =</span> <span id="cb16-10"><a href="#cb16-10"></a> texture</span> <span id="cb16-11"><a href="#cb16-11"></a> ( positionTexture</span> <span id="cb16-12"><a href="#cb16-12"></a> , texCoord</span> <span id="cb16-13"><a href="#cb16-13"></a> );</span> <span id="cb16-14"><a href="#cb16-14"></a></span> <span id="cb16-15"><a href="#cb16-15"></a> <span class="co">// ...</span></span></code></pre></div> <p>When sampling the surrounding positions inside the loop, add the noise vector to the current fragment's coordinates. The rest of the calculations are the same.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/base.vert" target="_blank" rel="noopener noreferrer">base.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/position.frag" target="_blank" rel="noopener noreferrer">position.frag</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/outline.frag" target="_blank" rel="noopener noreferrer">outline.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="flow-mapping.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="depth-of-field.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/outlining.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/outlining.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 9561 }
3
[:arrow_backward:](fog.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](bloom.md) # 3D Game Shaders For Beginners ## Blur <p align="center"> <img src="https://i.imgur.com/b5vw2AJ.gif" alt="Kuwahara Filter" title="Kuwahara Filter"> </p> The need to blur this or that can come up quite often as you try to obtain a particular look or perform some technique like motion blur. Below are just some of ways you can blur your game's imagery. ### Box Blur <p align="center"> <img src="https://i.imgur.com/uaXC1JM.gif" alt="Box Blur" title="Box Blur"> </p> The box blur or mean filter algorithm is a simple to implement blurring effect. It's fast and gets the job done. If you need more finesse, you can upgrade to a Gaussian blur. ```c // ... vec2 texSize = textureSize(colorTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; int size = int(parameters.x); if (size <= 0) { fragColor = texture(colorTexture, texCoord); return; } // ... ``` The `size` parameter controls how blurry the result is. If the `size` is zero or less, return the fragment untouched. ```c // ... float separation = parameters.y; separation = max(separation, 1); // ... ``` The `separation` parameter spreads out the blur without having to sample additional fragments. `separation` ranges from one to infinity. <p align="center"> <img src="https://i.imgur.com/bRw0OkX.png" alt="Blur Kernel" title="Blur Kernel"> </p> ```c // ... for (int i = -size; i <= size; ++i) { for (int j = -size; j <= size; ++j) { // ... } } // ... ``` Like the [outlining](outlining.md) technique, the box blur technique uses a kernel/matrix/window centered around the current fragment. The size of the window is `size * 2 + 1` by `size * 2 + 1`. So for example, with a `size` setting of two, the window uses `(2 * 2 + 1)^2 = 25` samples per fragment. ```c // ... fragColor += texture ( colorTexture , ( gl_FragCoord.xy + (vec2(i, j) * separation) ) / texSize ); // ... ``` To compute the mean or average of the samples in the window, start by loop through the window, adding up each color vector. ```c // ... fragColor /= pow(size * 2 + 1, 2); // ... ``` To finish computing the mean, divide the sum of the colors sampled by the number of samples taken. The final fragment color is the mean or average of the fragments sampled inside the window. ### Median Filter <p align="center"> <img src="https://i.imgur.com/T1nEEn3.gif" alt="Median Filter" title="Median Filter"> </p> The box blur uses the mean color of the samples taken. The median filter uses the median color of the samples taken. By using the median instead of the mean, the edges in the image are preserved—meaning the edges stay nice and crisp. For example, look at the windows in the box blurred image versus the median filtered image. Unfortunately, finding the median can be slower than finding the mean. You could sort the values and choose the middle one but that would take at least quasilinear time. There is a technique to find the median in linear time but it can be quite awkward inside a shader. The numerical approach below approximates the median in linear time. How well it approximates the median can be controlled. <p align="center"> <img src="https://i.imgur.com/AnbzUmN.png" alt="Painterly" title="Painterly"> </p> At lower quality approximations, you end up with a nice [painterly](https://en.wikipedia.org/wiki/Painterliness) look. ```c // ... #define MAX_SIZE 4 #define MAX_KERNEL_SIZE ((MAX_SIZE * 2 + 1) * (MAX_SIZE * 2 + 1)) #define MAX_BINS_SIZE 100 // ... ``` These are the hard limits for the `size` parameter, window size, and `bins` array. ```c // ... vec2 texSize = textureSize(colorTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; int size = int(parameters.x); if (size <= 0) { fragColor = texture(colorTexture, texCoord); return; } if (size > MAX_SIZE) { size = MAX_SIZE; } int kernelSize = int(pow(size * 2 + 1, 2)); // ... ``` The `size` parameter controls how blurry or smeared the effect is. If the size is at or below zero, return the current fragment untouched. From the `size` parameter, calculate the total size of the kernel or window. This is how many samples you'll be taking per fragment. ```c // ... int binsSize = int(parameters.y); binsSize = clamp(binsSize, 1, MAX_BINS_SIZE); // ... ``` Set up the `binsSize`, making sure to limit it by the `MAX_BINS_SIZE`. ```c // ... int i = 0; int j = 0; int count = 0; int binIndex = 0; // ... ``` `i` and `j` are used to sample the given texture around the current fragment. `i` is also used as a general for loop count. `count` is used in the initialization of the `colors` array which you'll see later. `binIndex` is used to approximate the median color. ```c // ... vec4 colors[MAX_KERNEL_SIZE]; float bins[MAX_BINS_SIZE]; int binIndexes[colors.length()]; // ... ``` The `colors` array holds the sampled colors taken from the input texture. `bins` is used to approximate the median of the sampled colors. Each bin holds a count of how many colors fall into its range when converting each color into a greyscale value (between zero and one). As `binsSize` approaches 100, the algorithm finds the true median almost always. `binIndexes` stores the `bins` index or which bin each sample falls into. ```c // ... float total = 0; float limit = floor(float(kernelSize) / 2) + 1; // ... ``` `total` keeps track of how many colors you've come across as you loop through `bins`. When `total` reaches `limit`, you return whatever `bins` index you're at. The `limit` is the median index. For example, if the window size is 81, `limit` is 41 which is directly in the middle (40 samples below and 40 samples above). ```c // ... float value = 0; vec3 valueRatios = vec3(0.3, 0.59, 0.11); // ... ``` These are used to covert and hold each color sample's greyscale value. Instead of dividing red, green, and blue by one third, it uses 30% of red, 59% of green, and 11% of blue for a total of 100%. ```c // ... for (i = -size; i <= size; ++i) { for (j = -size; j <= size; ++j) { colors[count] = texture ( colorTexture , ( gl_FragCoord.xy + vec2(i, j) ) / texSize ); count += 1; } } // ... ``` Loop through the window and collect the color samples into `colors`. ```c // ... for (i = 0; i < binsSize; ++i) { bins[i] = 0; } // ... ``` Initialize the `bins` array with zeros. ```c // ... for (i = 0; i < kernelSize; ++i) { value = dot(colors[i].rgb, valueRatios); binIndex = int(floor(value * binsSize)); binIndex = clamp(binIndex, 0, binsSize - 1); bins[binIndex] += 1; binIndexes[i] = binIndex; } // ... ``` Loop through the colors and convert each one to a greyscale value. `dot(colors[i].rgb, valueRatios)` is the weighted sum `colors.r * 0.3 + colors.g * 0.59 + colors.b * 0.11`. Each value will fall into some bin. Each bin covers some range of values. For example, if the number of bins is 10, the first bin covers everything from zero up to but not including 0.1. Increment the number of colors that fall into this bin and remember the color sample's bin index so you can look it up later. ```c // ... binIndex = 0; for (i = 0; i < binsSize; ++i) { total += bins[i]; if (total >= limit) { binIndex = i; break; } } // ... ``` Loop through the bins, tallying up the number of colors seen so far. When you reach the median index, exit the loop and remember the last `bins` index reached. ```c // ... fragColor = colors[0]; for (i = 0; i < kernelSize; ++i) { if (binIndexes[i] == binIndex) { fragColor = colors[i]; break; } } // ... ``` Now loop through the `binIndexes` and find the first color with the last `bins` indexed reached. Its greyscale value is the approximated median which in many cases will be the true median value. Set this color as the fragColor and exit the loop and shader. ### Kuwahara Filter <p align="center"> <img src="https://i.imgur.com/b5vw2AJ.gif" alt="Kuwahara Filter" title="Kuwahara Filter"> </p> Like the median filter, the kuwahara filter preserves the major edges found in the image. You'll notice that it has a more block like or chunky pattern to it. In practice, the Kuwahara filter runs faster than the median filter, allowing for larger `size` values without a noticeable slowdown. ```c // ... #define MAX_SIZE 5 #define MAX_KERNEL_SIZE ((MAX_SIZE * 2 + 1) * (MAX_SIZE * 2 + 1)) // ... ``` Set a hard limit for the `size` parameter and the number of samples taken. ```c // ... int i = 0; int j = 0; int count = 0; // ... ``` These are used to sample the input texture and set up the `values` array. ```c // ... vec3 valueRatios = vec3(0.3, 0.59, 0.11); // ... ``` Like the median filter, you'll be converting the color samples into greyscale values. ```c // ... float values[MAX_KERNEL_SIZE]; // ... ``` Initialize the `values` array. This will hold the greyscale values for the color samples. ```c // ... vec4 color = vec4(0); vec4 meanTemp = vec4(0); vec4 mean = vec4(0); float valueMean = 0; float variance = 0; float minVariance = -1; // ... ``` The Kuwahara filter works by computing the variance of four subwindows and then using the mean of the subwindow with the smallest variance. ```c // ... void findMean(int i0, int i1, int j0, int j1) { // ... ``` `findMean` is a function defined outside of `main`. Each run of `findMean` will remember the mean of the given subwindow that has the lowest variance seen so far. ```c // ... meanTemp = vec4(0); count = 0; // ... ``` Make sure to reset `count` and `meanTemp` before computing the mean of the given subwindow. ```c // ... for (i = i0; i <= i1; ++i) { for (j = j0; j <= j1; ++j) { color = texture ( colorTexture , (gl_FragCoord.xy + vec2(i, j)) / texSize ); meanTemp += color; values[count] = dot(color.rgb, valueRatios); count += 1; } } // ... ``` Similar to the box blur, loop through the given subwindow and add up each color. At the same time, make sure to store the greyscale value for this sample in `values`. ```c // ... meanTemp.rgb /= count; valueMean = dot(meanTemp.rgb, valueRatios); // ... ``` To compute the mean, divide the samples sum by the number of samples taken. Calculate the greyscale value for the mean. ```c // ... for (i = 0; i < count; ++i) { variance += pow(values[i] - valueMean, 2); } variance /= count; // ... ``` Now calculate the variance for this given subwindow. The variance is the average squared difference between each sample's greyscale value the mean greyscale value. ```c // ... if (variance < minVariance || minVariance <= -1) { mean = meanTemp; minVariance = variance; } } // ... ``` If the variance is smaller than what you've seen before or this is the first variance you've seen, set the mean of this subwindow as the final mean and update the minimum variance seen so far. ```c // ... void main() { int size = int(parameters.x); if (size <= 0) { fragColor = texture(colorTexture, texCoord); return; } // ... ``` Back in `main`, set the `size` parameter. If the size is at or below zero, return the fragment unchanged. <p align="center"> <img src="https://i.imgur.com/iuLbLKO.gif" alt="Kuwahara Kernal" title="Kuwahara Kernal"> </p> ```c // ... // Lower Left findMean(-size, 0, -size, 0); // Upper Right findMean(0, size, 0, size); // Upper Left findMean(-size, 0, 0, size); // Lower Right findMean(0, size, -size, 0); // ... ``` As stated above, the Kuwahara filter works by computing the variance of four subwindows and then using the mean of the subwindow with the lowest variance as the final fragment color. Note that the four subwindows overlap each other. ```c // ... mean.a = 1; fragColor = mean; // ... ``` After computing the variance and mean for each subwindow, set the fragment color to the mean of the subwindow with the lowest variance. ### Source - [main.cxx](../demonstration/src/main.cxx) - [basic.vert](../demonstration/shaders/vertex/basic.vert) - [position.frag](../demonstration/shaders/fragment/position.frag) - [box-blur.frag](../demonstration/shaders/fragment/box-blur.frag) - [median-filter.frag](../demonstration/shaders/fragment/median-filter.frag) - [kuwahara-filter.frag](../demonstration/shaders/fragment/kuwahara-filter.frag) ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](fog.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](bloom.md)
3d-game-shaders-for-beginners/sections/blur.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/blur.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 4702 }
4
[:arrow_backward:](ssao.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](chromatic-aberration.md) # 3D Game Shaders For Beginners ## Motion Blur <p align="center"> <img src="https://i.imgur.com/eTnhpLr.gif" alt="Motion Blur" title="Motion Blur"> </p> To really sell the illusion of speed, you can do no better than motion blur. From high speed car chases to moving at warp speed, motion blur greatly improves the look and feel of fast moving objects. There are a few ways to implement motion blur as a screen space technique. The less involved implementation will only blur the scene in relation to the camera's movements while the more involved version will blur any moving objects even with the camera remaining still. The less involved technique is described below but the principle is the same. ### Textures ```c uniform sampler2D positionTexture; uniform sampler2D colorTexture; // ... ``` The input textures needed are the vertex positions in view space and the scene's colors. Refer back to [SSAO](ssao.md#vertex-positions) for acquiring the vertex positions. ### Matrices ```c // ... uniform mat4 previousViewWorldMat; uniform mat4 worldViewMat; uniform mat4 lensProjection; // ... ``` The motion blur technique determines the blur direction by comparing the previous frame's vertex positions with the current frame's vertex positions. To do this, you'll need the previous frame's view-to-world matrix, the current frame's world-to-view matrix, and the camera lens' projection matrix. ### Parameters ```c // ... uniform vec2 parameters; // ... void main() { int size = int(parameters.x); float separation = parameters.y; // ... ``` The adjustable parameters are `size` and `separation`. `size` controls how many samples are taken along the blur direction. Increasing `size` increases the amount of blur at the cost of performance. `separation` controls how spread out the samples are along the blur direction. Increasing `separation` increases the amount of blur at the cost of accuracy. ### Blur Direction ```c // ... vec2 texSize = textureSize(colorTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; vec4 position1 = texture(positionTexture, texCoord); vec4 position0 = worldViewMat * previousViewWorldMat * position1; // ... ``` To determine which way to blur this fragment, you'll need to know where things were last frame and where things are this frame. To figure out where things are now, sample the current vertex position. To figure out where things were last frame, transform the current position from view space to world space, using the previous frame's view-to-world matrix, and then transform it back to view space from world space using this frame's world-to-view matrix. This transformed position is this fragment's previous interpolated vertex position. <p align="center"> <img src="https://i.imgur.com/oQqdxM9.gif" alt="Position Projection" title="Position Projection"> </p> ```c // ... position0 = lensProjection * position0; position0.xyz /= position0.w; position0.xy = position0.xy * 0.5 + 0.5; position1 = lensProjection * position1; position1.xyz /= position1.w; position1.xy = position1.xy * 0.5 + 0.5; // ... ``` Now that you have the current and previous positions, transform them to screen space. With the positions in screen space, you can trace out the 2D direction you'll need to blur the onscreen image. ```c // ... // position1.xy = position0.xy + direction; vec2 direction = position1.xy - position0.xy; if (length(direction) <= 0.0) { return; } // ... ``` The blur direction goes from the previous position to the current position. ### Blurring ```c // ... fragColor = texture(colorTexture, texCoord); // ... ``` Sample the current fragment's color. This will be the first of the colors blurred together. ```c // ... direction.xy *= separation; // ... ``` Multiply the direction vector by the separation. ```c // ... vec2 forward = texCoord; vec2 backward = texCoord; // ... ``` For a more seamless blur, sample in the direction of the blur and in the opposite direction of the blur. For now, set the two vectors to the fragment's UV coordinate. ```c // ... float count = 1.0; // ... ``` `count` is used to average all of the samples taken. It starts at one since you've already sampled the current fragment's color. ```c // ... for (int i = 0; i < size; ++i) { forward += direction; backward -= direction; fragColor += texture ( colorTexture , forward ); fragColor += texture ( colorTexture , backward ); count += 2.0; } // ... ``` Sample the screen's colors both in the forward and backward direction of the blur. Be sure to add these samples together as you travel along. ```c // ... fragColor /= count; } ``` The final fragment color is the average color of the samples taken. ### Source - [main.cxx](../demonstration/src/main.cxx) - [basic.vert](../demonstration/shaders/vertex/basic.vert) - [position.frag](../demonstration/shaders/fragment/position.frag) - [motion-blur.frag](../demonstration/shaders/fragment/motion-blur.frag) ## Copyright (C) 2020 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](ssao.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](chromatic-aberration.md)
3d-game-shaders-for-beginners/sections/motion-blur.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/motion-blur.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 1759 }
5
# Skip json.hpp since it is copied directly from external repo AirLib/include/common/common_utils/json.hpp
AirSim/.clang-format-ignore/0
{ "file_path": "AirSim/.clang-format-ignore", "repo_id": "AirSim", "token_count": 30 }
6
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_VehicleApiBase_hpp #define air_VehicleApiBase_hpp #include "common/CommonStructs.hpp" #include "common/UpdatableObject.hpp" #include "common/Common.hpp" #include "common/Waiter.hpp" #include "safety/SafetyEval.hpp" #include "common/CommonStructs.hpp" #include "common/ImageCaptureBase.hpp" #include "sensors/SensorCollection.hpp" #include "sensors/lidar/LidarBase.hpp" #include "sensors/imu/ImuBase.hpp" #include "sensors/barometer/BarometerBase.hpp" #include "sensors/magnetometer/MagnetometerBase.hpp" #include "sensors/distance/DistanceBase.hpp" #include "sensors/gps/GpsBase.hpp" #include <exception> #include <string> namespace msr { namespace airlib { /* Vehicle controller allows to obtain state from vehicle and send control commands to the vehicle. State can include many things including sensor data, logs, estimated state from onboard computer etc. Control commands can be low level actuation commands or high level movement commands. The base class defines usually available methods that all vehicle controllers may implement. Some methods may not be applicable to specific vehicle in which case an exception may be raised or call may be ignored. */ class VehicleApiBase : public UpdatableObject { public: virtual void enableApiControl(bool is_enabled) = 0; virtual bool isApiControlEnabled() const = 0; virtual bool armDisarm(bool arm) = 0; virtual GeoPoint getHomeGeoPoint() const = 0; virtual void update() override { UpdatableObject::update(); } virtual void cancelLastTask() { //if derived class supports async task then override this method } virtual bool isReady(std::string& message) const { unused(message); return true; } virtual bool canArm() const { return true; } //if vehicle supports it, call this method to send //kinematics and other info to somewhere (ex. log viewer, file, cloud etc) virtual void sendTelemetry(float last_interval = -1) { //no default action unused(last_interval); } //below APIs are used by FastPhysicsEngine virtual real_T getActuation(unsigned int actuator_index) const { unused(actuator_index); throw VehicleCommandNotImplementedException("getActuation API is not supported for this vehicle"); } virtual size_t getActuatorCount() const { throw VehicleCommandNotImplementedException("getActuatorCount API is not supported for this vehicle"); } virtual void getStatusMessages(std::vector<std::string>& messages) { unused(messages); //default implementation } /* For RCs, there are two cases: (1) vehicle may be configured to use RC bound to its hardware (2) vehicle may be configured to get RC data supplied via API calls. Below two APIs are not symmetrical, i.e., getRCData() may or may not return same thing as setRCData(). */ //get reading from RC bound to vehicle (if unsupported then RCData::is_valid = false) virtual RCData getRCData() const { static const RCData invalid_rc_data{}; return invalid_rc_data; } //set external RC data to vehicle (if unsupported then returns false) virtual bool setRCData(const RCData& rc_data) { unused(rc_data); return false; } // Sensors APIs virtual const SensorCollection& getSensors() const { throw VehicleCommandNotImplementedException("getSensors API is not supported for this vehicle"); } // Lidar APIs virtual const LidarData& getLidarData(const std::string& lidar_name) const { auto* lidar = static_cast<const LidarBase*>(findSensorByName(lidar_name, SensorBase::SensorType::Lidar)); if (lidar == nullptr) throw VehicleControllerException(Utils::stringf("No lidar with name %s exist on vehicle", lidar_name.c_str())); return lidar->getOutput(); } // IMU API virtual const ImuBase::Output& getImuData(const std::string& imu_name) const { auto* imu = static_cast<const ImuBase*>(findSensorByName(imu_name, SensorBase::SensorType::Imu)); if (imu == nullptr) throw VehicleControllerException(Utils::stringf("No IMU with name %s exist on vehicle", imu_name.c_str())); return imu->getOutput(); } // Barometer API virtual const BarometerBase::Output& getBarometerData(const std::string& barometer_name) const { auto* barometer = static_cast<const BarometerBase*>(findSensorByName(barometer_name, SensorBase::SensorType::Barometer)); if (barometer == nullptr) throw VehicleControllerException(Utils::stringf("No barometer with name %s exist on vehicle", barometer_name.c_str())); return barometer->getOutput(); } // Magnetometer API virtual const MagnetometerBase::Output& getMagnetometerData(const std::string& magnetometer_name) const { auto* magnetometer = static_cast<const MagnetometerBase*>(findSensorByName(magnetometer_name, SensorBase::SensorType::Magnetometer)); if (magnetometer == nullptr) throw VehicleControllerException(Utils::stringf("No magnetometer with name %s exist on vehicle", magnetometer_name.c_str())); return magnetometer->getOutput(); } // Gps API virtual const GpsBase::Output& getGpsData(const std::string& gps_name) const { auto* gps = static_cast<const GpsBase*>(findSensorByName(gps_name, SensorBase::SensorType::Gps)); if (gps == nullptr) throw VehicleControllerException(Utils::stringf("No gps with name %s exist on vehicle", gps_name.c_str())); return gps->getOutput(); } // Distance Sensor API virtual const DistanceSensorData& getDistanceSensorData(const std::string& distance_sensor_name) const { auto* distance_sensor = static_cast<const DistanceBase*>(findSensorByName(distance_sensor_name, SensorBase::SensorType::Distance)); if (distance_sensor == nullptr) throw VehicleControllerException(Utils::stringf("No distance sensor with name %s exist on vehicle", distance_sensor_name.c_str())); return distance_sensor->getOutput(); } virtual ~VehicleApiBase() = default; //exceptions class VehicleControllerException : public std::runtime_error { public: VehicleControllerException(const std::string& message) : runtime_error(message) { } }; class VehicleCommandNotImplementedException : public VehicleControllerException { public: VehicleCommandNotImplementedException(const std::string& message) : VehicleControllerException(message) { } }; class VehicleMoveException : public VehicleControllerException { public: VehicleMoveException(const std::string& message) : VehicleControllerException(message) { } }; private: const SensorBase* findSensorByName(const std::string& sensor_name, const SensorBase::SensorType type) const { const SensorBase* sensor = nullptr; // Find sensor with the given name (for empty input name, return the first one found) // Not efficient but should suffice given small number of sensors uint count_sensors = getSensors().size(type); for (uint i = 0; i < count_sensors; i++) { const SensorBase* current_sensor = getSensors().getByType(type, i); if (current_sensor != nullptr && (current_sensor->getName() == sensor_name || sensor_name == "")) { sensor = current_sensor; break; } } return sensor; } }; } } //namespace #endif
AirSim/AirLib/include/api/VehicleApiBase.hpp/0
{ "file_path": "AirSim/AirLib/include/api/VehicleApiBase.hpp", "repo_id": "AirSim", "token_count": 3467 }
7
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_ImageCaptureBase_hpp #define air_ImageCaptureBase_hpp #include "common/Common.hpp" #include "common/common_utils/EnumFlags.hpp" namespace msr { namespace airlib { // This is an abstraction for cameras associated with a vehicle. Each camera has a unique id. class ImageCaptureBase { public: //types enum class ImageType : int { //this indexes to array, -1 is special to indicate main camera Scene = 0, DepthPlanar, DepthPerspective, DepthVis, DisparityNormalized, Segmentation, SurfaceNormals, Infrared, OpticalFlow, OpticalFlowVis, Count //must be last }; struct ImageRequest { std::string camera_name; ImageCaptureBase::ImageType image_type = ImageCaptureBase::ImageType::Scene; bool pixels_as_float = false; bool compress = true; ImageRequest() { } ImageRequest(const std::string& camera_name_val, ImageCaptureBase::ImageType image_type_val, bool pixels_as_float_val = false, bool compress_val = true) : camera_name(camera_name_val) , image_type(image_type_val) , pixels_as_float(pixels_as_float_val) , compress(compress_val) { } }; struct ImageResponse { vector<uint8_t> image_data_uint8; vector<float> image_data_float; std::string camera_name; Vector3r camera_position = Vector3r::Zero(); Quaternionr camera_orientation = Quaternionr::Identity(); TTimePoint time_stamp = 0; std::string message; bool pixels_as_float = false; bool compress = true; int width = 0, height = 0; ImageType image_type; }; public: //methods virtual void getImages(const std::vector<ImageRequest>& requests, std::vector<ImageResponse>& responses) const = 0; virtual ~ImageCaptureBase() = default; }; } } //namespace #endif
AirSim/AirLib/include/common/ImageCaptureBase.hpp/0
{ "file_path": "AirSim/AirLib/include/common/ImageCaptureBase.hpp", "repo_id": "AirSim", "token_count": 1128 }
8
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_ExceptionsUtils_hpp #define air_ExceptionsUtils_hpp //print exception stack trace //from: http://stackoverflow.com/a/11674810/207661 #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-pedantic" #include <dlfcn.h> #include <execinfo.h> #include <typeinfo> #include <string> #include <memory> #include <cxxabi.h> #include <cstdlib> namespace { void* last_frames[20]; size_t last_size; std::string exception_name; std::string demangle(const char* name) { int status; std::unique_ptr<char, void (*)(void*)> realname(abi::__cxa_demangle(name, 0, 0, &status), &std::free); return status ? "failed" : &*realname; } } extern "C" { void __cxa_throw(void* ex, void* info, void (*dest)(void*)) { exception_name = demangle(reinterpret_cast<const std::type_info*>(info)->name()); last_size = backtrace(last_frames, sizeof last_frames / sizeof(void*)); static void (*const rethrow)(void*, void*, void (*)(void*)) __attribute__((noreturn)) = (void (*)(void*, void*, void (*)(void*)))dlsym(RTLD_NEXT, "__cxa_throw"); rethrow(ex, info, dest); } } #pragma GCC diagnostic pop #endif void printExceptionStack() { #ifdef __GNUC__ backtrace_symbols_fd(last_frames, last_size, 2); #endif } #endif
AirSim/AirLib/include/common/common_utils/ExceptionUtils.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/ExceptionUtils.hpp", "repo_id": "AirSim", "token_count": 505 }
9
/* ***************************************************************************** * * * Platform Independent * * Bitmap Image Reader Writer Library * * * * Author: Arash Partow - 2002 * * URL: http://partow.net/programming/bitmap/index.html * * * * Note: This library only supports 24-bits per pixel bitmap format files. * * * * Copyright notice: * * Free use of the Platform Independent Bitmap Image Reader Writer Library * * is permitted under the guidelines and in accordance with the most current * * version of the MIT License. * * http://www.opensource.org/licenses/MIT * * * ***************************************************************************** */ #ifndef INCLUDE_BITMAP_IMAGE_HPP #define INCLUDE_BITMAP_IMAGE_HPP // clang-format off #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <limits> #include <string> #include <vector> namespace common_utils { namespace bmp { class bitmap_image { public: enum channel_mode { rgb_mode = 0, bgr_mode = 1 }; enum color_plane { blue_plane = 0, green_plane = 1, red_plane = 2 }; struct rgb_t { unsigned char red; unsigned char green; unsigned char blue; }; bitmap_image() : file_name_(""), width_(0), height_(0), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) {} bitmap_image(const std::string& filename) : file_name_(filename), width_(0), height_(0), row_increment_(0), bytes_per_pixel_(0), channel_mode_(bgr_mode) { load_bitmap(); } bitmap_image(const unsigned int width, const unsigned int height) : file_name_(""), width_(width), height_(height), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) { create_bitmap(); } bitmap_image(const bitmap_image& image) : file_name_(image.file_name_), width_(image.width_), height_(image.height_), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) { create_bitmap(); data_ = image.data_; } bitmap_image& operator=(const bitmap_image& image) { if (this != &image) { file_name_ = image.file_name_; bytes_per_pixel_ = image.bytes_per_pixel_; width_ = image.width_; height_ = image.height_; row_increment_ = 0; channel_mode_ = image.channel_mode_; create_bitmap(); data_ = image.data_; } return *this; } inline bool operator!() { return (data_.size() == 0) || (width_ == 0) || (height_ == 0) || (row_increment_ == 0); } inline void clear(const unsigned char v = 0x00) { std::fill(data_.begin(), data_.end(), v); } inline unsigned char red_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 2)]; } inline unsigned char green_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 1)]; } inline unsigned char blue_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 0)]; } inline void red_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 2)] = value; } inline void green_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 1)] = value; } inline void blue_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 0)] = value; } inline unsigned char* row(unsigned int row_index) const { return const_cast<unsigned char*>(&data_[(row_index * row_increment_)]); } inline void get_pixel(const unsigned int x, const unsigned int y, unsigned char& red, unsigned char& green, unsigned char& blue) const { const unsigned int y_offset = y * row_increment_; const unsigned int x_offset = x * bytes_per_pixel_; const unsigned int offset = y_offset + x_offset; blue = data_[offset + 0]; green = data_[offset + 1]; red = data_[offset + 2]; } template <typename RGB> inline void get_pixel(const unsigned int x, const unsigned int y, RGB& colour) const { get_pixel(x, y, colour.red, colour.green, colour.blue); } inline rgb_t get_pixel(const unsigned int x, const unsigned int y) const { rgb_t colour; get_pixel(x, y, colour.red, colour.green, colour.blue); return colour; } inline void set_pixel(const unsigned int x, const unsigned int y, const unsigned char red, const unsigned char green, const unsigned char blue) { const unsigned int y_offset = y * row_increment_; const unsigned int x_offset = x * bytes_per_pixel_; const unsigned int offset = y_offset + x_offset; data_[offset + 0] = blue; data_[offset + 1] = green; data_[offset + 2] = red; } template <typename RGB> inline void set_pixel(const unsigned int x, const unsigned int y, const RGB& colour) { set_pixel(x, y, colour.red, colour.green, colour.blue); } inline bool copy_from(const bitmap_image& image) { if ( (image.height_ != height_) || (image.width_ != width_) ) { return false; } data_ = image.data_; return true; } inline bool copy_from(const bitmap_image& source_image, const unsigned int& x_offset, const unsigned int& y_offset) { if ((x_offset + source_image.width_) > width_) { return false; } if ((y_offset + source_image.height_) > height_) { return false; } for (unsigned int y = 0; y < source_image.height_; ++y) { unsigned char* itr1 = row(y + y_offset) + x_offset * bytes_per_pixel_; const unsigned char* itr2 = source_image.row(y); const unsigned char* itr2_end = itr2 + source_image.width_ * bytes_per_pixel_; std::copy(itr2, itr2_end, itr1); } return true; } inline bool region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, bitmap_image& dest_image) const { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } if ( (dest_image.width_ < width_) || (dest_image.height_ < height_) ) { dest_image.setwidth_height(width, height); } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr1 = row(r + y) + x * bytes_per_pixel_; unsigned char* itr1_end = itr1 + (width * bytes_per_pixel_); unsigned char* itr2 = dest_image.row(r); std::copy(itr1, itr1_end, itr2); } return true; } inline bool roi_from_center(const unsigned int& cx, const unsigned int& cy, const unsigned int& width, const unsigned int& height, bitmap_image& dest_image) const { return region(cx - (width / 2), cy - (height / 2), width, height, dest_image); } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const unsigned char& value) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_; unsigned char* itr_end = itr + (width * bytes_per_pixel_); std::fill(itr, itr_end, value); } return true; } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const color_plane color, const unsigned char& value) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } const unsigned int color_plane_offset = offset(color); for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_ + color_plane_offset; unsigned char* itr_end = itr + (width * bytes_per_pixel_); while (itr != itr_end) { *itr = value; itr += bytes_per_pixel_; } } return true; } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const unsigned char& red, const unsigned char& green, const unsigned char& blue) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_; unsigned char* itr_end = itr + (width * bytes_per_pixel_); while (itr != itr_end) { *(itr++) = blue; *(itr++) = green; *(itr++) = red; } } return true; } void reflective_image(bitmap_image& image, const bool include_diagnols = false) { image.setwidth_height(3 * width_, 3 * height_, true); image.copy_from(*this, width_, height_); vertical_flip(); image.copy_from(*this, width_, 0); image.copy_from(*this, width_, 2 * height_); vertical_flip(); horizontal_flip(); image.copy_from(*this, 0, height_); image.copy_from(*this, 2 * width_, height_); horizontal_flip(); if (include_diagnols) { bitmap_image tile = *this; tile.vertical_flip(); tile.horizontal_flip(); image.copy_from(tile, 0, 0); image.copy_from(tile, 2 * width_, 0); image.copy_from(tile, 2 * width_, 2 * height_); image.copy_from(tile, 0, 2 * height_); } } inline unsigned int width() const { return width_; } inline unsigned int height() const { return height_; } inline unsigned int bytes_per_pixel() const { return bytes_per_pixel_; } inline unsigned int pixel_count() const { return width_ * height_; } inline void setwidth_height(const unsigned int width, const unsigned int height, const bool clear = false) { data_.clear(); width_ = width; height_ = height; create_bitmap(); if (clear) { std::fill(data_.begin(), data_.end(), static_cast<unsigned char>(0x00)); } } void save_image(const std::string& file_name) const { std::ofstream stream(file_name.c_str(), std::ios::binary); if (!stream) { std::cerr << "bitmap_image::save_image(): Error - Could not open file " << file_name << " for writing!" << std::endl; return; } bitmap_information_header bih; bih.width = width_; bih.height = height_; bih.bit_count = static_cast<unsigned short>(bytes_per_pixel_ << 3); bih.clr_important = 0; bih.clr_used = 0; bih.compression = 0; bih.planes = 1; bih.size = bih.struct_size(); bih.x_pels_per_meter = 0; bih.y_pels_per_meter = 0; bih.size_image = (((bih.width * bytes_per_pixel_) + 3) & 0x0000FFFC) * bih.height; bitmap_file_header bfh; bfh.type = 19778; bfh.size = bfh.struct_size() + bih.struct_size() + bih.size_image; bfh.reserved1 = 0; bfh.reserved2 = 0; bfh.off_bits = bih.struct_size() + bfh.struct_size(); write_bfh(stream, bfh); write_bih(stream, bih); unsigned int padding = (4 - ((3 * width_) % 4)) % 4; char padding_data[4] = { 0x00, 0x00, 0x00, 0x00 }; for (unsigned int i = 0; i < height_; ++i) { const unsigned char* data_ptr = &data_[(row_increment_ * (height_ - i - 1))]; stream.write(reinterpret_cast<const char*>(data_ptr), sizeof(unsigned char) * bytes_per_pixel_ * width_); stream.write(padding_data, padding); } stream.close(); } inline void set_all_ith_bits_low(const unsigned int bitr_index) { unsigned char mask = static_cast<unsigned char>(~(1 << bitr_index)); for (unsigned char* itr = data(); itr != end(); ++itr) { *itr &= mask; } } inline void set_all_ith_bits_high(const unsigned int bitr_index) { unsigned char mask = static_cast<unsigned char>(1 << bitr_index); for (unsigned char* itr = data(); itr != end(); ++itr) { *itr |= mask; } } inline void set_all_ith_channels(const unsigned int& channel, const unsigned char& value) { for (unsigned char* itr = (data() + channel); itr < end(); itr += bytes_per_pixel_) { *itr = value; } } inline void set_channel(const color_plane color, const unsigned char& value) { for (unsigned char* itr = (data() + offset(color)); itr < end(); itr += bytes_per_pixel_) { *itr = value; } } inline void ror_channel(const color_plane color, const unsigned int& ror) { for (unsigned char* itr = (data() + offset(color)); itr < end(); itr += bytes_per_pixel_) { *itr = static_cast<unsigned char>(((*itr) >> ror) | ((*itr) << (8 - ror))); } } inline void set_all_channels(const unsigned char& value) { for (unsigned char* itr = data(); itr < end(); ) { *(itr++) = value; } } inline void set_all_channels(const unsigned char& r_value, const unsigned char& g_value, const unsigned char& b_value) { for (unsigned char* itr = (data() + 0); itr < end(); itr += bytes_per_pixel_) { *(itr + 0) = b_value; *(itr + 1) = g_value; *(itr + 2) = r_value; } } inline void invert_color_planes() { for (unsigned char* itr = data(); itr < end(); *itr = ~(*itr), ++itr); } inline void add_to_color_plane(const color_plane color, const unsigned char& value) { for (unsigned char* itr = (data() + offset(color)); itr < end(); itr += bytes_per_pixel_) { (*itr) += value; } } inline void convert_to_grayscale() { double r_scaler = 0.299; double g_scaler = 0.587; double b_scaler = 0.114; if (rgb_mode == channel_mode_) { std::swap(r_scaler, b_scaler); } for (unsigned char* itr = data(); itr < end(); ) { unsigned char gray_value = static_cast<unsigned char> ( (r_scaler * (*(itr + 2))) + (g_scaler * (*(itr + 1))) + (b_scaler * (*(itr + 0))) ); *(itr++) = gray_value; *(itr++) = gray_value; *(itr++) = gray_value; } } inline const unsigned char* data() const { return data_.data(); } inline unsigned char* data() { return const_cast<unsigned char*>(data_.data()); } inline void bgr_to_rgb() { if ((bgr_mode == channel_mode_) && (3 == bytes_per_pixel_)) { reverse_channels(); channel_mode_ = rgb_mode; } } inline void rgb_to_bgr() { if ((rgb_mode == channel_mode_) && (3 == bytes_per_pixel_)) { reverse_channels(); channel_mode_ = bgr_mode; } } inline void reverse() { unsigned char* itr1 = data(); unsigned char* itr2 = end() - bytes_per_pixel_; while (itr1 < itr2) { for (std::size_t i = 0; i < bytes_per_pixel_; ++i) { unsigned char* citr1 = itr1 + i; unsigned char* citr2 = itr2 + i; std::swap(*citr1, *citr2); } itr1 += bytes_per_pixel_; itr2 -= bytes_per_pixel_; } } inline void horizontal_flip() { for (unsigned int y = 0; y < height_; ++y) { unsigned char* itr1 = row(y); unsigned char* itr2 = itr1 + row_increment_ - bytes_per_pixel_; while (itr1 < itr2) { for (unsigned int i = 0; i < bytes_per_pixel_; ++i) { unsigned char* p1 = (itr1 + i); unsigned char* p2 = (itr2 + i); std::swap(*p1, *p2); } itr1 += bytes_per_pixel_; itr2 -= bytes_per_pixel_; } } } inline void vertical_flip() { for (unsigned int y = 0; y < (height_ / 2); ++y) { unsigned char* itr1 = row(y); unsigned char* itr2 = row(height_ - y - 1); for (std::size_t x = 0; x < row_increment_; ++x) { std::swap(*(itr1 + x), *(itr2 + x)); } } } inline void export_color_plane(const color_plane color, unsigned char* image) { for (unsigned char* itr = (data() + offset(color)); itr < end(); ++image, itr += bytes_per_pixel_) { (*image) = (*itr); } } inline void export_color_plane(const color_plane color, bitmap_image& image) { if ( (width_ != image.width_) || (height_ != image.height_) ) { image.setwidth_height(width_, height_); } image.clear(); unsigned char* itr1 = (data() + offset(color)); unsigned char* itr1_end = end(); unsigned char* itr2 = (image.data() + offset(color)); while (itr1 < itr1_end) { (*itr2) = (*itr1); itr1 += bytes_per_pixel_; itr2 += bytes_per_pixel_; } } inline void export_response_image(const color_plane color, double* response_image) { double* resp_itr = response_image; for (unsigned char* itr = (data() + offset(color)); itr < end(); ++response_image, itr += bytes_per_pixel_) { *(resp_itr++) = (1.0 * (*itr)) / 256.0; } } inline void export_gray_scale_response_image(double* response_image) const { double* resp_itr = response_image; for (const unsigned char* itr = data(); itr < end(); itr += bytes_per_pixel_) { unsigned char gray_value = static_cast<unsigned char> ( (0.299 * (*(itr + 2))) + (0.587 * (*(itr + 1))) + (0.114 * (*(itr + 0))) ); *(resp_itr++) = (1.0 * gray_value) / 256.0; } } inline void export_rgb(double* red, double* green, double* blue) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { (*blue) = (1.0 * (*(itr++))) / 256.0; (*green) = (1.0 * (*(itr++))) / 256.0; (*red) = (1.0 * (*(itr++))) / 256.0; } } inline void export_rgb(float* red, float* green, float* blue) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { (*blue) = (1.0f * (*(itr++))) / 256.0f; (*green) = (1.0f * (*(itr++))) / 256.0f; (*red) = (1.0f * (*(itr++))) / 256.0f; } } inline void export_rgb(unsigned char* red, unsigned char* green, unsigned char* blue) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { (*blue) = *(itr++); (*green) = *(itr++); (*red) = *(itr++); } } inline void export_ycbcr(double* y, double* cb, double* cr) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++y, ++cb, ++cr) { const double blue = (1.0 * (*(itr++))); const double green = (1.0 * (*(itr++))); const double red = (1.0 * (*(itr++))); (*y) = clamp<double>(16.0 + (1.0 / 256.0) * (65.738 * red + 129.057 * green + 25.064 * blue), 1.0, 254); (*cb) = clamp<double>(128.0 + (1.0 / 256.0) * (-37.945 * red - 74.494 * green + 112.439 * blue), 1.0, 254); (*cr) = clamp<double>(128.0 + (1.0 / 256.0) * (112.439 * red - 94.154 * green - 18.285 * blue), 1.0, 254); } } inline void export_rgb_normal(double* red, double* green, double* blue) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { (*blue) = (1.0 * (*(itr++))); (*green) = (1.0 * (*(itr++))); (*red) = (1.0 * (*(itr++))); } } inline void export_rgb_normal(float* red, float* green, float* blue) const { if (bgr_mode != channel_mode_) return; for (const unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { (*blue) = (1.0f * (*(itr++))); (*green) = (1.0f * (*(itr++))); (*red) = (1.0f * (*(itr++))); } } inline void import_rgb(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(256.0 * (*blue)); *(itr++) = static_cast<unsigned char>(256.0 * (*green)); *(itr++) = static_cast<unsigned char>(256.0 * (*red)); } } inline void import_rgb(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(256.0f * (*blue)); *(itr++) = static_cast<unsigned char>(256.0f * (*green)); *(itr++) = static_cast<unsigned char>(256.0f * (*red)); } } inline void import_rgb(unsigned char* red, unsigned char* green, unsigned char* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = (*blue); *(itr++) = (*green); *(itr++) = (*red); } } inline void import_ycbcr(double* y, double* cb, double* cr) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++y, ++cb, ++cr) { double y_ = (*y); double cb_ = (*cb); double cr_ = (*cr); *(itr++) = static_cast<unsigned char>(clamp((298.082 * y_ + 516.412 * cb_) / 256.0 - 276.836, 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp((298.082 * y_ - 100.291 * cb_ - 208.120 * cr_) / 256.0 + 135.576, 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp((298.082 * y_ + 408.583 * cr_) / 256.0 - 222.921, 0.0, 255.0)); } } inline void import_gray_scale_clamped(double* gray) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++gray) { unsigned char c = static_cast<unsigned char>(clamp<double>(256.0 * (*gray), 0.0, 255.0)); *(itr + 0) = c; *(itr + 1) = c; *(itr + 2) = c; itr += 3; } } inline void import_rgb_clamped(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(clamp<double>(256.0 * (*blue), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp<double>(256.0 * (*green), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp<double>(256.0 * (*red), 0.0, 255.0)); } } inline void import_rgb_clamped(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(clamp<double>(256.0f * (*blue), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp<double>(256.0f * (*green), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp<double>(256.0f * (*red), 0.0, 255.0)); } } inline void import_rgb_normal(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(*blue); *(itr++) = static_cast<unsigned char>(*green); *(itr++) = static_cast<unsigned char>(*red); } } inline void import_rgb_normal(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data(); itr < end(); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(*blue); *(itr++) = static_cast<unsigned char>(*green); *(itr++) = static_cast<unsigned char>(*red); } } inline void subsample(bitmap_image& dest) const { /* Half sub-sample of original image. */ unsigned int w = 0; unsigned int h = 0; bool odd_width = false; bool odd_height = false; if (0 == (width_ % 2)) w = width_ / 2; else { w = 1 + (width_ / 2); odd_width = true; } if (0 == (height_ % 2)) h = height_ / 2; else { h = 1 + (height_ / 2); odd_height = true; } unsigned int horizontal_upper = (odd_width) ? (w - 1) : w; unsigned int vertical_upper = (odd_height) ? (h - 1) : h; dest.setwidth_height(w, h); dest.clear(); unsigned char* s_itr[3]; const unsigned char* itr1[3]; const unsigned char* itr2[3]; s_itr[0] = dest.data() + 0; s_itr[1] = dest.data() + 1; s_itr[2] = dest.data() + 2; itr1[0] = data() + 0; itr1[1] = data() + 1; itr1[2] = data() + 2; itr2[0] = data() + row_increment_ + 0; itr2[1] = data() + row_increment_ + 1; itr2[2] = data() + row_increment_ + 2; unsigned int total = 0; for (unsigned int j = 0; j < vertical_upper; ++j) { for (unsigned int i = 0; i < horizontal_upper; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); total += *(itr1[k]); total += *(itr2[k]); total += *(itr2[k]); itr1[k] += bytes_per_pixel_; itr1[k] += bytes_per_pixel_; itr2[k] += bytes_per_pixel_; itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 2); } } if (odd_width) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); total += *(itr2[k]); itr1[k] += bytes_per_pixel_; itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 1); } } for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { itr1[k] += row_increment_; } if (j != (vertical_upper - 1)) { for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { itr2[k] += row_increment_; } } } if (odd_height) { for (unsigned int i = 0; i < horizontal_upper; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); total += *(itr2[k]); itr1[k] += bytes_per_pixel_; itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 1); } } if (odd_width) { for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { (*(s_itr[k])) = *(itr1[k]); } } } } inline void upsample(bitmap_image& dest) const { /* 2x up-sample of original image. */ dest.setwidth_height(2 * width_, 2 * height_); dest.clear(); const unsigned char* s_itr[3]; unsigned char* itr1[3]; unsigned char* itr2[3]; s_itr[0] = data() + 0; s_itr[1] = data() + 1; s_itr[2] = data() + 2; itr1[0] = dest.data() + 0; itr1[1] = dest.data() + 1; itr1[2] = dest.data() + 2; itr2[0] = dest.data() + dest.row_increment_ + 0; itr2[1] = dest.data() + dest.row_increment_ + 1; itr2[2] = dest.data() + dest.row_increment_ + 2; for (unsigned int j = 0; j < height_; ++j) { for (unsigned int i = 0; i < width_; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { *(itr1[k]) = *(s_itr[k]); itr1[k] += bytes_per_pixel_; *(itr1[k]) = *(s_itr[k]); itr1[k] += bytes_per_pixel_; *(itr2[k]) = *(s_itr[k]); itr2[k] += bytes_per_pixel_; *(itr2[k]) = *(s_itr[k]); itr2[k] += bytes_per_pixel_; } } for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { itr1[k] += dest.row_increment_; itr2[k] += dest.row_increment_; } } } inline void alpha_blend(const double& alpha, const bitmap_image& image) { if ( (image.width_ != width_) || (image.height_ != height_) ) { return; } if ((alpha < 0.0) || (alpha > 1.0)) { return; } unsigned char* itr1 = data(); const unsigned char* itr1_end = end(); const unsigned char* itr2 = image.data(); double alpha_compliment = 1.0 - alpha; while (itr1 != itr1_end) { *(itr1) = static_cast<unsigned char>((alpha * (*itr2)) + (alpha_compliment * (*itr1))); ++itr1; ++itr2; } } inline double psnr(const bitmap_image& image) { if ( (image.width_ != width_) || (image.height_ != height_) ) { return 0.0; } const unsigned char* itr1 = data(); const unsigned char* itr2 = image.data(); double mse = 0.0; while (itr1 != end()) { const double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * width_ * height_); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline double psnr(const unsigned int& x, const unsigned int& y, const bitmap_image& image) { if ((x + image.width()) > width_) { return 0.0; } if ((y + image.height()) > height_) { return 0.0; } double mse = 0.0; const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int r = 0; r < height; ++r) { const unsigned char* itr1 = row(r + y) + x * bytes_per_pixel_; const unsigned char* itr1_end = itr1 + (width * bytes_per_pixel_); const unsigned char* itr2 = image.row(r); while (itr1 != itr1_end) { double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * image.width() * image.height()); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline void histogram(const color_plane color, double hist[256]) const { std::fill(hist, hist + 256, 0.0); for (const unsigned char* itr = (data() + offset(color)); itr < end(); itr += bytes_per_pixel_) { ++hist[(*itr)]; } } inline void histogram_normalized(const color_plane color, double hist[256]) const { histogram(color, hist); double* h_itr = hist; const double* h_end = hist + 256; const double pixel_count = static_cast<double>(width_ * height_); while (h_end != h_itr) { *(h_itr++) /= pixel_count; } } inline unsigned int offset(const color_plane color) const { switch (channel_mode_) { case rgb_mode: { switch (color) { case red_plane: return 0; case green_plane: return 1; case blue_plane: return 2; default: return std::numeric_limits<unsigned int>::max(); } } case bgr_mode: { switch (color) { case red_plane: return 2; case green_plane: return 1; case blue_plane: return 0; default: return std::numeric_limits<unsigned int>::max(); } } default: return std::numeric_limits<unsigned int>::max(); } } inline void incremental() { unsigned char current_color = 0; for (unsigned char* itr = data(); itr < end();) { (*itr++) = (current_color); (*itr++) = (current_color); (*itr++) = (current_color); ++current_color; } } inline void reverse_channels() { if (3 != bytes_per_pixel_) return; for (unsigned char* itr = data(); itr < end(); itr += bytes_per_pixel_) { std::swap(*(itr + 0), *(itr + 2)); } } private: inline const unsigned char* end() const { return data_.data() + data_.size(); } inline unsigned char* end() { return const_cast<unsigned char*>(data() + data_.size()); } struct bitmap_file_header { unsigned short type; unsigned int size; unsigned short reserved1; unsigned short reserved2; unsigned int off_bits; unsigned int struct_size() const { return sizeof(type) + sizeof(size) + sizeof(reserved1) + sizeof(reserved2) + sizeof(off_bits); } void clear() { std::memset(this, 0x00, sizeof(bitmap_file_header)); } }; struct bitmap_information_header { unsigned int size; unsigned int width; unsigned int height; unsigned short planes; unsigned short bit_count; unsigned int compression; unsigned int size_image; unsigned int x_pels_per_meter; unsigned int y_pels_per_meter; unsigned int clr_used; unsigned int clr_important; unsigned int struct_size() const { return sizeof(size) + sizeof(width) + sizeof(height) + sizeof(planes) + sizeof(bit_count) + sizeof(compression) + sizeof(size_image) + sizeof(x_pels_per_meter) + sizeof(y_pels_per_meter) + sizeof(clr_used) + sizeof(clr_important); } void clear() { std::memset(this, 0x00, sizeof(bitmap_information_header)); } }; inline bool big_endian() const { unsigned int v = 0x01; return (1 != reinterpret_cast<char*>(&v)[0]); } inline unsigned short flip(const unsigned short& v) const { return ((v >> 8) | (v << 8)); } inline unsigned int flip(const unsigned int& v) const { return ( ((v & 0xFF000000) >> 0x18) | ((v & 0x000000FF) << 0x18) | ((v & 0x00FF0000) >> 0x08) | ((v & 0x0000FF00) << 0x08) ); } template <typename T> inline void read_from_stream(std::ifstream& stream, T& t) { stream.read(reinterpret_cast<char*>(&t), sizeof(T)); } template <typename T> inline void write_to_stream(std::ofstream& stream, const T& t) const { stream.write(reinterpret_cast<const char*>(&t), sizeof(T)); } inline void read_bfh(std::ifstream& stream, bitmap_file_header& bfh) { read_from_stream(stream, bfh.type); read_from_stream(stream, bfh.size); read_from_stream(stream, bfh.reserved1); read_from_stream(stream, bfh.reserved2); read_from_stream(stream, bfh.off_bits); if (big_endian()) { bfh.type = flip(bfh.type); bfh.size = flip(bfh.size); bfh.reserved1 = flip(bfh.reserved1); bfh.reserved2 = flip(bfh.reserved2); bfh.off_bits = flip(bfh.off_bits); } } inline void write_bfh(std::ofstream& stream, const bitmap_file_header& bfh) const { if (big_endian()) { write_to_stream(stream, flip(bfh.type)); write_to_stream(stream, flip(bfh.size)); write_to_stream(stream, flip(bfh.reserved1)); write_to_stream(stream, flip(bfh.reserved2)); write_to_stream(stream, flip(bfh.off_bits)); } else { write_to_stream(stream, bfh.type); write_to_stream(stream, bfh.size); write_to_stream(stream, bfh.reserved1); write_to_stream(stream, bfh.reserved2); write_to_stream(stream, bfh.off_bits); } } inline void read_bih(std::ifstream& stream, bitmap_information_header& bih) { read_from_stream(stream, bih.size); read_from_stream(stream, bih.width); read_from_stream(stream, bih.height); read_from_stream(stream, bih.planes); read_from_stream(stream, bih.bit_count); read_from_stream(stream, bih.compression); read_from_stream(stream, bih.size_image); read_from_stream(stream, bih.x_pels_per_meter); read_from_stream(stream, bih.y_pels_per_meter); read_from_stream(stream, bih.clr_used); read_from_stream(stream, bih.clr_important); if (big_endian()) { bih.size = flip(bih.size); bih.width = flip(bih.width); bih.height = flip(bih.height); bih.planes = flip(bih.planes); bih.bit_count = flip(bih.bit_count); bih.compression = flip(bih.compression); bih.size_image = flip(bih.size_image); bih.x_pels_per_meter = flip(bih.x_pels_per_meter); bih.y_pels_per_meter = flip(bih.y_pels_per_meter); bih.clr_used = flip(bih.clr_used); bih.clr_important = flip(bih.clr_important); } } inline void write_bih(std::ofstream& stream, const bitmap_information_header& bih) const { if (big_endian()) { write_to_stream(stream, flip(bih.size)); write_to_stream(stream, flip(bih.width)); write_to_stream(stream, flip(bih.height)); write_to_stream(stream, flip(bih.planes)); write_to_stream(stream, flip(bih.bit_count)); write_to_stream(stream, flip(bih.compression)); write_to_stream(stream, flip(bih.size_image)); write_to_stream(stream, flip(bih.x_pels_per_meter)); write_to_stream(stream, flip(bih.y_pels_per_meter)); write_to_stream(stream, flip(bih.clr_used)); write_to_stream(stream, flip(bih.clr_important)); } else { write_to_stream(stream, bih.size); write_to_stream(stream, bih.width); write_to_stream(stream, bih.height); write_to_stream(stream, bih.planes); write_to_stream(stream, bih.bit_count); write_to_stream(stream, bih.compression); write_to_stream(stream, bih.size_image); write_to_stream(stream, bih.x_pels_per_meter); write_to_stream(stream, bih.y_pels_per_meter); write_to_stream(stream, bih.clr_used); write_to_stream(stream, bih.clr_important); } } inline std::size_t file_size(const std::string& file_name) const { std::ifstream file(file_name.c_str(), std::ios::in | std::ios::binary); if (!file) return 0; file.seekg(0, std::ios::end); return static_cast<std::size_t>(file.tellg()); } void create_bitmap() { row_increment_ = width_ * bytes_per_pixel_; data_.resize(height_ * row_increment_); } void load_bitmap() { std::ifstream stream(file_name_.c_str(), std::ios::binary); if (!stream) { std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - file " << file_name_ << " not found!" << std::endl; return; } width_ = 0; height_ = 0; bitmap_file_header bfh; bitmap_information_header bih; bfh.clear(); bih.clear(); read_bfh(stream, bfh); read_bih(stream, bih); if (bfh.type != 19778) { bfh.clear(); bih.clear(); stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid type value " << bfh.type << " expected 19778." << std::endl; return; } if (bih.bit_count != 24) { bfh.clear(); bih.clear(); stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid bit depth " << bih.bit_count << " expected 24." << std::endl; return; } if (bih.size != bih.struct_size()) { bfh.clear(); bih.clear(); stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid BIH size " << bih.size << " expected " << bih.struct_size() << std::endl; return; } width_ = bih.width; height_ = bih.height; bytes_per_pixel_ = bih.bit_count >> 3; unsigned int padding = (4 - ((3 * width_) % 4)) % 4; char padding_data[4] = { 0,0,0,0 }; std::size_t bitmap_file_size = file_size(file_name_); std::size_t bitmap_logical_size = (height_ * width_ * bytes_per_pixel_) + (height_ * padding) + bih.struct_size() + bfh.struct_size(); if (bitmap_file_size != bitmap_logical_size) { bfh.clear(); bih.clear(); stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Mismatch between logical and physical sizes of bitmap. " << "Logical: " << bitmap_logical_size << " " << "Physical: " << bitmap_file_size << std::endl; return; } create_bitmap(); for (unsigned int i = 0; i < height_; ++i) { unsigned char* data_ptr = row(height_ - i - 1); // read in inverted row order stream.read(reinterpret_cast<char*>(data_ptr), sizeof(char) * bytes_per_pixel_ * width_); stream.read(padding_data, padding); } } template <typename T> inline T clamp(const T& v, const T& lower_range, const T& upper_range) const { if (v < lower_range) return lower_range; else if (v > upper_range) return upper_range; else return v; } std::string file_name_; unsigned int width_; unsigned int height_; unsigned int row_increment_; unsigned int bytes_per_pixel_; channel_mode channel_mode_; std::vector<unsigned char> data_; }; typedef bitmap_image::rgb_t rgb_t; inline bool operator==(const rgb_t& c0, const rgb_t& c1) { return (c0.red == c1.red) && (c0.green == c1.green) && (c0.blue == c1.blue); } inline bool operator!=(const rgb_t& c0, const rgb_t& c1) { return (c0.red != c1.red) || (c0.green != c1.green) || (c0.blue != c1.blue); } inline std::size_t hamming_distance(const rgb_t& c0, const rgb_t& c1) { std::size_t result = 0; if (c0.red != c1.red) ++result; if (c0.green != c1.green) ++result; if (c0.blue != c1.blue) ++result; return result; } inline rgb_t make_colour(const unsigned int& red, const unsigned int& green, const unsigned int& blue) { rgb_t result; result.red = static_cast<unsigned char>(red); result.green = static_cast<unsigned char>(green); result.blue = static_cast<unsigned char>(blue); return result; } template <typename OutputIterator> inline void generate_colours(const std::size_t& steps, const rgb_t c0, const rgb_t& c1, OutputIterator out) { double dr = ((double)c1.red - (double)c0.red) / steps; double dg = ((double)c1.green - (double)c0.green) / steps; double db = ((double)c1.blue - (double)c0.blue) / steps; for (std::size_t i = 0; i < steps; ++i) { rgb_t c; c.red = static_cast<unsigned char>(c0.red + (i * dr)); c.green = static_cast<unsigned char>(c0.green + (i * dg)); c.blue = static_cast<unsigned char>(c0.blue + (i * db)); *(out++) = c; } } template <typename ResponseImage, typename Palette> inline std::size_t convert_rsp_to_image(const ResponseImage& resp_image, const Palette& palette, bitmap_image& image) { if ( (resp_image.width() > image.width()) || (resp_image.height() > image.height()) ) return 0; for (std::size_t y = 0; y < resp_image.height(); ++y) { for (std::size_t x = 0; x < resp_image.width(); ++x) { const double v = resp_image(x, y); unsigned int index = static_cast<unsigned int>((v < 0) ? 0 : v >(palette.size()) ? (palette.size() - 1) : v); image.set_pixel(x, y, palette[index]); } } return (resp_image.width() * resp_image.height()); } inline void rgb_to_ycbcr(const unsigned int& length, double* red, double* green, double* blue, double* y, double* cb, double* cr) { unsigned int i = 0; while (i < length) { (*y) = 16.0 + (65.481 * (*red) + 128.553 * (*green) + 24.966 * (*blue)); (*cb) = 128.0 + (-37.797 * (*red) + -74.203 * (*green) + 112.000 * (*blue)); (*cr) = 128.0 + (112.000 * (*red) + -93.786 * (*green) - 18.214 * (*blue)); ++i; ++red; ++green; ++blue; ++y; ++cb; ++cr; } } inline void ycbcr_to_rgb(const unsigned int& length, double* y, double* cb, double* cr, double* red, double* green, double* blue) { unsigned int i = 0; while (i < length) { double y_ = (*y) - 16.0; double cb_ = (*cb) - 128.0; double cr_ = (*cr) - 128.0; (*red) = 0.000456621 * y_ + 0.00625893 * cr_; (*green) = 0.000456621 * y_ - 0.00153632 * cb_ - 0.00318811 * cr_; (*blue) = 0.000456621 * y_ + 0.00791071 * cb_; ++i; ++red; ++green; ++blue; ++y; ++cb; ++cr; } } inline void subsample(const unsigned int& width, const unsigned int& height, const double* source, unsigned int& w, unsigned int& h, double*& dest) { /* Single channel. */ w = 0; h = 0; bool odd_width = false; bool odd_height = false; if (0 == (width % 2)) w = width / 2; else { w = 1 + (width / 2); odd_width = true; } if (0 == (height % 2)) h = height / 2; else { h = 1 + (height / 2); odd_height = true; } unsigned int horizontal_upper = (odd_width) ? w - 1 : w; unsigned int vertical_upper = (odd_height) ? h - 1 : h; dest = new double[w * h]; double* s_itr = dest; const double* itr1 = source; const double* itr2 = source + width; for (unsigned int j = 0; j < vertical_upper; ++j) { for (unsigned int i = 0; i < horizontal_upper; ++i, ++s_itr) { (*s_itr) = *(itr1++); (*s_itr) += *(itr1++); (*s_itr) += *(itr2++); (*s_itr) += *(itr2++); (*s_itr) /= 4.0; } if (odd_width) { (*(s_itr++)) = ((*itr1++) + (*itr2++)) / 2.0; } itr1 += width; if (j != (vertical_upper - 1)) { itr2 += width; } } if (odd_height) { for (unsigned int i = 0; i < horizontal_upper; ++i, ++s_itr) { (*s_itr) += (*(itr1++)); (*s_itr) += (*(itr1++)); (*s_itr) /= 2.0; } if (odd_width) { (*(s_itr++)) = (*itr1); } } } inline void upsample(const unsigned int& width, const unsigned int& height, const double* source, unsigned int& w, unsigned int& h, double*& dest) { /* Single channel. */ w = 2 * width; h = 2 * height; dest = new double[w * h]; const double* s_itr = source; double* itr1 = dest; double* itr2 = dest + w; for (unsigned int j = 0; j < height; ++j) { for (unsigned int i = 0; i < width; ++i, ++s_itr) { *(itr1++) = (*s_itr); *(itr1++) = (*s_itr); *(itr2++) = (*s_itr); *(itr2++) = (*s_itr); } itr1 += w; itr2 += w; } } inline void checkered_pattern(const unsigned int x_width, const unsigned int y_width, const unsigned char value, const bitmap_image::color_plane color, bitmap_image& image) { if ( (x_width >= image.width()) || (y_width >= image.height()) ) { return; } bool setter_x = false; bool setter_y = true; const unsigned int color_plane_offset = image.offset(color); const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int y = 0; y < height; ++y) { if (0 == (y % y_width)) { setter_y = !setter_y; } unsigned char* row = image.row(y) + color_plane_offset; for (unsigned int x = 0; x < width; ++x, row += image.bytes_per_pixel()) { if (0 == (x % x_width)) { setter_x = !setter_x; } if (setter_x ^ setter_y) { *row = value; } } } } inline void checkered_pattern(const unsigned int x_width, const unsigned int y_width, const unsigned char red, const unsigned char green, const unsigned char blue, bitmap_image& image) { if ( (x_width >= image.width()) || (y_width >= image.height()) ) { return; } bool setter_x = false; bool setter_y = true; const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int y = 0; y < height; ++y) { if (0 == (y % y_width)) { setter_y = !setter_y; } unsigned char* row = image.row(y); for (unsigned int x = 0; x < width; ++x, row += image.bytes_per_pixel()) { if (0 == (x % x_width)) { setter_x = !setter_x; } if (setter_x ^ setter_y) { *(row + 0) = blue; *(row + 1) = green; *(row + 2) = red; } } } } inline void plasma(bitmap_image& image, const double& x, const double& y, const double& width, const double& height, const double& c1, const double& c2, const double& c3, const double& c4, const double& roughness = 3.0, const rgb_t colormap[] = 0) { // Note: c1,c2,c3,c4 -> [0.0,1.0] const double half_width = (width / 2.0); const double half_height = (height / 2.0); if ((width >= 1.0) || (height >= 1.0)) { const double corner1 = (c1 + c2) / 2.0; const double corner2 = (c2 + c3) / 2.0; const double corner3 = (c3 + c4) / 2.0; const double corner4 = (c4 + c1) / 2.0; double center = (c1 + c2 + c3 + c4) / 4.0 + ((1.0 * ::rand() / (1.0 * RAND_MAX)) - 0.5) * // should use a better rng ((1.0 * half_width + half_height) / (image.width() + image.height()) * roughness); center = std::min<double>(std::max<double>(0.0, center), 1.0); plasma(image, x, y, half_width, half_height, c1, corner1, center, corner4, roughness, colormap); plasma(image, x + half_width, y, half_width, half_height, corner1, c2, corner2, center, roughness, colormap); plasma(image, x + half_width, y + half_height, half_width, half_height, center, corner2, c3, corner3, roughness, colormap); plasma(image, x, y + half_height, half_width, half_height, corner4, center, corner3, c4, roughness, colormap); } else { rgb_t color = colormap[static_cast<unsigned int>(1000.0 * ((c1 + c2 + c3 + c4) / 4.0)) % 1000]; image.set_pixel(static_cast<unsigned int>(x), static_cast<unsigned int>(y), color); } } inline void plasma(bitmap_image& image, const double& c1, const double& c2, const double& c3, const double& c4, const double& roughness = 3.0, const rgb_t colormap[] = 0) { plasma ( image, 0, 0, image.width(), image.height(), c1, c2, c3, c4, roughness, colormap ); } inline double psnr_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const bitmap_image& image1, const bitmap_image& image2) { if ( (image1.width() != image2.width()) || (image1.height() != image2.height()) ) { return 0.0; } if ((x + width) > image1.width()) { return 0.0; } if ((y + height) > image1.height()) { return 0.0; } double mse = 0.0; for (unsigned int r = 0; r < height; ++r) { const unsigned char* itr1 = image1.row(r + y) + x * image1.bytes_per_pixel(); const unsigned char* itr1_end = itr1 + (width * image1.bytes_per_pixel()); const unsigned char* itr2 = image2.row(r + y) + x * image2.bytes_per_pixel(); while (itr1 != itr1_end) { double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * width * height); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline void hierarchical_psnr_r(const double& x, const double& y, const double& width, const double& height, const bitmap_image& image1, bitmap_image& image2, const double& threshold, const rgb_t colormap[]) { if ((width <= 4.0) || (height <= 4.0)) { const double psnr = psnr_region ( static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(width), static_cast<unsigned int>(height), image1, image2 ); if (psnr < threshold) { rgb_t c = colormap[static_cast<unsigned int>(1000.0 * (1.0 - (psnr / threshold)))]; image2.set_region ( static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(width + 1), static_cast<unsigned int>(height + 1), c.red, c.green, c.blue ); } } else { const double half_width = (width / 2.0); const double half_height = (height / 2.0); hierarchical_psnr_r(x, y, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x + half_width, y, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x + half_width, y + half_height, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x, y + half_height, half_width, half_height, image1, image2, threshold, colormap); } } inline void hierarchical_psnr(bitmap_image& image1, bitmap_image& image2, const double threshold, const rgb_t colormap[]) { if ( (image1.width() != image2.width()) || (image1.height() != image2.height()) ) { return; } const double psnr = psnr_region ( 0, 0, image1.width(), image1.height(), image1, image2 ); if (psnr < threshold) { hierarchical_psnr_r ( 0, 0, image1.width(), image1.height(), image1, image2, threshold, colormap ); } } class image_drawer { public: image_drawer(bitmap_image& image) : image_(image), pen_width_(1), pen_color_red_(0), pen_color_green_(0), pen_color_blue_(0) {} void rectangle(int x1, int y1, int x2, int y2) { line_segment(x1, y1, x2, y1); line_segment(x2, y1, x2, y2); line_segment(x2, y2, x1, y2); line_segment(x1, y2, x1, y1); } void triangle(int x1, int y1, int x2, int y2, int x3, int y3) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x1, y1); } void quadix(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x4, y4); line_segment(x4, y4, x1, y1); } void line_segment(int x1, int y1, int x2, int y2) { int steep = 0; int sx = ((x2 - x1) > 0) ? 1 : -1; int sy = ((y2 - y1) > 0) ? 1 : -1; int dx = abs(x2 - x1); int dy = abs(y2 - y1); if (dy > dx) { std::swap(x1, y1); std::swap(dx, dy); std::swap(sx, sy); steep = 1; } int e = 2 * dy - dx; for (int i = 0; i < dx; ++i) { if (steep) plot_pen_pixel(y1, x1); else plot_pen_pixel(x1, y1); while (e >= 0) { y1 += sy; e -= (dx << 1); } x1 += sx; e += (dy << 1); } plot_pen_pixel(x2, y2); } void horiztonal_line_segment(int x1, int x2, int y) { if (x1 > x2) { std::swap(x1, x2); } for (int i = 0; i < (x2 - x1); ++i) { plot_pen_pixel(x1 + i, y); } } void vertical_line_segment(int y1, int y2, int x) { if (y1 > y2) { std::swap(y1, y2); } for (int i = 0; i < (y2 - y1); ++i) { plot_pen_pixel(x, y1 + i); } } void ellipse(int centerx, int centery, int a, int b) { int t1 = a * a; int t2 = t1 << 1; int t3 = t2 << 1; int t4 = b * b; int t5 = t4 << 1; int t6 = t5 << 1; int t7 = a * t5; int t8 = t7 << 1; int t9 = 0; int d1 = t2 - t7 + (t4 >> 1); int d2 = (t1 >> 1) - t8 + t5; int x = a; int y = 0; int negative_tx = centerx - x; int positive_tx = centerx + x; int negative_ty = centery - y; int positive_ty = centery + y; while (d2 < 0) { plot_pen_pixel(positive_tx, positive_ty); plot_pen_pixel(positive_tx, negative_ty); plot_pen_pixel(negative_tx, positive_ty); plot_pen_pixel(negative_tx, negative_ty); ++y; t9 = t9 + t3; if (d1 < 0) { d1 = d1 + t9 + t2; d2 = d2 + t9; } else { x--; t8 = t8 - t6; d1 = d1 + (t9 + t2 - t8); d2 = d2 + (t9 + t5 - t8); negative_tx = centerx - x; positive_tx = centerx + x; } negative_ty = centery - y; positive_ty = centery + y; } do { plot_pen_pixel(positive_tx, positive_ty); plot_pen_pixel(positive_tx, negative_ty); plot_pen_pixel(negative_tx, positive_ty); plot_pen_pixel(negative_tx, negative_ty); x--; t8 = t8 - t6; if (d2 < 0) { ++y; t9 = t9 + t3; d2 = d2 + (t9 + t5 - t8); negative_ty = centery - y; positive_ty = centery + y; } else d2 = d2 + (t5 - t8); negative_tx = centerx - x; positive_tx = centerx + x; } while (x >= 0); } void circle(int centerx, int centery, int radius) { int x = 0; int d = (1 - radius) << 1; while (radius >= 0) { plot_pen_pixel(centerx + x, centery + radius); plot_pen_pixel(centerx + x, centery - radius); plot_pen_pixel(centerx - x, centery + radius); plot_pen_pixel(centerx - x, centery - radius); if ((d + radius) > 0) d -= ((--radius) << 1) - 1; if (x > d) d += ((++x) << 1) + 1; } } void plot_pen_pixel(int x, int y) { switch (pen_width_) { case 1: plot_pixel(x, y); break; case 2: { plot_pixel(x, y); plot_pixel(x + 1, y); plot_pixel(x + 1, y + 1); plot_pixel(x, y + 1); } break; case 3: { plot_pixel(x, y - 1); plot_pixel(x - 1, y - 1); plot_pixel(x + 1, y - 1); plot_pixel(x, y); plot_pixel(x - 1, y); plot_pixel(x + 1, y); plot_pixel(x, y + 1); plot_pixel(x - 1, y + 1); plot_pixel(x + 1, y + 1); } break; default: plot_pixel(x, y); break; } } void plot_pixel(int x, int y) { if ( (x < 0) || (y < 0) || (x >= static_cast<int>(image_.width())) || (y >= static_cast<int>(image_.height())) ) return; image_.set_pixel(x, y, pen_color_red_, pen_color_green_, pen_color_blue_); } void pen_width(const unsigned int& width) { if ((width > 0) && (width < 4)) { pen_width_ = width; } } void pen_color(const unsigned char& red, const unsigned char& green, const unsigned char& blue) { pen_color_red_ = red; pen_color_green_ = green; pen_color_blue_ = blue; } template <typename RGB> void pen_color(const RGB colour) { pen_color_red_ = colour.red; pen_color_green_ = colour.green; pen_color_blue_ = colour.blue; } private: image_drawer(const image_drawer& id); image_drawer& operator =(const image_drawer& id); bitmap_image& image_; unsigned int pen_width_; unsigned char pen_color_red_; unsigned char pen_color_green_; unsigned char pen_color_blue_; }; class cartesian_canvas { public: cartesian_canvas(const double x_length, const double y_length) : width_div2_(0.0), height_div2_(0.0), min_x_(0.0), min_y_(0.0), max_x_(0.0), max_y_(0.0), draw_(image_) { setup_canvas(x_length, y_length); } inline bool operator!() { return !image_; } void rectangle(double x1, double y1, double x2, double y2) { line_segment(x1, y1, x2, y1); line_segment(x2, y1, x2, y2); line_segment(x2, y2, x1, y2); line_segment(x1, y2, x1, y1); } void triangle(double x1, double y1, double x2, double y2, double x3, double y3) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x1, y1); } void quadix(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x4, y4); line_segment(x4, y4, x1, y1); } void line_segment(double x1, double y1, double x2, double y2) { if (clip(x1, y1, x2, y2)) { const int sc_x1 = static_cast<int>(cart_to_screen_x(x1)); const int sc_x2 = static_cast<int>(cart_to_screen_x(x2)); const int sc_y1 = static_cast<int>(cart_to_screen_y(y1)); const int sc_y2 = static_cast<int>(cart_to_screen_y(y2)); draw_.line_segment(sc_x1, sc_y1, sc_x2, sc_y2); } } void horiztonal_line_segment(double x1, double x2, double y) { x1 = clamp_x(x1); x2 = clamp_x(x2); y = clamp_y(y); const int sc_x1 = static_cast<int>(cart_to_screen_x(x1)); const int sc_x2 = static_cast<int>(cart_to_screen_x(x2)); const int sc_y = static_cast<int>(cart_to_screen_y(y)); draw_.horiztonal_line_segment(sc_x1, sc_x2, sc_y); } void vertical_line_segment(double y1, double y2, double x) { y1 = clamp_y(y1); y2 = clamp_y(y2); x = clamp_x(x); const int sc_y1 = static_cast<int>(cart_to_screen_y(y1)); const int sc_y2 = static_cast<int>(cart_to_screen_y(y2)); const int sc_x = static_cast<int>(cart_to_screen_x(x)); draw_.vertical_line_segment(sc_y1, sc_y2, sc_x); } void ellipse(double centerx, double centery, double a, double b) { const int sc_cx = static_cast<int>(cart_to_screen_x(centerx)); const int sc_cy = static_cast<int>(cart_to_screen_y(centery)); draw_.ellipse(sc_cx, sc_cy, static_cast<int>(a), static_cast<int>(b)); } void circle(double centerx, double centery, double radius) { const int sc_cx = static_cast<int>(cart_to_screen_x(centerx)); const int sc_cy = static_cast<int>(cart_to_screen_y(centery)); draw_.circle(sc_cx, sc_cy, static_cast<int>(radius)); } void fill_rectangle(double x1, double y1, double x2, double y2) { if (y1 > y2) std::swap(y1, y2); for (double y = y1; y <= y2; y += 0.5) { line_segment(x1, y, x2, y); } } void fill_triangle(double x1, double y1, double x2, double y2, double x3, double y3) { typedef std::pair<double, double> point_t; std::vector<point_t> p; p.push_back(std::make_pair(x1, y1)); p.push_back(std::make_pair(x2, y2)); p.push_back(std::make_pair(x3, y3)); if (p[0].second > p[1].second) std::swap(p[0], p[1]); if (p[0].second > p[2].second) std::swap(p[0], p[2]); if (p[1].second > p[2].second) std::swap(p[1], p[2]); class draw_modes { private: cartesian_canvas & canvas; // Needed for incompetent and broken msvc compiler versions #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4822) #endif draw_modes& operator=(const draw_modes&); #ifdef _MSC_VER #pragma warning(pop) #endif public: draw_modes(cartesian_canvas& c) : canvas(c) {} void bottom(const point_t& p0, const point_t& p1, const point_t& p2) { const double m0 = (p1.first - p0.first) / (2.0 * (p1.second - p0.second)); const double m1 = (p2.first - p0.first) / (2.0 * (p2.second - p0.second)); double x0 = p0.first; double x1 = p0.first; for (double y = p0.second; y <= p1.second; y += 0.5) { canvas.horiztonal_line_segment(x0, x1, y); x0 += m0; x1 += m1; } } void top(const point_t& p0, const point_t& p1, const point_t& p2) { const double m0 = (p2.first - p0.first) / (2.0 * (p2.second - p0.second)); const double m1 = (p2.first - p1.first) / (2.0 * (p2.second - p1.second)); double x0 = p2.first; double x1 = p2.first; for (double y = p2.second; y >= p0.second; y -= 0.5) { canvas.horiztonal_line_segment(x0, x1, y); x0 -= m0; x1 -= m1; } } }; draw_modes dm(*this); const double eps = 0.00001; if (std::abs(p[1].second - p[2].second) < eps) dm.bottom(p[0], p[1], p[2]); else if (std::abs(p[0].second - p[1].second) < eps) dm.top(p[0], p[1], p[2]); else { point_t p3; p3.first = (p[0].first + ((p[1].second - p[0].second) / (p[2].second - p[0].second)) * (p[2].first - p[0].first)); p3.second = p[1].second; dm.bottom(p[0], p[1], p3); dm.top(p[1], p3, p[2]); } } void fill_quadix(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { fill_triangle(x1, y1, x2, y2, x3, y3); fill_triangle(x1, y1, x3, y3, x4, y4); } void fill_circle(double cx, double cy, double radius) { const double delta = 1.0; double x = radius; double y = 0.0; double dx = delta - (2.0 * delta * radius); double dy = 0.0; double dr = 0.0; while (x >= y) { for (double i = cx - x; i <= cx + x; i += delta) { horiztonal_line_segment(cx - x, cx + x, cy + y); horiztonal_line_segment(cx - x, cx + x, cy - y); } for (double i = cx - y; i <= cx + y; i += delta) { horiztonal_line_segment(cx - y, cx + y, cy + x); horiztonal_line_segment(cx - y, cx + y, cy - x); } y += delta; dr += dy; dy += 2.0 * delta; if ((2.0 * delta * dr + dx) > 0) { x -= delta; dr += dx; dx += 2.0 * delta; } } } void plot_pen_pixel(double x, double y) { if ((x < min_x_) || (x > max_x_)) return; if ((y < min_y_) || (y > max_y_)) return; const int sc_x = static_cast<int>(cart_to_screen_x(x)); const int sc_y = static_cast<int>(cart_to_screen_y(y)); draw_.plot_pen_pixel(sc_x, sc_y); } void plot_pixel(double x, double y) { if ((x < min_x_) || (x > max_x_)) return; if ((y < min_y_) || (y > max_y_)) return; const int sc_x = static_cast<int>(cart_to_screen_x(x)); const int sc_y = static_cast<int>(cart_to_screen_y(y)); draw_.plot_pixel(sc_x, sc_y); } void pen_width(const unsigned int& width) { draw_.pen_width(width); } void pen_color(const unsigned char& red, const unsigned char& green, const unsigned char& blue) { draw_.pen_color(red, green, blue); } template <typename RGB> void pen_color(const RGB colour) { draw_.pen_color(colour); } const bitmap_image& image() const { return image_; } bitmap_image& image() { return image_; } void set_widthheight(const double x_length, const double y_length) { setup_canvas(x_length, y_length); } double min_x() const { return min_x_; } double min_y() const { return min_y_; } double max_x() const { return max_x_; } double max_y() const { return max_y_; } private: void setup_canvas(const double x_length, const double y_length) { if ((x_length < 2.0) || (y_length < 2.0)) return; width_div2_ = x_length / 2.0; height_div2_ = y_length / 2.0; min_x_ = -width_div2_; min_y_ = -height_div2_; max_x_ = width_div2_; max_y_ = height_div2_; image_.setwidth_height(static_cast<unsigned int>(x_length) + 1, static_cast<unsigned int>(y_length) + 1); image_.clear(0xFF); } double clamp_x(const double& x) { if (x < min_x_) return min_x_; else if (x > max_x_) return max_x_; else return x; } double clamp_y(const double& y) { if (y < min_y_) return min_y_; else if (y > max_y_) return max_y_; else return y; } double cart_to_screen_x(const double& x) { return x + width_div2_; } double cart_to_screen_y(const double& y) { return height_div2_ - y; } enum clip_code { e_clip_bottom = 1, e_clip_top = 2, e_clip_left = 4, e_clip_right = 8 }; int out_code( const double& x, const double& y, const double& x1, const double& y1, const double& x2, const double& y2 ) { int result = 0; if (y < y1) result |= e_clip_bottom; else if (y > y2) result |= e_clip_top; if (x < x1) result |= e_clip_left; else if (x > x2) result |= e_clip_right; return result; } bool clip(double& x1, double& y1, double& x2, double& y2) { bool result = false; double x = 0.0; double y = 0.0; int outcode0 = out_code(x1, y1, min_x_, min_y_, max_x_, max_y_); int outcode1 = out_code(x2, y2, min_x_, min_y_, max_x_, max_y_); int outcodeout = 0; while ((outcode0 != 0) || (outcode1 != 0)) { if ((outcode0 & outcode1) != 0) return result; else { if (outcode0 != 0) outcodeout = outcode0; else outcodeout = outcode1; double dx = (x2 - x1); double dy = (y2 - y1); if ((outcodeout & e_clip_bottom) == e_clip_bottom) { x = x1 + dx * (min_y_ - y1) / dy; y = min_y_; } else if ((outcodeout & e_clip_top) == e_clip_top) { x = x1 + dx * (max_y_ - y1) / dy; y = max_y_; } else if ((outcodeout & e_clip_right) == e_clip_right) { y = y1 + dy * (max_x_ - x1) / dx; x = max_x_; } else if ((outcodeout & e_clip_left) == e_clip_left) { y = y1 + dy * (min_x_ - x1) / dx; x = min_x_; } if (outcodeout == outcode0) { x1 = x; y1 = y; outcode0 = out_code(x1, y1, min_x_, min_y_, max_x_, max_y_); } else { x2 = x; y2 = y; outcode1 = out_code(x2, y2, min_x_, min_y_, max_x_, max_y_); } } } return true; } cartesian_canvas(const cartesian_canvas&); cartesian_canvas operator=(const cartesian_canvas&); double width_div2_; double height_div2_; double min_x_; double min_y_; double max_x_; double max_y_; bitmap_image image_; image_drawer draw_; }; inline rgb_t convert_wave_length_nm_to_rgb(const double wave_length_nm) { // Credits: Dan Bruton http://www.physics.sfasu.edu/astro/color.html double red = 0.0; double green = 0.0; double blue = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 439.0)) { red = -(wave_length_nm - 440.0) / (440.0 - 380.0); green = 0.0; blue = 1.0; } else if ((440.0 <= wave_length_nm) && (wave_length_nm <= 489.0)) { red = 0.0; green = (wave_length_nm - 440.0) / (490.0 - 440.0); blue = 1.0; } else if ((490.0 <= wave_length_nm) && (wave_length_nm <= 509.0)) { red = 0.0; green = 1.0; blue = -(wave_length_nm - 510.0) / (510.0 - 490.0); } else if ((510.0 <= wave_length_nm) && (wave_length_nm <= 579.0)) { red = (wave_length_nm - 510.0) / (580.0 - 510.0); green = 1.0; blue = 0.0; } else if ((580.0 <= wave_length_nm) && (wave_length_nm <= 644.0)) { red = 1.0; green = -(wave_length_nm - 645.0) / (645.0 - 580.0); blue = 0.0; } else if ((645.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) { red = 1.0; green = 0.0; blue = 0.0; } double factor = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 419.0)) factor = 0.3 + 0.7 * (wave_length_nm - 380.0) / (420.0 - 380.0); else if ((420.0 <= wave_length_nm) && (wave_length_nm <= 700.0)) factor = 1.0; else if ((701.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) factor = 0.3 + 0.7 * (780.0 - wave_length_nm) / (780.0 - 700.0); else factor = 0.0; rgb_t result; const double gamma = 0.8; const double intensity_max = 255.0; #define round(d) std::floor(d + 0.5) result.red = static_cast<unsigned char>((red == 0.0) ? red : round(intensity_max * std::pow(red * factor, gamma))); result.green = static_cast<unsigned char>((green == 0.0) ? green : round(intensity_max * std::pow(green * factor, gamma))); result.blue = static_cast<unsigned char>((blue == 0.0) ? blue : round(intensity_max * std::pow(blue * factor, gamma))); #undef round return result; } inline double weighted_distance(const unsigned char r0, const unsigned char g0, const unsigned char b0, const unsigned char r1, const unsigned char g1, const unsigned char b1) { const double diff_r = /*0.30 */ (r0 - r1); const double diff_g = /*0.59 */ (g0 - g1); const double diff_b = /*0.11 */ (b0 - b1); return std::sqrt((diff_r * diff_r) + (diff_g * diff_g) + (diff_b * diff_b)); } inline double weighted_distance(const rgb_t c0, const rgb_t c1) { return weighted_distance(c0.red, c0.green, c0.blue, c1.red, c1.green, c1.blue); } template <typename Iterator> inline rgb_t find_nearest_color(const rgb_t& c, const Iterator begin, const Iterator end) { if (0 == std::distance(begin, end)) return c; double min_d = std::numeric_limits<double>::max(); rgb_t result = *begin; for (Iterator itr = begin; itr != end; ++itr) { if (c == (*itr)) { return (*itr); } double curr_d = weighted_distance(c, *itr); if (curr_d < min_d) { min_d = curr_d; result = *itr; } } return result; } template <template <typename, typename> class Sequence, typename Allocator> inline rgb_t find_nearest_color(const rgb_t& c, const Sequence<rgb_t, Allocator>& seq) { return find_nearest_color(c, seq.begin(), seq.end()); } template <std::size_t N> inline rgb_t find_nearest_color(const rgb_t& c, const rgb_t(&colors)[N]) { return find_nearest_color(c, colors, colors + N); } inline double find_nearest_wave_length(const rgb_t& c, const double increment = 0.001) { const double max_wave_length = 800.0; //800nm double min_wave_length = 0.0; double min_d = std::numeric_limits<double>::max(); for (double i = 0.0; i < max_wave_length; i += increment) { const rgb_t curr_rgb = convert_wave_length_nm_to_rgb(i); if (c == curr_rgb) { return i; } const double curr_d = weighted_distance(c, curr_rgb); if (curr_d <= min_d) { min_wave_length = i; min_d = curr_d; } } return min_wave_length; } template <typename T> class response_image { public: response_image(const std::size_t& width, const std::size_t& height, const T null = T(0)) : width_(width), height_(height), null_(null) { data_.resize(width_ * height_); } std::size_t width() const { return width_; } std::size_t height() const { return height_; } void set_all(const T& t) { std::fill_n(data_.begin(), data_.size(), t); } const T& operator()(const std::size_t& x, const std::size_t& y) const { if (y >= height_) return null_; if (x >= width_) return null_; return data_[width_ * y + x]; } T& operator()(const std::size_t& x, const std::size_t& y) { if (y >= height_) return null_; if (x >= width_) return null_; return data_[width_ * y + x]; } bool valid(const std::size_t& x, const std::size_t& y) { return ((x < width_) || (y < height_)); } void inc_all(const T& v) { for (std::size_t i = 0; i < data_.size(); ++i) { data_[i] += v; } } void mul_all(const T& v) { for (std::size_t i = 0; i < data_.size(); ++i) { data_[i] *= v; } } T* row(const std::size_t& row_index) { if (row_index < height_) return &data_[width_ * row_index]; else return reinterpret_cast<T*>(0); } const T* row(const std::size_t& row_index) const { if (row_index < height_) return data_[width_ * row_index]; else return reinterpret_cast<T*>(0); } private: std::size_t width_; std::size_t height_; std::vector<T> data_; T null_; }; inline void sobel_operator(const bitmap_image& src_image, bitmap_image& dst_image, const double threshold = 0.0) { typedef double T; response_image<T> im0(src_image.width(), src_image.height(), 0.0); response_image<T> im1(src_image.width(), src_image.height(), 0.0); src_image.export_gray_scale_response_image(&im0(0, 0)); for (std::size_t y = 1; y < im0.height() - 1; ++y) { const T* itr0 = im0.row(y - 1); const T* itr1 = im0.row(y); const T* itr2 = im0.row(y + 1); T* out = im1.row(y) + 1; for (std::size_t x = 1; x < im0.width() - 1; ++x) { const T c0 = *(itr0 + x - 1); const T c1 = *(itr0 + x); const T c2 = *(itr0 + x + 1); const T c3 = *(itr1 + x - 1); /*const T c4 = *(itr1 + x);*/ const T c5 = *(itr1 + x + 1); const T c6 = *(itr2 + x - 1); const T c7 = *(itr2 + x); const T c8 = *(itr2 + x + 1); const T gx = (2.0 * (c5 - c3)) + (c2 - c0) + (c8 - c6); const T gy = (2.0 * (c1 - c7)) + (c0 - c6) + (c2 - c8); *(out++) = std::sqrt((gx * gx) + (gy * gy)); } } if (threshold > 0.0) { const T* end = im1.row(0) + (im1.width() * im1.height()); for (T* itr = im1.row(0); itr != end; ++itr) { T& v = *itr; if (v <= threshold) v = 0; } } dst_image.setwidth_height ( static_cast<unsigned int>(im1.width()), static_cast<unsigned int>(im1.height()) ); dst_image.import_gray_scale_clamped(&im1(0, 0)); } enum palette_name { e_red, e_scarlet, e_vermilion, e_tangelo, e_orange, e_gamboge, e_amber, e_gold, e_yellow, e_apple_green, e_lime_green, e_spring_bud, e_chartreuse_green, e_pistachio, e_harlequin, e_sap_green, e_green, e_emerald_green, e_malachite_green, e_sea_green, e_spring_green, e_aquamarine, e_turquoise, e_opal, e_cyan, e_arctic_blue, e_cerulean, e_cornflower_blue, e_azure, e_cobalt_blue, e_sapphire_blue, e_phthalo_blue, e_blue, e_persian_blue, e_indigo, e_blue_violet, e_violet, e_purple, e_mulberry, e_heliotrope, e_magenta, e_orchid, e_fuchsia, e_cerise, e_rose, e_raspberry, e_crimson, e_amaranth, e_white, e_black }; const rgb_t palette_colormap[] = { { 255, 0, 0 },{ 255, 31, 0 },{ 255, 63, 0 },{ 255, 95, 0 },{ 255, 127, 0 }, { 255, 159, 0 },{ 255, 191, 0 },{ 255, 223, 0 },{ 255, 255, 0 },{ 223, 255, 0 }, { 191, 255, 0 },{ 159, 255, 0 },{ 127, 255, 0 },{ 95, 255, 0 },{ 63, 255, 0 }, { 31, 255, 0 },{ 0, 255, 0 },{ 0, 255, 31 },{ 0, 255, 63 },{ 0, 255, 95 }, { 0, 255, 127 },{ 0, 255, 159 },{ 0, 255, 191 },{ 0, 255, 223 },{ 0, 255, 255 }, { 0, 223, 255 },{ 0, 191, 255 },{ 0, 159, 255 },{ 0, 127, 255 },{ 0, 95, 255 }, { 0, 63, 255 },{ 0, 31, 255 },{ 0, 0, 255 },{ 31, 0, 255 },{ 63, 0, 255 }, { 95, 0, 255 },{ 127, 0, 255 },{ 159, 0, 255 },{ 191, 0, 255 },{ 223, 0, 255 }, { 255, 0, 255 },{ 255, 0, 223 },{ 255, 0, 191 },{ 255, 0, 159 },{ 255, 0, 127 }, { 255, 0, 95 },{ 255, 0, 63 },{ 255, 0, 31 },{ 255, 255, 255 },{ 0, 0, 0 } }; const rgb_t autumn_colormap[1000] = { { 255, 0, 0 },{ 255, 0, 0 },{ 255, 1, 0 },{ 255, 1, 0 },{ 255, 1, 0 }, { 255, 1, 0 },{ 255, 2, 0 },{ 255, 2, 0 },{ 255, 2, 0 },{ 255, 2, 0 }, { 255, 3, 0 },{ 255, 3, 0 },{ 255, 3, 0 },{ 255, 3, 0 },{ 255, 4, 0 }, { 255, 4, 0 },{ 255, 4, 0 },{ 255, 4, 0 },{ 255, 5, 0 },{ 255, 5, 0 }, { 255, 5, 0 },{ 255, 5, 0 },{ 255, 6, 0 },{ 255, 6, 0 },{ 255, 6, 0 }, { 255, 6, 0 },{ 255, 7, 0 },{ 255, 7, 0 },{ 255, 7, 0 },{ 255, 7, 0 }, { 255, 8, 0 },{ 255, 8, 0 },{ 255, 8, 0 },{ 255, 8, 0 },{ 255, 9, 0 }, { 255, 9, 0 },{ 255, 9, 0 },{ 255, 9, 0 },{ 255, 10, 0 },{ 255, 10, 0 }, { 255, 10, 0 },{ 255, 10, 0 },{ 255, 11, 0 },{ 255, 11, 0 },{ 255, 11, 0 }, { 255, 11, 0 },{ 255, 12, 0 },{ 255, 12, 0 },{ 255, 12, 0 },{ 255, 13, 0 }, { 255, 13, 0 },{ 255, 13, 0 },{ 255, 13, 0 },{ 255, 14, 0 },{ 255, 14, 0 }, { 255, 14, 0 },{ 255, 14, 0 },{ 255, 15, 0 },{ 255, 15, 0 },{ 255, 15, 0 }, { 255, 15, 0 },{ 255, 16, 0 },{ 255, 16, 0 },{ 255, 16, 0 },{ 255, 16, 0 }, { 255, 17, 0 },{ 255, 17, 0 },{ 255, 17, 0 },{ 255, 17, 0 },{ 255, 18, 0 }, { 255, 18, 0 },{ 255, 18, 0 },{ 255, 18, 0 },{ 255, 19, 0 },{ 255, 19, 0 }, { 255, 19, 0 },{ 255, 19, 0 },{ 255, 20, 0 },{ 255, 20, 0 },{ 255, 20, 0 }, { 255, 20, 0 },{ 255, 21, 0 },{ 255, 21, 0 },{ 255, 21, 0 },{ 255, 21, 0 }, { 255, 22, 0 },{ 255, 22, 0 },{ 255, 22, 0 },{ 255, 22, 0 },{ 255, 23, 0 }, { 255, 23, 0 },{ 255, 23, 0 },{ 255, 23, 0 },{ 255, 24, 0 },{ 255, 24, 0 }, { 255, 24, 0 },{ 255, 25, 0 },{ 255, 25, 0 },{ 255, 25, 0 },{ 255, 25, 0 }, { 255, 26, 0 },{ 255, 26, 0 },{ 255, 26, 0 },{ 255, 26, 0 },{ 255, 27, 0 }, { 255, 27, 0 },{ 255, 27, 0 },{ 255, 27, 0 },{ 255, 28, 0 },{ 255, 28, 0 }, { 255, 28, 0 },{ 255, 28, 0 },{ 255, 29, 0 },{ 255, 29, 0 },{ 255, 29, 0 }, { 255, 29, 0 },{ 255, 30, 0 },{ 255, 30, 0 },{ 255, 30, 0 },{ 255, 30, 0 }, { 255, 31, 0 },{ 255, 31, 0 },{ 255, 31, 0 },{ 255, 31, 0 },{ 255, 32, 0 }, { 255, 32, 0 },{ 255, 32, 0 },{ 255, 32, 0 },{ 255, 33, 0 },{ 255, 33, 0 }, { 255, 33, 0 },{ 255, 33, 0 },{ 255, 34, 0 },{ 255, 34, 0 },{ 255, 34, 0 }, { 255, 34, 0 },{ 255, 35, 0 },{ 255, 35, 0 },{ 255, 35, 0 },{ 255, 35, 0 }, { 255, 36, 0 },{ 255, 36, 0 },{ 255, 36, 0 },{ 255, 37, 0 },{ 255, 37, 0 }, { 255, 37, 0 },{ 255, 37, 0 },{ 255, 38, 0 },{ 255, 38, 0 },{ 255, 38, 0 }, { 255, 38, 0 },{ 255, 39, 0 },{ 255, 39, 0 },{ 255, 39, 0 },{ 255, 39, 0 }, { 255, 40, 0 },{ 255, 40, 0 },{ 255, 40, 0 },{ 255, 40, 0 },{ 255, 41, 0 }, { 255, 41, 0 },{ 255, 41, 0 },{ 255, 41, 0 },{ 255, 42, 0 },{ 255, 42, 0 }, { 255, 42, 0 },{ 255, 42, 0 },{ 255, 43, 0 },{ 255, 43, 0 },{ 255, 43, 0 }, { 255, 43, 0 },{ 255, 44, 0 },{ 255, 44, 0 },{ 255, 44, 0 },{ 255, 44, 0 }, { 255, 45, 0 },{ 255, 45, 0 },{ 255, 45, 0 },{ 255, 45, 0 },{ 255, 46, 0 }, { 255, 46, 0 },{ 255, 46, 0 },{ 255, 46, 0 },{ 255, 47, 0 },{ 255, 47, 0 }, { 255, 47, 0 },{ 255, 47, 0 },{ 255, 48, 0 },{ 255, 48, 0 },{ 255, 48, 0 }, { 255, 48, 0 },{ 255, 49, 0 },{ 255, 49, 0 },{ 255, 49, 0 },{ 255, 50, 0 }, { 255, 50, 0 },{ 255, 50, 0 },{ 255, 50, 0 },{ 255, 51, 0 },{ 255, 51, 0 }, { 255, 51, 0 },{ 255, 51, 0 },{ 255, 52, 0 },{ 255, 52, 0 },{ 255, 52, 0 }, { 255, 52, 0 },{ 255, 53, 0 },{ 255, 53, 0 },{ 255, 53, 0 },{ 255, 53, 0 }, { 255, 54, 0 },{ 255, 54, 0 },{ 255, 54, 0 },{ 255, 54, 0 },{ 255, 55, 0 }, { 255, 55, 0 },{ 255, 55, 0 },{ 255, 55, 0 },{ 255, 56, 0 },{ 255, 56, 0 }, { 255, 56, 0 },{ 255, 56, 0 },{ 255, 57, 0 },{ 255, 57, 0 },{ 255, 57, 0 }, { 255, 57, 0 },{ 255, 58, 0 },{ 255, 58, 0 },{ 255, 58, 0 },{ 255, 58, 0 }, { 255, 59, 0 },{ 255, 59, 0 },{ 255, 59, 0 },{ 255, 59, 0 },{ 255, 60, 0 }, { 255, 60, 0 },{ 255, 60, 0 },{ 255, 60, 0 },{ 255, 61, 0 },{ 255, 61, 0 }, { 255, 61, 0 },{ 255, 62, 0 },{ 255, 62, 0 },{ 255, 62, 0 },{ 255, 62, 0 }, { 255, 63, 0 },{ 255, 63, 0 },{ 255, 63, 0 },{ 255, 63, 0 },{ 255, 64, 0 }, { 255, 64, 0 },{ 255, 64, 0 },{ 255, 64, 0 },{ 255, 65, 0 },{ 255, 65, 0 }, { 255, 65, 0 },{ 255, 65, 0 },{ 255, 66, 0 },{ 255, 66, 0 },{ 255, 66, 0 }, { 255, 66, 0 },{ 255, 67, 0 },{ 255, 67, 0 },{ 255, 67, 0 },{ 255, 67, 0 }, { 255, 68, 0 },{ 255, 68, 0 },{ 255, 68, 0 },{ 255, 68, 0 },{ 255, 69, 0 }, { 255, 69, 0 },{ 255, 69, 0 },{ 255, 69, 0 },{ 255, 70, 0 },{ 255, 70, 0 }, { 255, 70, 0 },{ 255, 70, 0 },{ 255, 71, 0 },{ 255, 71, 0 },{ 255, 71, 0 }, { 255, 71, 0 },{ 255, 72, 0 },{ 255, 72, 0 },{ 255, 72, 0 },{ 255, 72, 0 }, { 255, 73, 0 },{ 255, 73, 0 },{ 255, 73, 0 },{ 255, 74, 0 },{ 255, 74, 0 }, { 255, 74, 0 },{ 255, 74, 0 },{ 255, 75, 0 },{ 255, 75, 0 },{ 255, 75, 0 }, { 255, 75, 0 },{ 255, 76, 0 },{ 255, 76, 0 },{ 255, 76, 0 },{ 255, 76, 0 }, { 255, 77, 0 },{ 255, 77, 0 },{ 255, 77, 0 },{ 255, 77, 0 },{ 255, 78, 0 }, { 255, 78, 0 },{ 255, 78, 0 },{ 255, 78, 0 },{ 255, 79, 0 },{ 255, 79, 0 }, { 255, 79, 0 },{ 255, 79, 0 },{ 255, 80, 0 },{ 255, 80, 0 },{ 255, 80, 0 }, { 255, 80, 0 },{ 255, 81, 0 },{ 255, 81, 0 },{ 255, 81, 0 },{ 255, 81, 0 }, { 255, 82, 0 },{ 255, 82, 0 },{ 255, 82, 0 },{ 255, 82, 0 },{ 255, 83, 0 }, { 255, 83, 0 },{ 255, 83, 0 },{ 255, 83, 0 },{ 255, 84, 0 },{ 255, 84, 0 }, { 255, 84, 0 },{ 255, 84, 0 },{ 255, 85, 0 },{ 255, 85, 0 },{ 255, 85, 0 }, { 255, 86, 0 },{ 255, 86, 0 },{ 255, 86, 0 },{ 255, 86, 0 },{ 255, 87, 0 }, { 255, 87, 0 },{ 255, 87, 0 },{ 255, 87, 0 },{ 255, 88, 0 },{ 255, 88, 0 }, { 255, 88, 0 },{ 255, 88, 0 },{ 255, 89, 0 },{ 255, 89, 0 },{ 255, 89, 0 }, { 255, 89, 0 },{ 255, 90, 0 },{ 255, 90, 0 },{ 255, 90, 0 },{ 255, 90, 0 }, { 255, 91, 0 },{ 255, 91, 0 },{ 255, 91, 0 },{ 255, 91, 0 },{ 255, 92, 0 }, { 255, 92, 0 },{ 255, 92, 0 },{ 255, 92, 0 },{ 255, 93, 0 },{ 255, 93, 0 }, { 255, 93, 0 },{ 255, 93, 0 },{ 255, 94, 0 },{ 255, 94, 0 },{ 255, 94, 0 }, { 255, 94, 0 },{ 255, 95, 0 },{ 255, 95, 0 },{ 255, 95, 0 },{ 255, 95, 0 }, { 255, 96, 0 },{ 255, 96, 0 },{ 255, 96, 0 },{ 255, 96, 0 },{ 255, 97, 0 }, { 255, 97, 0 },{ 255, 97, 0 },{ 255, 98, 0 },{ 255, 98, 0 },{ 255, 98, 0 }, { 255, 98, 0 },{ 255, 99, 0 },{ 255, 99, 0 },{ 255, 99, 0 },{ 255, 99, 0 }, { 255, 100, 0 },{ 255, 100, 0 },{ 255, 100, 0 },{ 255, 100, 0 },{ 255, 101, 0 }, { 255, 101, 0 },{ 255, 101, 0 },{ 255, 101, 0 },{ 255, 102, 0 },{ 255, 102, 0 }, { 255, 102, 0 },{ 255, 102, 0 },{ 255, 103, 0 },{ 255, 103, 0 },{ 255, 103, 0 }, { 255, 103, 0 },{ 255, 104, 0 },{ 255, 104, 0 },{ 255, 104, 0 },{ 255, 104, 0 }, { 255, 105, 0 },{ 255, 105, 0 },{ 255, 105, 0 },{ 255, 105, 0 },{ 255, 106, 0 }, { 255, 106, 0 },{ 255, 106, 0 },{ 255, 106, 0 },{ 255, 107, 0 },{ 255, 107, 0 }, { 255, 107, 0 },{ 255, 107, 0 },{ 255, 108, 0 },{ 255, 108, 0 },{ 255, 108, 0 }, { 255, 108, 0 },{ 255, 109, 0 },{ 255, 109, 0 },{ 255, 109, 0 },{ 255, 110, 0 }, { 255, 110, 0 },{ 255, 110, 0 },{ 255, 110, 0 },{ 255, 111, 0 },{ 255, 111, 0 }, { 255, 111, 0 },{ 255, 111, 0 },{ 255, 112, 0 },{ 255, 112, 0 },{ 255, 112, 0 }, { 255, 112, 0 },{ 255, 113, 0 },{ 255, 113, 0 },{ 255, 113, 0 },{ 255, 113, 0 }, { 255, 114, 0 },{ 255, 114, 0 },{ 255, 114, 0 },{ 255, 114, 0 },{ 255, 115, 0 }, { 255, 115, 0 },{ 255, 115, 0 },{ 255, 115, 0 },{ 255, 116, 0 },{ 255, 116, 0 }, { 255, 116, 0 },{ 255, 116, 0 },{ 255, 117, 0 },{ 255, 117, 0 },{ 255, 117, 0 }, { 255, 117, 0 },{ 255, 118, 0 },{ 255, 118, 0 },{ 255, 118, 0 },{ 255, 118, 0 }, { 255, 119, 0 },{ 255, 119, 0 },{ 255, 119, 0 },{ 255, 119, 0 },{ 255, 120, 0 }, { 255, 120, 0 },{ 255, 120, 0 },{ 255, 120, 0 },{ 255, 121, 0 },{ 255, 121, 0 }, { 255, 121, 0 },{ 255, 122, 0 },{ 255, 122, 0 },{ 255, 122, 0 },{ 255, 122, 0 }, { 255, 123, 0 },{ 255, 123, 0 },{ 255, 123, 0 },{ 255, 123, 0 },{ 255, 124, 0 }, { 255, 124, 0 },{ 255, 124, 0 },{ 255, 124, 0 },{ 255, 125, 0 },{ 255, 125, 0 }, { 255, 125, 0 },{ 255, 125, 0 },{ 255, 126, 0 },{ 255, 126, 0 },{ 255, 126, 0 }, { 255, 126, 0 },{ 255, 127, 0 },{ 255, 127, 0 },{ 255, 127, 0 },{ 255, 127, 0 }, { 255, 128, 0 },{ 255, 128, 0 },{ 255, 128, 0 },{ 255, 128, 0 },{ 255, 129, 0 }, { 255, 129, 0 },{ 255, 129, 0 },{ 255, 129, 0 },{ 255, 130, 0 },{ 255, 130, 0 }, { 255, 130, 0 },{ 255, 130, 0 },{ 255, 131, 0 },{ 255, 131, 0 },{ 255, 131, 0 }, { 255, 131, 0 },{ 255, 132, 0 },{ 255, 132, 0 },{ 255, 132, 0 },{ 255, 132, 0 }, { 255, 133, 0 },{ 255, 133, 0 },{ 255, 133, 0 },{ 255, 133, 0 },{ 255, 134, 0 }, { 255, 134, 0 },{ 255, 134, 0 },{ 255, 135, 0 },{ 255, 135, 0 },{ 255, 135, 0 }, { 255, 135, 0 },{ 255, 136, 0 },{ 255, 136, 0 },{ 255, 136, 0 },{ 255, 136, 0 }, { 255, 137, 0 },{ 255, 137, 0 },{ 255, 137, 0 },{ 255, 137, 0 },{ 255, 138, 0 }, { 255, 138, 0 },{ 255, 138, 0 },{ 255, 138, 0 },{ 255, 139, 0 },{ 255, 139, 0 }, { 255, 139, 0 },{ 255, 139, 0 },{ 255, 140, 0 },{ 255, 140, 0 },{ 255, 140, 0 }, { 255, 140, 0 },{ 255, 141, 0 },{ 255, 141, 0 },{ 255, 141, 0 },{ 255, 141, 0 }, { 255, 142, 0 },{ 255, 142, 0 },{ 255, 142, 0 },{ 255, 142, 0 },{ 255, 143, 0 }, { 255, 143, 0 },{ 255, 143, 0 },{ 255, 143, 0 },{ 255, 144, 0 },{ 255, 144, 0 }, { 255, 144, 0 },{ 255, 144, 0 },{ 255, 145, 0 },{ 255, 145, 0 },{ 255, 145, 0 }, { 255, 145, 0 },{ 255, 146, 0 },{ 255, 146, 0 },{ 255, 146, 0 },{ 255, 147, 0 }, { 255, 147, 0 },{ 255, 147, 0 },{ 255, 147, 0 },{ 255, 148, 0 },{ 255, 148, 0 }, { 255, 148, 0 },{ 255, 148, 0 },{ 255, 149, 0 },{ 255, 149, 0 },{ 255, 149, 0 }, { 255, 149, 0 },{ 255, 150, 0 },{ 255, 150, 0 },{ 255, 150, 0 },{ 255, 150, 0 }, { 255, 151, 0 },{ 255, 151, 0 },{ 255, 151, 0 },{ 255, 151, 0 },{ 255, 152, 0 }, { 255, 152, 0 },{ 255, 152, 0 },{ 255, 152, 0 },{ 255, 153, 0 },{ 255, 153, 0 }, { 255, 153, 0 },{ 255, 153, 0 },{ 255, 154, 0 },{ 255, 154, 0 },{ 255, 154, 0 }, { 255, 154, 0 },{ 255, 155, 0 },{ 255, 155, 0 },{ 255, 155, 0 },{ 255, 155, 0 }, { 255, 156, 0 },{ 255, 156, 0 },{ 255, 156, 0 },{ 255, 156, 0 },{ 255, 157, 0 }, { 255, 157, 0 },{ 255, 157, 0 },{ 255, 157, 0 },{ 255, 158, 0 },{ 255, 158, 0 }, { 255, 158, 0 },{ 255, 159, 0 },{ 255, 159, 0 },{ 255, 159, 0 },{ 255, 159, 0 }, { 255, 160, 0 },{ 255, 160, 0 },{ 255, 160, 0 },{ 255, 160, 0 },{ 255, 161, 0 }, { 255, 161, 0 },{ 255, 161, 0 },{ 255, 161, 0 },{ 255, 162, 0 },{ 255, 162, 0 }, { 255, 162, 0 },{ 255, 162, 0 },{ 255, 163, 0 },{ 255, 163, 0 },{ 255, 163, 0 }, { 255, 163, 0 },{ 255, 164, 0 },{ 255, 164, 0 },{ 255, 164, 0 },{ 255, 164, 0 }, { 255, 165, 0 },{ 255, 165, 0 },{ 255, 165, 0 },{ 255, 165, 0 },{ 255, 166, 0 }, { 255, 166, 0 },{ 255, 166, 0 },{ 255, 166, 0 },{ 255, 167, 0 },{ 255, 167, 0 }, { 255, 167, 0 },{ 255, 167, 0 },{ 255, 168, 0 },{ 255, 168, 0 },{ 255, 168, 0 }, { 255, 168, 0 },{ 255, 169, 0 },{ 255, 169, 0 },{ 255, 169, 0 },{ 255, 169, 0 }, { 255, 170, 0 },{ 255, 170, 0 },{ 255, 170, 0 },{ 255, 171, 0 },{ 255, 171, 0 }, { 255, 171, 0 },{ 255, 171, 0 },{ 255, 172, 0 },{ 255, 172, 0 },{ 255, 172, 0 }, { 255, 172, 0 },{ 255, 173, 0 },{ 255, 173, 0 },{ 255, 173, 0 },{ 255, 173, 0 }, { 255, 174, 0 },{ 255, 174, 0 },{ 255, 174, 0 },{ 255, 174, 0 },{ 255, 175, 0 }, { 255, 175, 0 },{ 255, 175, 0 },{ 255, 175, 0 },{ 255, 176, 0 },{ 255, 176, 0 }, { 255, 176, 0 },{ 255, 176, 0 },{ 255, 177, 0 },{ 255, 177, 0 },{ 255, 177, 0 }, { 255, 177, 0 },{ 255, 178, 0 },{ 255, 178, 0 },{ 255, 178, 0 },{ 255, 178, 0 }, { 255, 179, 0 },{ 255, 179, 0 },{ 255, 179, 0 },{ 255, 179, 0 },{ 255, 180, 0 }, { 255, 180, 0 },{ 255, 180, 0 },{ 255, 180, 0 },{ 255, 181, 0 },{ 255, 181, 0 }, { 255, 181, 0 },{ 255, 181, 0 },{ 255, 182, 0 },{ 255, 182, 0 },{ 255, 182, 0 }, { 255, 183, 0 },{ 255, 183, 0 },{ 255, 183, 0 },{ 255, 183, 0 },{ 255, 184, 0 }, { 255, 184, 0 },{ 255, 184, 0 },{ 255, 184, 0 },{ 255, 185, 0 },{ 255, 185, 0 }, { 255, 185, 0 },{ 255, 185, 0 },{ 255, 186, 0 },{ 255, 186, 0 },{ 255, 186, 0 }, { 255, 186, 0 },{ 255, 187, 0 },{ 255, 187, 0 },{ 255, 187, 0 },{ 255, 187, 0 }, { 255, 188, 0 },{ 255, 188, 0 },{ 255, 188, 0 },{ 255, 188, 0 },{ 255, 189, 0 }, { 255, 189, 0 },{ 255, 189, 0 },{ 255, 189, 0 },{ 255, 190, 0 },{ 255, 190, 0 }, { 255, 190, 0 },{ 255, 190, 0 },{ 255, 191, 0 },{ 255, 191, 0 },{ 255, 191, 0 }, { 255, 191, 0 },{ 255, 192, 0 },{ 255, 192, 0 },{ 255, 192, 0 },{ 255, 192, 0 }, { 255, 193, 0 },{ 255, 193, 0 },{ 255, 193, 0 },{ 255, 193, 0 },{ 255, 194, 0 }, { 255, 194, 0 },{ 255, 194, 0 },{ 255, 195, 0 },{ 255, 195, 0 },{ 255, 195, 0 }, { 255, 195, 0 },{ 255, 196, 0 },{ 255, 196, 0 },{ 255, 196, 0 },{ 255, 196, 0 }, { 255, 197, 0 },{ 255, 197, 0 },{ 255, 197, 0 },{ 255, 197, 0 },{ 255, 198, 0 }, { 255, 198, 0 },{ 255, 198, 0 },{ 255, 198, 0 },{ 255, 199, 0 },{ 255, 199, 0 }, { 255, 199, 0 },{ 255, 199, 0 },{ 255, 200, 0 },{ 255, 200, 0 },{ 255, 200, 0 }, { 255, 200, 0 },{ 255, 201, 0 },{ 255, 201, 0 },{ 255, 201, 0 },{ 255, 201, 0 }, { 255, 202, 0 },{ 255, 202, 0 },{ 255, 202, 0 },{ 255, 202, 0 },{ 255, 203, 0 }, { 255, 203, 0 },{ 255, 203, 0 },{ 255, 203, 0 },{ 255, 204, 0 },{ 255, 204, 0 }, { 255, 204, 0 },{ 255, 204, 0 },{ 255, 205, 0 },{ 255, 205, 0 },{ 255, 205, 0 }, { 255, 205, 0 },{ 255, 206, 0 },{ 255, 206, 0 },{ 255, 206, 0 },{ 255, 207, 0 }, { 255, 207, 0 },{ 255, 207, 0 },{ 255, 207, 0 },{ 255, 208, 0 },{ 255, 208, 0 }, { 255, 208, 0 },{ 255, 208, 0 },{ 255, 209, 0 },{ 255, 209, 0 },{ 255, 209, 0 }, { 255, 209, 0 },{ 255, 210, 0 },{ 255, 210, 0 },{ 255, 210, 0 },{ 255, 210, 0 }, { 255, 211, 0 },{ 255, 211, 0 },{ 255, 211, 0 },{ 255, 211, 0 },{ 255, 212, 0 }, { 255, 212, 0 },{ 255, 212, 0 },{ 255, 212, 0 },{ 255, 213, 0 },{ 255, 213, 0 }, { 255, 213, 0 },{ 255, 213, 0 },{ 255, 214, 0 },{ 255, 214, 0 },{ 255, 214, 0 }, { 255, 214, 0 },{ 255, 215, 0 },{ 255, 215, 0 },{ 255, 215, 0 },{ 255, 215, 0 }, { 255, 216, 0 },{ 255, 216, 0 },{ 255, 216, 0 },{ 255, 216, 0 },{ 255, 217, 0 }, { 255, 217, 0 },{ 255, 217, 0 },{ 255, 217, 0 },{ 255, 218, 0 },{ 255, 218, 0 }, { 255, 218, 0 },{ 255, 218, 0 },{ 255, 219, 0 },{ 255, 219, 0 },{ 255, 219, 0 }, { 255, 220, 0 },{ 255, 220, 0 },{ 255, 220, 0 },{ 255, 220, 0 },{ 255, 221, 0 }, { 255, 221, 0 },{ 255, 221, 0 },{ 255, 221, 0 },{ 255, 222, 0 },{ 255, 222, 0 }, { 255, 222, 0 },{ 255, 222, 0 },{ 255, 223, 0 },{ 255, 223, 0 },{ 255, 223, 0 }, { 255, 223, 0 },{ 255, 224, 0 },{ 255, 224, 0 },{ 255, 224, 0 },{ 255, 224, 0 }, { 255, 225, 0 },{ 255, 225, 0 },{ 255, 225, 0 },{ 255, 225, 0 },{ 255, 226, 0 }, { 255, 226, 0 },{ 255, 226, 0 },{ 255, 226, 0 },{ 255, 227, 0 },{ 255, 227, 0 }, { 255, 227, 0 },{ 255, 227, 0 },{ 255, 228, 0 },{ 255, 228, 0 },{ 255, 228, 0 }, { 255, 228, 0 },{ 255, 229, 0 },{ 255, 229, 0 },{ 255, 229, 0 },{ 255, 229, 0 }, { 255, 230, 0 },{ 255, 230, 0 },{ 255, 230, 0 },{ 255, 230, 0 },{ 255, 231, 0 }, { 255, 231, 0 },{ 255, 231, 0 },{ 255, 232, 0 },{ 255, 232, 0 },{ 255, 232, 0 }, { 255, 232, 0 },{ 255, 233, 0 },{ 255, 233, 0 },{ 255, 233, 0 },{ 255, 233, 0 }, { 255, 234, 0 },{ 255, 234, 0 },{ 255, 234, 0 },{ 255, 234, 0 },{ 255, 235, 0 }, { 255, 235, 0 },{ 255, 235, 0 },{ 255, 235, 0 },{ 255, 236, 0 },{ 255, 236, 0 }, { 255, 236, 0 },{ 255, 236, 0 },{ 255, 237, 0 },{ 255, 237, 0 },{ 255, 237, 0 }, { 255, 237, 0 },{ 255, 238, 0 },{ 255, 238, 0 },{ 255, 238, 0 },{ 255, 238, 0 }, { 255, 239, 0 },{ 255, 239, 0 },{ 255, 239, 0 },{ 255, 239, 0 },{ 255, 240, 0 }, { 255, 240, 0 },{ 255, 240, 0 },{ 255, 240, 0 },{ 255, 241, 0 },{ 255, 241, 0 }, { 255, 241, 0 },{ 255, 241, 0 },{ 255, 242, 0 },{ 255, 242, 0 },{ 255, 242, 0 }, { 255, 242, 0 },{ 255, 243, 0 },{ 255, 243, 0 },{ 255, 243, 0 },{ 255, 244, 0 }, { 255, 244, 0 },{ 255, 244, 0 },{ 255, 244, 0 },{ 255, 245, 0 },{ 255, 245, 0 }, { 255, 245, 0 },{ 255, 245, 0 },{ 255, 246, 0 },{ 255, 246, 0 },{ 255, 246, 0 }, { 255, 246, 0 },{ 255, 247, 0 },{ 255, 247, 0 },{ 255, 247, 0 },{ 255, 247, 0 }, { 255, 248, 0 },{ 255, 248, 0 },{ 255, 248, 0 },{ 255, 248, 0 },{ 255, 249, 0 }, { 255, 249, 0 },{ 255, 249, 0 },{ 255, 249, 0 },{ 255, 250, 0 },{ 255, 250, 0 }, { 255, 250, 0 },{ 255, 250, 0 },{ 255, 251, 0 },{ 255, 251, 0 },{ 255, 251, 0 }, { 255, 251, 0 },{ 255, 252, 0 },{ 255, 252, 0 },{ 255, 252, 0 },{ 255, 252, 0 }, { 255, 253, 0 },{ 255, 253, 0 },{ 255, 253, 0 },{ 255, 253, 0 },{ 255, 254, 0 }, { 255, 254, 0 },{ 255, 254, 0 },{ 255, 254, 0 },{ 255, 255, 0 },{ 255, 255, 0 } }; const rgb_t copper_colormap[1000] = { { 0, 0, 0 },{ 0, 0, 0 },{ 1, 0, 0 },{ 1, 1, 0 },{ 1, 1, 1 }, { 2, 1, 1 },{ 2, 1, 1 },{ 2, 1, 1 },{ 3, 2, 1 },{ 3, 2, 1 }, { 3, 2, 1 },{ 4, 2, 1 },{ 4, 2, 2 },{ 4, 3, 2 },{ 4, 3, 2 }, { 5, 3, 2 },{ 5, 3, 2 },{ 5, 3, 2 },{ 6, 4, 2 },{ 6, 4, 2 }, { 6, 4, 3 },{ 7, 4, 3 },{ 7, 4, 3 },{ 7, 5, 3 },{ 8, 5, 3 }, { 8, 5, 3 },{ 8, 5, 3 },{ 9, 5, 3 },{ 9, 6, 4 },{ 9, 6, 4 }, { 10, 6, 4 },{ 10, 6, 4 },{ 10, 6, 4 },{ 11, 7, 4 },{ 11, 7, 4 }, { 11, 7, 4 },{ 11, 7, 5 },{ 12, 7, 5 },{ 12, 8, 5 },{ 12, 8, 5 }, { 13, 8, 5 },{ 13, 8, 5 },{ 13, 8, 5 },{ 14, 9, 5 },{ 14, 9, 6 }, { 14, 9, 6 },{ 15, 9, 6 },{ 15, 9, 6 },{ 15, 10, 6 },{ 16, 10, 6 }, { 16, 10, 6 },{ 16, 10, 6 },{ 17, 10, 7 },{ 17, 11, 7 },{ 17, 11, 7 }, { 18, 11, 7 },{ 18, 11, 7 },{ 18, 11, 7 },{ 19, 12, 7 },{ 19, 12, 7 }, { 19, 12, 8 },{ 19, 12, 8 },{ 20, 12, 8 },{ 20, 13, 8 },{ 20, 13, 8 }, { 21, 13, 8 },{ 21, 13, 8 },{ 21, 13, 9 },{ 22, 14, 9 },{ 22, 14, 9 }, { 22, 14, 9 },{ 23, 14, 9 },{ 23, 14, 9 },{ 23, 15, 9 },{ 24, 15, 9 }, { 24, 15, 10 },{ 24, 15, 10 },{ 25, 15, 10 },{ 25, 16, 10 },{ 25, 16, 10 }, { 26, 16, 10 },{ 26, 16, 10 },{ 26, 16, 10 },{ 26, 17, 11 },{ 27, 17, 11 }, { 27, 17, 11 },{ 27, 17, 11 },{ 28, 17, 11 },{ 28, 18, 11 },{ 28, 18, 11 }, { 29, 18, 11 },{ 29, 18, 12 },{ 29, 18, 12 },{ 30, 19, 12 },{ 30, 19, 12 }, { 30, 19, 12 },{ 31, 19, 12 },{ 31, 19, 12 },{ 31, 20, 12 },{ 32, 20, 13 }, { 32, 20, 13 },{ 32, 20, 13 },{ 33, 20, 13 },{ 33, 21, 13 },{ 33, 21, 13 }, { 34, 21, 13 },{ 34, 21, 13 },{ 34, 21, 14 },{ 34, 22, 14 },{ 35, 22, 14 }, { 35, 22, 14 },{ 35, 22, 14 },{ 36, 22, 14 },{ 36, 23, 14 },{ 36, 23, 14 }, { 37, 23, 15 },{ 37, 23, 15 },{ 37, 23, 15 },{ 38, 24, 15 },{ 38, 24, 15 }, { 38, 24, 15 },{ 39, 24, 15 },{ 39, 24, 15 },{ 39, 25, 16 },{ 40, 25, 16 }, { 40, 25, 16 },{ 40, 25, 16 },{ 41, 25, 16 },{ 41, 26, 16 },{ 41, 26, 16 }, { 41, 26, 17 },{ 42, 26, 17 },{ 42, 26, 17 },{ 42, 27, 17 },{ 43, 27, 17 }, { 43, 27, 17 },{ 43, 27, 17 },{ 44, 27, 17 },{ 44, 28, 18 },{ 44, 28, 18 }, { 45, 28, 18 },{ 45, 28, 18 },{ 45, 28, 18 },{ 46, 29, 18 },{ 46, 29, 18 }, { 46, 29, 18 },{ 47, 29, 19 },{ 47, 29, 19 },{ 47, 30, 19 },{ 48, 30, 19 }, { 48, 30, 19 },{ 48, 30, 19 },{ 48, 30, 19 },{ 49, 31, 19 },{ 49, 31, 20 }, { 49, 31, 20 },{ 50, 31, 20 },{ 50, 31, 20 },{ 50, 32, 20 },{ 51, 32, 20 }, { 51, 32, 20 },{ 51, 32, 20 },{ 52, 32, 21 },{ 52, 33, 21 },{ 52, 33, 21 }, { 53, 33, 21 },{ 53, 33, 21 },{ 53, 33, 21 },{ 54, 34, 21 },{ 54, 34, 21 }, { 54, 34, 22 },{ 55, 34, 22 },{ 55, 34, 22 },{ 55, 34, 22 },{ 56, 35, 22 }, { 56, 35, 22 },{ 56, 35, 22 },{ 56, 35, 22 },{ 57, 35, 23 },{ 57, 36, 23 }, { 57, 36, 23 },{ 58, 36, 23 },{ 58, 36, 23 },{ 58, 36, 23 },{ 59, 37, 23 }, { 59, 37, 23 },{ 59, 37, 24 },{ 60, 37, 24 },{ 60, 37, 24 },{ 60, 38, 24 }, { 61, 38, 24 },{ 61, 38, 24 },{ 61, 38, 24 },{ 62, 38, 25 },{ 62, 39, 25 }, { 62, 39, 25 },{ 63, 39, 25 },{ 63, 39, 25 },{ 63, 39, 25 },{ 63, 40, 25 }, { 64, 40, 25 },{ 64, 40, 26 },{ 64, 40, 26 },{ 65, 40, 26 },{ 65, 41, 26 }, { 65, 41, 26 },{ 66, 41, 26 },{ 66, 41, 26 },{ 66, 41, 26 },{ 67, 42, 27 }, { 67, 42, 27 },{ 67, 42, 27 },{ 68, 42, 27 },{ 68, 42, 27 },{ 68, 43, 27 }, { 69, 43, 27 },{ 69, 43, 27 },{ 69, 43, 28 },{ 70, 43, 28 },{ 70, 44, 28 }, { 70, 44, 28 },{ 71, 44, 28 },{ 71, 44, 28 },{ 71, 44, 28 },{ 71, 45, 28 }, { 72, 45, 29 },{ 72, 45, 29 },{ 72, 45, 29 },{ 73, 45, 29 },{ 73, 46, 29 }, { 73, 46, 29 },{ 74, 46, 29 },{ 74, 46, 29 },{ 74, 46, 30 },{ 75, 47, 30 }, { 75, 47, 30 },{ 75, 47, 30 },{ 76, 47, 30 },{ 76, 47, 30 },{ 76, 48, 30 }, { 77, 48, 30 },{ 77, 48, 31 },{ 77, 48, 31 },{ 78, 48, 31 },{ 78, 49, 31 }, { 78, 49, 31 },{ 78, 49, 31 },{ 79, 49, 31 },{ 79, 49, 31 },{ 79, 50, 32 }, { 80, 50, 32 },{ 80, 50, 32 },{ 80, 50, 32 },{ 81, 50, 32 },{ 81, 51, 32 }, { 81, 51, 32 },{ 82, 51, 33 },{ 82, 51, 33 },{ 82, 51, 33 },{ 83, 52, 33 }, { 83, 52, 33 },{ 83, 52, 33 },{ 84, 52, 33 },{ 84, 52, 33 },{ 84, 53, 34 }, { 85, 53, 34 },{ 85, 53, 34 },{ 85, 53, 34 },{ 86, 53, 34 },{ 86, 54, 34 }, { 86, 54, 34 },{ 86, 54, 34 },{ 87, 54, 35 },{ 87, 54, 35 },{ 87, 55, 35 }, { 88, 55, 35 },{ 88, 55, 35 },{ 88, 55, 35 },{ 89, 55, 35 },{ 89, 56, 35 }, { 89, 56, 36 },{ 90, 56, 36 },{ 90, 56, 36 },{ 90, 56, 36 },{ 91, 57, 36 }, { 91, 57, 36 },{ 91, 57, 36 },{ 92, 57, 36 },{ 92, 57, 37 },{ 92, 58, 37 }, { 93, 58, 37 },{ 93, 58, 37 },{ 93, 58, 37 },{ 93, 58, 37 },{ 94, 59, 37 }, { 94, 59, 37 },{ 94, 59, 38 },{ 95, 59, 38 },{ 95, 59, 38 },{ 95, 60, 38 }, { 96, 60, 38 },{ 96, 60, 38 },{ 96, 60, 38 },{ 97, 60, 38 },{ 97, 61, 39 }, { 97, 61, 39 },{ 98, 61, 39 },{ 98, 61, 39 },{ 98, 61, 39 },{ 99, 62, 39 }, { 99, 62, 39 },{ 99, 62, 39 },{ 100, 62, 40 },{ 100, 62, 40 },{ 100, 63, 40 }, { 101, 63, 40 },{ 101, 63, 40 },{ 101, 63, 40 },{ 101, 63, 40 },{ 102, 64, 41 }, { 102, 64, 41 },{ 102, 64, 41 },{ 103, 64, 41 },{ 103, 64, 41 },{ 103, 65, 41 }, { 104, 65, 41 },{ 104, 65, 41 },{ 104, 65, 42 },{ 105, 65, 42 },{ 105, 66, 42 }, { 105, 66, 42 },{ 106, 66, 42 },{ 106, 66, 42 },{ 106, 66, 42 },{ 107, 67, 42 }, { 107, 67, 43 },{ 107, 67, 43 },{ 108, 67, 43 },{ 108, 67, 43 },{ 108, 68, 43 }, { 108, 68, 43 },{ 109, 68, 43 },{ 109, 68, 43 },{ 109, 68, 44 },{ 110, 69, 44 }, { 110, 69, 44 },{ 110, 69, 44 },{ 111, 69, 44 },{ 111, 69, 44 },{ 111, 70, 44 }, { 112, 70, 44 },{ 112, 70, 45 },{ 112, 70, 45 },{ 113, 70, 45 },{ 113, 71, 45 }, { 113, 71, 45 },{ 114, 71, 45 },{ 114, 71, 45 },{ 114, 71, 45 },{ 115, 72, 46 }, { 115, 72, 46 },{ 115, 72, 46 },{ 116, 72, 46 },{ 116, 72, 46 },{ 116, 73, 46 }, { 116, 73, 46 },{ 117, 73, 46 },{ 117, 73, 47 },{ 117, 73, 47 },{ 118, 74, 47 }, { 118, 74, 47 },{ 118, 74, 47 },{ 119, 74, 47 },{ 119, 74, 47 },{ 119, 75, 47 }, { 120, 75, 48 },{ 120, 75, 48 },{ 120, 75, 48 },{ 121, 75, 48 },{ 121, 76, 48 }, { 121, 76, 48 },{ 122, 76, 48 },{ 122, 76, 49 },{ 122, 76, 49 },{ 123, 77, 49 }, { 123, 77, 49 },{ 123, 77, 49 },{ 123, 77, 49 },{ 124, 77, 49 },{ 124, 78, 49 }, { 124, 78, 50 },{ 125, 78, 50 },{ 125, 78, 50 },{ 125, 78, 50 },{ 126, 79, 50 }, { 126, 79, 50 },{ 126, 79, 50 },{ 127, 79, 50 },{ 127, 79, 51 },{ 127, 80, 51 }, { 128, 80, 51 },{ 128, 80, 51 },{ 128, 80, 51 },{ 129, 80, 51 },{ 129, 81, 51 }, { 129, 81, 51 },{ 130, 81, 52 },{ 130, 81, 52 },{ 130, 81, 52 },{ 130, 82, 52 }, { 131, 82, 52 },{ 131, 82, 52 },{ 131, 82, 52 },{ 132, 82, 52 },{ 132, 83, 53 }, { 132, 83, 53 },{ 133, 83, 53 },{ 133, 83, 53 },{ 133, 83, 53 },{ 134, 84, 53 }, { 134, 84, 53 },{ 134, 84, 53 },{ 135, 84, 54 },{ 135, 84, 54 },{ 135, 85, 54 }, { 136, 85, 54 },{ 136, 85, 54 },{ 136, 85, 54 },{ 137, 85, 54 },{ 137, 86, 54 }, { 137, 86, 55 },{ 138, 86, 55 },{ 138, 86, 55 },{ 138, 86, 55 },{ 138, 87, 55 }, { 139, 87, 55 },{ 139, 87, 55 },{ 139, 87, 55 },{ 140, 87, 56 },{ 140, 88, 56 }, { 140, 88, 56 },{ 141, 88, 56 },{ 141, 88, 56 },{ 141, 88, 56 },{ 142, 89, 56 }, { 142, 89, 57 },{ 142, 89, 57 },{ 143, 89, 57 },{ 143, 89, 57 },{ 143, 90, 57 }, { 144, 90, 57 },{ 144, 90, 57 },{ 144, 90, 57 },{ 145, 90, 58 },{ 145, 91, 58 }, { 145, 91, 58 },{ 145, 91, 58 },{ 146, 91, 58 },{ 146, 91, 58 },{ 146, 92, 58 }, { 147, 92, 58 },{ 147, 92, 59 },{ 147, 92, 59 },{ 148, 92, 59 },{ 148, 93, 59 }, { 148, 93, 59 },{ 149, 93, 59 },{ 149, 93, 59 },{ 149, 93, 59 },{ 150, 94, 60 }, { 150, 94, 60 },{ 150, 94, 60 },{ 151, 94, 60 },{ 151, 94, 60 },{ 151, 95, 60 }, { 152, 95, 60 },{ 152, 95, 60 },{ 152, 95, 61 },{ 153, 95, 61 },{ 153, 96, 61 }, { 153, 96, 61 },{ 153, 96, 61 },{ 154, 96, 61 },{ 154, 96, 61 },{ 154, 97, 61 }, { 155, 97, 62 },{ 155, 97, 62 },{ 155, 97, 62 },{ 156, 97, 62 },{ 156, 98, 62 }, { 156, 98, 62 },{ 157, 98, 62 },{ 157, 98, 62 },{ 157, 98, 63 },{ 158, 99, 63 }, { 158, 99, 63 },{ 158, 99, 63 },{ 159, 99, 63 },{ 159, 99, 63 },{ 159, 100, 63 }, { 160, 100, 63 },{ 160, 100, 64 },{ 160, 100, 64 },{ 160, 100, 64 },{ 161, 101, 64 }, { 161, 101, 64 },{ 161, 101, 64 },{ 162, 101, 64 },{ 162, 101, 65 },{ 162, 101, 65 }, { 163, 102, 65 },{ 163, 102, 65 },{ 163, 102, 65 },{ 164, 102, 65 },{ 164, 102, 65 }, { 164, 103, 65 },{ 165, 103, 66 },{ 165, 103, 66 },{ 165, 103, 66 },{ 166, 103, 66 }, { 166, 104, 66 },{ 166, 104, 66 },{ 167, 104, 66 },{ 167, 104, 66 },{ 167, 104, 67 }, { 168, 105, 67 },{ 168, 105, 67 },{ 168, 105, 67 },{ 168, 105, 67 },{ 169, 105, 67 }, { 169, 106, 67 },{ 169, 106, 67 },{ 170, 106, 68 },{ 170, 106, 68 },{ 170, 106, 68 }, { 171, 107, 68 },{ 171, 107, 68 },{ 171, 107, 68 },{ 172, 107, 68 },{ 172, 107, 68 }, { 172, 108, 69 },{ 173, 108, 69 },{ 173, 108, 69 },{ 173, 108, 69 },{ 174, 108, 69 }, { 174, 109, 69 },{ 174, 109, 69 },{ 175, 109, 69 },{ 175, 109, 70 },{ 175, 109, 70 }, { 175, 110, 70 },{ 176, 110, 70 },{ 176, 110, 70 },{ 176, 110, 70 },{ 177, 110, 70 }, { 177, 111, 70 },{ 177, 111, 71 },{ 178, 111, 71 },{ 178, 111, 71 },{ 178, 111, 71 }, { 179, 112, 71 },{ 179, 112, 71 },{ 179, 112, 71 },{ 180, 112, 71 },{ 180, 112, 72 }, { 180, 113, 72 },{ 181, 113, 72 },{ 181, 113, 72 },{ 181, 113, 72 },{ 182, 113, 72 }, { 182, 114, 72 },{ 182, 114, 73 },{ 183, 114, 73 },{ 183, 114, 73 },{ 183, 114, 73 }, { 183, 115, 73 },{ 184, 115, 73 },{ 184, 115, 73 },{ 184, 115, 73 },{ 185, 115, 74 }, { 185, 116, 74 },{ 185, 116, 74 },{ 186, 116, 74 },{ 186, 116, 74 },{ 186, 116, 74 }, { 187, 117, 74 },{ 187, 117, 74 },{ 187, 117, 75 },{ 188, 117, 75 },{ 188, 117, 75 }, { 188, 118, 75 },{ 189, 118, 75 },{ 189, 118, 75 },{ 189, 118, 75 },{ 190, 118, 75 }, { 190, 119, 76 },{ 190, 119, 76 },{ 190, 119, 76 },{ 191, 119, 76 },{ 191, 119, 76 }, { 191, 120, 76 },{ 192, 120, 76 },{ 192, 120, 76 },{ 192, 120, 77 },{ 193, 120, 77 }, { 193, 121, 77 },{ 193, 121, 77 },{ 194, 121, 77 },{ 194, 121, 77 },{ 194, 121, 77 }, { 195, 122, 77 },{ 195, 122, 78 },{ 195, 122, 78 },{ 196, 122, 78 },{ 196, 122, 78 }, { 196, 123, 78 },{ 197, 123, 78 },{ 197, 123, 78 },{ 197, 123, 78 },{ 198, 123, 79 }, { 198, 124, 79 },{ 198, 124, 79 },{ 198, 124, 79 },{ 199, 124, 79 },{ 199, 124, 79 }, { 199, 125, 79 },{ 200, 125, 79 },{ 200, 125, 80 },{ 200, 125, 80 },{ 201, 125, 80 }, { 201, 126, 80 },{ 201, 126, 80 },{ 202, 126, 80 },{ 202, 126, 80 },{ 202, 126, 81 }, { 203, 127, 81 },{ 203, 127, 81 },{ 203, 127, 81 },{ 204, 127, 81 },{ 204, 127, 81 }, { 204, 128, 81 },{ 205, 128, 81 },{ 205, 128, 82 },{ 205, 128, 82 },{ 205, 128, 82 }, { 206, 129, 82 },{ 206, 129, 82 },{ 206, 129, 82 },{ 207, 129, 82 },{ 207, 129, 82 }, { 207, 130, 83 },{ 208, 130, 83 },{ 208, 130, 83 },{ 208, 130, 83 },{ 209, 130, 83 }, { 209, 131, 83 },{ 209, 131, 83 },{ 210, 131, 83 },{ 210, 131, 84 },{ 210, 131, 84 }, { 211, 132, 84 },{ 211, 132, 84 },{ 211, 132, 84 },{ 212, 132, 84 },{ 212, 132, 84 }, { 212, 133, 84 },{ 212, 133, 85 },{ 213, 133, 85 },{ 213, 133, 85 },{ 213, 133, 85 }, { 214, 134, 85 },{ 214, 134, 85 },{ 214, 134, 85 },{ 215, 134, 85 },{ 215, 134, 86 }, { 215, 135, 86 },{ 216, 135, 86 },{ 216, 135, 86 },{ 216, 135, 86 },{ 217, 135, 86 }, { 217, 136, 86 },{ 217, 136, 86 },{ 218, 136, 87 },{ 218, 136, 87 },{ 218, 136, 87 }, { 219, 137, 87 },{ 219, 137, 87 },{ 219, 137, 87 },{ 220, 137, 87 },{ 220, 137, 87 }, { 220, 138, 88 },{ 220, 138, 88 },{ 221, 138, 88 },{ 221, 138, 88 },{ 221, 138, 88 }, { 222, 139, 88 },{ 222, 139, 88 },{ 222, 139, 89 },{ 223, 139, 89 },{ 223, 139, 89 }, { 223, 140, 89 },{ 224, 140, 89 },{ 224, 140, 89 },{ 224, 140, 89 },{ 225, 140, 89 }, { 225, 141, 90 },{ 225, 141, 90 },{ 226, 141, 90 },{ 226, 141, 90 },{ 226, 141, 90 }, { 227, 142, 90 },{ 227, 142, 90 },{ 227, 142, 90 },{ 227, 142, 91 },{ 228, 142, 91 }, { 228, 143, 91 },{ 228, 143, 91 },{ 229, 143, 91 },{ 229, 143, 91 },{ 229, 143, 91 }, { 230, 144, 91 },{ 230, 144, 92 },{ 230, 144, 92 },{ 231, 144, 92 },{ 231, 144, 92 }, { 231, 145, 92 },{ 232, 145, 92 },{ 232, 145, 92 },{ 232, 145, 92 },{ 233, 145, 93 }, { 233, 146, 93 },{ 233, 146, 93 },{ 234, 146, 93 },{ 234, 146, 93 },{ 234, 146, 93 }, { 235, 147, 93 },{ 235, 147, 93 },{ 235, 147, 94 },{ 235, 147, 94 },{ 236, 147, 94 }, { 236, 148, 94 },{ 236, 148, 94 },{ 237, 148, 94 },{ 237, 148, 94 },{ 237, 148, 94 }, { 238, 149, 95 },{ 238, 149, 95 },{ 238, 149, 95 },{ 239, 149, 95 },{ 239, 149, 95 }, { 239, 150, 95 },{ 240, 150, 95 },{ 240, 150, 95 },{ 240, 150, 96 },{ 241, 150, 96 }, { 241, 151, 96 },{ 241, 151, 96 },{ 242, 151, 96 },{ 242, 151, 96 },{ 242, 151, 96 }, { 242, 152, 97 },{ 243, 152, 97 },{ 243, 152, 97 },{ 243, 152, 97 },{ 244, 152, 97 }, { 244, 153, 97 },{ 244, 153, 97 },{ 245, 153, 97 },{ 245, 153, 98 },{ 245, 153, 98 }, { 246, 154, 98 },{ 246, 154, 98 },{ 246, 154, 98 },{ 247, 154, 98 },{ 247, 154, 98 }, { 247, 155, 98 },{ 248, 155, 99 },{ 248, 155, 99 },{ 248, 155, 99 },{ 249, 155, 99 }, { 249, 156, 99 },{ 249, 156, 99 },{ 250, 156, 99 },{ 250, 156, 99 },{ 250, 156, 100 }, { 250, 157, 100 },{ 251, 157, 100 },{ 251, 157, 100 },{ 251, 157, 100 },{ 252, 157, 100 }, { 252, 158, 100 },{ 252, 158, 100 },{ 253, 158, 101 },{ 253, 158, 101 },{ 253, 158, 101 }, { 253, 159, 101 },{ 253, 159, 101 },{ 254, 159, 101 },{ 254, 159, 101 },{ 254, 159, 101 }, { 254, 160, 102 },{ 254, 160, 102 },{ 254, 160, 102 },{ 254, 160, 102 },{ 254, 160, 102 }, { 255, 161, 102 },{ 255, 161, 102 },{ 255, 161, 102 },{ 255, 161, 103 },{ 255, 161, 103 }, { 255, 162, 103 },{ 255, 162, 103 },{ 255, 162, 103 },{ 255, 162, 103 },{ 255, 162, 103 }, { 255, 163, 103 },{ 255, 163, 104 },{ 255, 163, 104 },{ 255, 163, 104 },{ 255, 163, 104 }, { 255, 164, 104 },{ 255, 164, 104 },{ 255, 164, 104 },{ 255, 164, 105 },{ 255, 164, 105 }, { 255, 165, 105 },{ 255, 165, 105 },{ 255, 165, 105 },{ 255, 165, 105 },{ 255, 165, 105 }, { 255, 166, 105 },{ 255, 166, 106 },{ 255, 166, 106 },{ 255, 166, 106 },{ 255, 166, 106 }, { 255, 167, 106 },{ 255, 167, 106 },{ 255, 167, 106 },{ 255, 167, 106 },{ 255, 167, 107 }, { 255, 168, 107 },{ 255, 168, 107 },{ 255, 168, 107 },{ 255, 168, 107 },{ 255, 168, 107 }, { 255, 168, 107 },{ 255, 169, 107 },{ 255, 169, 108 },{ 255, 169, 108 },{ 255, 169, 108 }, { 255, 169, 108 },{ 255, 170, 108 },{ 255, 170, 108 },{ 255, 170, 108 },{ 255, 170, 108 }, { 255, 170, 109 },{ 255, 171, 109 },{ 255, 171, 109 },{ 255, 171, 109 },{ 255, 171, 109 }, { 255, 171, 109 },{ 255, 172, 109 },{ 255, 172, 109 },{ 255, 172, 110 },{ 255, 172, 110 }, { 255, 172, 110 },{ 255, 173, 110 },{ 255, 173, 110 },{ 255, 173, 110 },{ 255, 173, 110 }, { 255, 173, 110 },{ 255, 174, 111 },{ 255, 174, 111 },{ 255, 174, 111 },{ 255, 174, 111 }, { 255, 174, 111 },{ 255, 175, 111 },{ 255, 175, 111 },{ 255, 175, 111 },{ 255, 175, 112 }, { 255, 175, 112 },{ 255, 176, 112 },{ 255, 176, 112 },{ 255, 176, 112 },{ 255, 176, 112 }, { 255, 176, 112 },{ 255, 177, 113 },{ 255, 177, 113 },{ 255, 177, 113 },{ 255, 177, 113 }, { 255, 177, 113 },{ 255, 178, 113 },{ 255, 178, 113 },{ 255, 178, 113 },{ 255, 178, 114 }, { 255, 178, 114 },{ 255, 179, 114 },{ 255, 179, 114 },{ 255, 179, 114 },{ 255, 179, 114 }, { 255, 179, 114 },{ 255, 180, 114 },{ 255, 180, 115 },{ 255, 180, 115 },{ 255, 180, 115 }, { 255, 180, 115 },{ 255, 181, 115 },{ 255, 181, 115 },{ 255, 181, 115 },{ 255, 181, 115 }, { 255, 181, 116 },{ 255, 182, 116 },{ 255, 182, 116 },{ 255, 182, 116 },{ 255, 182, 116 }, { 255, 182, 116 },{ 255, 183, 116 },{ 255, 183, 116 },{ 255, 183, 117 },{ 255, 183, 117 }, { 255, 183, 117 },{ 255, 184, 117 },{ 255, 184, 117 },{ 255, 184, 117 },{ 255, 184, 117 }, { 255, 184, 117 },{ 255, 185, 118 },{ 255, 185, 118 },{ 255, 185, 118 },{ 255, 185, 118 }, { 255, 185, 118 },{ 255, 186, 118 },{ 255, 186, 118 },{ 255, 186, 118 },{ 255, 186, 119 }, { 255, 186, 119 },{ 255, 187, 119 },{ 255, 187, 119 },{ 255, 187, 119 },{ 255, 187, 119 }, { 255, 187, 119 },{ 255, 188, 119 },{ 255, 188, 120 },{ 255, 188, 120 },{ 255, 188, 120 }, { 255, 188, 120 },{ 255, 189, 120 },{ 255, 189, 120 },{ 255, 189, 120 },{ 255, 189, 121 }, { 255, 189, 121 },{ 255, 190, 121 },{ 255, 190, 121 },{ 255, 190, 121 },{ 255, 190, 121 }, { 255, 190, 121 },{ 255, 191, 121 },{ 255, 191, 122 },{ 255, 191, 122 },{ 255, 191, 122 }, { 255, 191, 122 },{ 255, 192, 122 },{ 255, 192, 122 },{ 255, 192, 122 },{ 255, 192, 122 }, { 255, 192, 123 },{ 255, 193, 123 },{ 255, 193, 123 },{ 255, 193, 123 },{ 255, 193, 123 }, { 255, 193, 123 },{ 255, 194, 123 },{ 255, 194, 123 },{ 255, 194, 124 },{ 255, 194, 124 }, { 255, 194, 124 },{ 255, 195, 124 },{ 255, 195, 124 },{ 255, 195, 124 },{ 255, 195, 124 }, { 255, 195, 124 },{ 255, 196, 125 },{ 255, 196, 125 },{ 255, 196, 125 },{ 255, 196, 125 }, { 255, 196, 125 },{ 255, 197, 125 },{ 255, 197, 125 },{ 255, 197, 125 },{ 255, 197, 126 }, { 255, 197, 126 },{ 255, 198, 126 },{ 255, 198, 126 },{ 255, 198, 126 },{ 255, 198, 126 }, { 255, 198, 126 },{ 255, 199, 126 },{ 255, 199, 127 },{ 255, 199, 127 },{ 255, 199, 127 } }; const rgb_t gray_colormap[1000] = { { 255, 255, 255 },{ 255, 255, 255 },{ 254, 254, 254 },{ 254, 254, 254 },{ 254, 254, 254 }, { 254, 254, 254 },{ 253, 253, 253 },{ 253, 253, 253 },{ 253, 253, 253 },{ 253, 253, 253 }, { 252, 252, 252 },{ 252, 252, 252 },{ 252, 252, 252 },{ 252, 252, 252 },{ 251, 251, 251 }, { 251, 251, 251 },{ 251, 251, 251 },{ 251, 251, 251 },{ 250, 250, 250 },{ 250, 250, 250 }, { 250, 250, 250 },{ 250, 250, 250 },{ 249, 249, 249 },{ 249, 249, 249 },{ 249, 249, 249 }, { 249, 249, 249 },{ 248, 248, 248 },{ 248, 248, 248 },{ 248, 248, 248 },{ 248, 248, 248 }, { 247, 247, 247 },{ 247, 247, 247 },{ 247, 247, 247 },{ 247, 247, 247 },{ 246, 246, 246 }, { 246, 246, 246 },{ 246, 246, 246 },{ 246, 246, 246 },{ 245, 245, 245 },{ 245, 245, 245 }, { 245, 245, 245 },{ 245, 245, 245 },{ 244, 244, 244 },{ 244, 244, 244 },{ 244, 244, 244 }, { 244, 244, 244 },{ 243, 243, 243 },{ 243, 243, 243 },{ 243, 243, 243 },{ 242, 242, 242 }, { 242, 242, 242 },{ 242, 242, 242 },{ 242, 242, 242 },{ 241, 241, 241 },{ 241, 241, 241 }, { 241, 241, 241 },{ 241, 241, 241 },{ 240, 240, 240 },{ 240, 240, 240 },{ 240, 240, 240 }, { 240, 240, 240 },{ 239, 239, 239 },{ 239, 239, 239 },{ 239, 239, 239 },{ 239, 239, 239 }, { 238, 238, 238 },{ 238, 238, 238 },{ 238, 238, 238 },{ 238, 238, 238 },{ 237, 237, 237 }, { 237, 237, 237 },{ 237, 237, 237 },{ 237, 237, 237 },{ 236, 236, 236 },{ 236, 236, 236 }, { 236, 236, 236 },{ 236, 236, 236 },{ 235, 235, 235 },{ 235, 235, 235 },{ 235, 235, 235 }, { 235, 235, 235 },{ 234, 234, 234 },{ 234, 234, 234 },{ 234, 234, 234 },{ 234, 234, 234 }, { 233, 233, 233 },{ 233, 233, 233 },{ 233, 233, 233 },{ 233, 233, 233 },{ 232, 232, 232 }, { 232, 232, 232 },{ 232, 232, 232 },{ 232, 232, 232 },{ 231, 231, 231 },{ 231, 231, 231 }, { 231, 231, 231 },{ 230, 230, 230 },{ 230, 230, 230 },{ 230, 230, 230 },{ 230, 230, 230 }, { 229, 229, 229 },{ 229, 229, 229 },{ 229, 229, 229 },{ 229, 229, 229 },{ 228, 228, 228 }, { 228, 228, 228 },{ 228, 228, 228 },{ 228, 228, 228 },{ 227, 227, 227 },{ 227, 227, 227 }, { 227, 227, 227 },{ 227, 227, 227 },{ 226, 226, 226 },{ 226, 226, 226 },{ 226, 226, 226 }, { 226, 226, 226 },{ 225, 225, 225 },{ 225, 225, 225 },{ 225, 225, 225 },{ 225, 225, 225 }, { 224, 224, 224 },{ 224, 224, 224 },{ 224, 224, 224 },{ 224, 224, 224 },{ 223, 223, 223 }, { 223, 223, 223 },{ 223, 223, 223 },{ 223, 223, 223 },{ 222, 222, 222 },{ 222, 222, 222 }, { 222, 222, 222 },{ 222, 222, 222 },{ 221, 221, 221 },{ 221, 221, 221 },{ 221, 221, 221 }, { 221, 221, 221 },{ 220, 220, 220 },{ 220, 220, 220 },{ 220, 220, 220 },{ 220, 220, 220 }, { 219, 219, 219 },{ 219, 219, 219 },{ 219, 219, 219 },{ 218, 218, 218 },{ 218, 218, 218 }, { 218, 218, 218 },{ 218, 218, 218 },{ 217, 217, 217 },{ 217, 217, 217 },{ 217, 217, 217 }, { 217, 217, 217 },{ 216, 216, 216 },{ 216, 216, 216 },{ 216, 216, 216 },{ 216, 216, 216 }, { 215, 215, 215 },{ 215, 215, 215 },{ 215, 215, 215 },{ 215, 215, 215 },{ 214, 214, 214 }, { 214, 214, 214 },{ 214, 214, 214 },{ 214, 214, 214 },{ 213, 213, 213 },{ 213, 213, 213 }, { 213, 213, 213 },{ 213, 213, 213 },{ 212, 212, 212 },{ 212, 212, 212 },{ 212, 212, 212 }, { 212, 212, 212 },{ 211, 211, 211 },{ 211, 211, 211 },{ 211, 211, 211 },{ 211, 211, 211 }, { 210, 210, 210 },{ 210, 210, 210 },{ 210, 210, 210 },{ 210, 210, 210 },{ 209, 209, 209 }, { 209, 209, 209 },{ 209, 209, 209 },{ 209, 209, 209 },{ 208, 208, 208 },{ 208, 208, 208 }, { 208, 208, 208 },{ 208, 208, 208 },{ 207, 207, 207 },{ 207, 207, 207 },{ 207, 207, 207 }, { 207, 207, 207 },{ 206, 206, 206 },{ 206, 206, 206 },{ 206, 206, 206 },{ 205, 205, 205 }, { 205, 205, 205 },{ 205, 205, 205 },{ 205, 205, 205 },{ 204, 204, 204 },{ 204, 204, 204 }, { 204, 204, 204 },{ 204, 204, 204 },{ 203, 203, 203 },{ 203, 203, 203 },{ 203, 203, 203 }, { 203, 203, 203 },{ 202, 202, 202 },{ 202, 202, 202 },{ 202, 202, 202 },{ 202, 202, 202 }, { 201, 201, 201 },{ 201, 201, 201 },{ 201, 201, 201 },{ 201, 201, 201 },{ 200, 200, 200 }, { 200, 200, 200 },{ 200, 200, 200 },{ 200, 200, 200 },{ 199, 199, 199 },{ 199, 199, 199 }, { 199, 199, 199 },{ 199, 199, 199 },{ 198, 198, 198 },{ 198, 198, 198 },{ 198, 198, 198 }, { 198, 198, 198 },{ 197, 197, 197 },{ 197, 197, 197 },{ 197, 197, 197 },{ 197, 197, 197 }, { 196, 196, 196 },{ 196, 196, 196 },{ 196, 196, 196 },{ 196, 196, 196 },{ 195, 195, 195 }, { 195, 195, 195 },{ 195, 195, 195 },{ 195, 195, 195 },{ 194, 194, 194 },{ 194, 194, 194 }, { 194, 194, 194 },{ 193, 193, 193 },{ 193, 193, 193 },{ 193, 193, 193 },{ 193, 193, 193 }, { 192, 192, 192 },{ 192, 192, 192 },{ 192, 192, 192 },{ 192, 192, 192 },{ 191, 191, 191 }, { 191, 191, 191 },{ 191, 191, 191 },{ 191, 191, 191 },{ 190, 190, 190 },{ 190, 190, 190 }, { 190, 190, 190 },{ 190, 190, 190 },{ 189, 189, 189 },{ 189, 189, 189 },{ 189, 189, 189 }, { 189, 189, 189 },{ 188, 188, 188 },{ 188, 188, 188 },{ 188, 188, 188 },{ 188, 188, 188 }, { 187, 187, 187 },{ 187, 187, 187 },{ 187, 187, 187 },{ 187, 187, 187 },{ 186, 186, 186 }, { 186, 186, 186 },{ 186, 186, 186 },{ 186, 186, 186 },{ 185, 185, 185 },{ 185, 185, 185 }, { 185, 185, 185 },{ 185, 185, 185 },{ 184, 184, 184 },{ 184, 184, 184 },{ 184, 184, 184 }, { 184, 184, 184 },{ 183, 183, 183 },{ 183, 183, 183 },{ 183, 183, 183 },{ 183, 183, 183 }, { 182, 182, 182 },{ 182, 182, 182 },{ 182, 182, 182 },{ 181, 181, 181 },{ 181, 181, 181 }, { 181, 181, 181 },{ 181, 181, 181 },{ 180, 180, 180 },{ 180, 180, 180 },{ 180, 180, 180 }, { 180, 180, 180 },{ 179, 179, 179 },{ 179, 179, 179 },{ 179, 179, 179 },{ 179, 179, 179 }, { 178, 178, 178 },{ 178, 178, 178 },{ 178, 178, 178 },{ 178, 178, 178 },{ 177, 177, 177 }, { 177, 177, 177 },{ 177, 177, 177 },{ 177, 177, 177 },{ 176, 176, 176 },{ 176, 176, 176 }, { 176, 176, 176 },{ 176, 176, 176 },{ 175, 175, 175 },{ 175, 175, 175 },{ 175, 175, 175 }, { 175, 175, 175 },{ 174, 174, 174 },{ 174, 174, 174 },{ 174, 174, 174 },{ 174, 174, 174 }, { 173, 173, 173 },{ 173, 173, 173 },{ 173, 173, 173 },{ 173, 173, 173 },{ 172, 172, 172 }, { 172, 172, 172 },{ 172, 172, 172 },{ 172, 172, 172 },{ 171, 171, 171 },{ 171, 171, 171 }, { 171, 171, 171 },{ 171, 171, 171 },{ 170, 170, 170 },{ 170, 170, 170 },{ 170, 170, 170 }, { 169, 169, 169 },{ 169, 169, 169 },{ 169, 169, 169 },{ 169, 169, 169 },{ 168, 168, 168 }, { 168, 168, 168 },{ 168, 168, 168 },{ 168, 168, 168 },{ 167, 167, 167 },{ 167, 167, 167 }, { 167, 167, 167 },{ 167, 167, 167 },{ 166, 166, 166 },{ 166, 166, 166 },{ 166, 166, 166 }, { 166, 166, 166 },{ 165, 165, 165 },{ 165, 165, 165 },{ 165, 165, 165 },{ 165, 165, 165 }, { 164, 164, 164 },{ 164, 164, 164 },{ 164, 164, 164 },{ 164, 164, 164 },{ 163, 163, 163 }, { 163, 163, 163 },{ 163, 163, 163 },{ 163, 163, 163 },{ 162, 162, 162 },{ 162, 162, 162 }, { 162, 162, 162 },{ 162, 162, 162 },{ 161, 161, 161 },{ 161, 161, 161 },{ 161, 161, 161 }, { 161, 161, 161 },{ 160, 160, 160 },{ 160, 160, 160 },{ 160, 160, 160 },{ 160, 160, 160 }, { 159, 159, 159 },{ 159, 159, 159 },{ 159, 159, 159 },{ 159, 159, 159 },{ 158, 158, 158 }, { 158, 158, 158 },{ 158, 158, 158 },{ 157, 157, 157 },{ 157, 157, 157 },{ 157, 157, 157 }, { 157, 157, 157 },{ 156, 156, 156 },{ 156, 156, 156 },{ 156, 156, 156 },{ 156, 156, 156 }, { 155, 155, 155 },{ 155, 155, 155 },{ 155, 155, 155 },{ 155, 155, 155 },{ 154, 154, 154 }, { 154, 154, 154 },{ 154, 154, 154 },{ 154, 154, 154 },{ 153, 153, 153 },{ 153, 153, 153 }, { 153, 153, 153 },{ 153, 153, 153 },{ 152, 152, 152 },{ 152, 152, 152 },{ 152, 152, 152 }, { 152, 152, 152 },{ 151, 151, 151 },{ 151, 151, 151 },{ 151, 151, 151 },{ 151, 151, 151 }, { 150, 150, 150 },{ 150, 150, 150 },{ 150, 150, 150 },{ 150, 150, 150 },{ 149, 149, 149 }, { 149, 149, 149 },{ 149, 149, 149 },{ 149, 149, 149 },{ 148, 148, 148 },{ 148, 148, 148 }, { 148, 148, 148 },{ 148, 148, 148 },{ 147, 147, 147 },{ 147, 147, 147 },{ 147, 147, 147 }, { 147, 147, 147 },{ 146, 146, 146 },{ 146, 146, 146 },{ 146, 146, 146 },{ 145, 145, 145 }, { 145, 145, 145 },{ 145, 145, 145 },{ 145, 145, 145 },{ 144, 144, 144 },{ 144, 144, 144 }, { 144, 144, 144 },{ 144, 144, 144 },{ 143, 143, 143 },{ 143, 143, 143 },{ 143, 143, 143 }, { 143, 143, 143 },{ 142, 142, 142 },{ 142, 142, 142 },{ 142, 142, 142 },{ 142, 142, 142 }, { 141, 141, 141 },{ 141, 141, 141 },{ 141, 141, 141 },{ 141, 141, 141 },{ 140, 140, 140 }, { 140, 140, 140 },{ 140, 140, 140 },{ 140, 140, 140 },{ 139, 139, 139 },{ 139, 139, 139 }, { 139, 139, 139 },{ 139, 139, 139 },{ 138, 138, 138 },{ 138, 138, 138 },{ 138, 138, 138 }, { 138, 138, 138 },{ 137, 137, 137 },{ 137, 137, 137 },{ 137, 137, 137 },{ 137, 137, 137 }, { 136, 136, 136 },{ 136, 136, 136 },{ 136, 136, 136 },{ 136, 136, 136 },{ 135, 135, 135 }, { 135, 135, 135 },{ 135, 135, 135 },{ 135, 135, 135 },{ 134, 134, 134 },{ 134, 134, 134 }, { 134, 134, 134 },{ 133, 133, 133 },{ 133, 133, 133 },{ 133, 133, 133 },{ 133, 133, 133 }, { 132, 132, 132 },{ 132, 132, 132 },{ 132, 132, 132 },{ 132, 132, 132 },{ 131, 131, 131 }, { 131, 131, 131 },{ 131, 131, 131 },{ 131, 131, 131 },{ 130, 130, 130 },{ 130, 130, 130 }, { 130, 130, 130 },{ 130, 130, 130 },{ 129, 129, 129 },{ 129, 129, 129 },{ 129, 129, 129 }, { 129, 129, 129 },{ 128, 128, 128 },{ 128, 128, 128 },{ 128, 128, 128 },{ 128, 128, 128 }, { 127, 127, 127 },{ 127, 127, 127 },{ 127, 127, 127 },{ 127, 127, 127 },{ 126, 126, 126 }, { 126, 126, 126 },{ 126, 126, 126 },{ 126, 126, 126 },{ 125, 125, 125 },{ 125, 125, 125 }, { 125, 125, 125 },{ 125, 125, 125 },{ 124, 124, 124 },{ 124, 124, 124 },{ 124, 124, 124 }, { 124, 124, 124 },{ 123, 123, 123 },{ 123, 123, 123 },{ 123, 123, 123 },{ 123, 123, 123 }, { 122, 122, 122 },{ 122, 122, 122 },{ 122, 122, 122 },{ 122, 122, 122 },{ 121, 121, 121 }, { 121, 121, 121 },{ 121, 121, 121 },{ 120, 120, 120 },{ 120, 120, 120 },{ 120, 120, 120 }, { 120, 120, 120 },{ 119, 119, 119 },{ 119, 119, 119 },{ 119, 119, 119 },{ 119, 119, 119 }, { 118, 118, 118 },{ 118, 118, 118 },{ 118, 118, 118 },{ 118, 118, 118 },{ 117, 117, 117 }, { 117, 117, 117 },{ 117, 117, 117 },{ 117, 117, 117 },{ 116, 116, 116 },{ 116, 116, 116 }, { 116, 116, 116 },{ 116, 116, 116 },{ 115, 115, 115 },{ 115, 115, 115 },{ 115, 115, 115 }, { 115, 115, 115 },{ 114, 114, 114 },{ 114, 114, 114 },{ 114, 114, 114 },{ 114, 114, 114 }, { 113, 113, 113 },{ 113, 113, 113 },{ 113, 113, 113 },{ 113, 113, 113 },{ 112, 112, 112 }, { 112, 112, 112 },{ 112, 112, 112 },{ 112, 112, 112 },{ 111, 111, 111 },{ 111, 111, 111 }, { 111, 111, 111 },{ 111, 111, 111 },{ 110, 110, 110 },{ 110, 110, 110 },{ 110, 110, 110 }, { 110, 110, 110 },{ 109, 109, 109 },{ 109, 109, 109 },{ 109, 109, 109 },{ 108, 108, 108 }, { 108, 108, 108 },{ 108, 108, 108 },{ 108, 108, 108 },{ 107, 107, 107 },{ 107, 107, 107 }, { 107, 107, 107 },{ 107, 107, 107 },{ 106, 106, 106 },{ 106, 106, 106 },{ 106, 106, 106 }, { 106, 106, 106 },{ 105, 105, 105 },{ 105, 105, 105 },{ 105, 105, 105 },{ 105, 105, 105 }, { 104, 104, 104 },{ 104, 104, 104 },{ 104, 104, 104 },{ 104, 104, 104 },{ 103, 103, 103 }, { 103, 103, 103 },{ 103, 103, 103 },{ 103, 103, 103 },{ 102, 102, 102 },{ 102, 102, 102 }, { 102, 102, 102 },{ 102, 102, 102 },{ 101, 101, 101 },{ 101, 101, 101 },{ 101, 101, 101 }, { 101, 101, 101 },{ 100, 100, 100 },{ 100, 100, 100 },{ 100, 100, 100 },{ 100, 100, 100 }, { 99, 99, 99 },{ 99, 99, 99 },{ 99, 99, 99 },{ 99, 99, 99 },{ 98, 98, 98 }, { 98, 98, 98 },{ 98, 98, 98 },{ 98, 98, 98 },{ 97, 97, 97 },{ 97, 97, 97 }, { 97, 97, 97 },{ 96, 96, 96 },{ 96, 96, 96 },{ 96, 96, 96 },{ 96, 96, 96 }, { 95, 95, 95 },{ 95, 95, 95 },{ 95, 95, 95 },{ 95, 95, 95 },{ 94, 94, 94 }, { 94, 94, 94 },{ 94, 94, 94 },{ 94, 94, 94 },{ 93, 93, 93 },{ 93, 93, 93 }, { 93, 93, 93 },{ 93, 93, 93 },{ 92, 92, 92 },{ 92, 92, 92 },{ 92, 92, 92 }, { 92, 92, 92 },{ 91, 91, 91 },{ 91, 91, 91 },{ 91, 91, 91 },{ 91, 91, 91 }, { 90, 90, 90 },{ 90, 90, 90 },{ 90, 90, 90 },{ 90, 90, 90 },{ 89, 89, 89 }, { 89, 89, 89 },{ 89, 89, 89 },{ 89, 89, 89 },{ 88, 88, 88 },{ 88, 88, 88 }, { 88, 88, 88 },{ 88, 88, 88 },{ 87, 87, 87 },{ 87, 87, 87 },{ 87, 87, 87 }, { 87, 87, 87 },{ 86, 86, 86 },{ 86, 86, 86 },{ 86, 86, 86 },{ 86, 86, 86 }, { 85, 85, 85 },{ 85, 85, 85 },{ 85, 85, 85 },{ 84, 84, 84 },{ 84, 84, 84 }, { 84, 84, 84 },{ 84, 84, 84 },{ 83, 83, 83 },{ 83, 83, 83 },{ 83, 83, 83 }, { 83, 83, 83 },{ 82, 82, 82 },{ 82, 82, 82 },{ 82, 82, 82 },{ 82, 82, 82 }, { 81, 81, 81 },{ 81, 81, 81 },{ 81, 81, 81 },{ 81, 81, 81 },{ 80, 80, 80 }, { 80, 80, 80 },{ 80, 80, 80 },{ 80, 80, 80 },{ 79, 79, 79 },{ 79, 79, 79 }, { 79, 79, 79 },{ 79, 79, 79 },{ 78, 78, 78 },{ 78, 78, 78 },{ 78, 78, 78 }, { 78, 78, 78 },{ 77, 77, 77 },{ 77, 77, 77 },{ 77, 77, 77 },{ 77, 77, 77 }, { 76, 76, 76 },{ 76, 76, 76 },{ 76, 76, 76 },{ 76, 76, 76 },{ 75, 75, 75 }, { 75, 75, 75 },{ 75, 75, 75 },{ 75, 75, 75 },{ 74, 74, 74 },{ 74, 74, 74 }, { 74, 74, 74 },{ 74, 74, 74 },{ 73, 73, 73 },{ 73, 73, 73 },{ 73, 73, 73 }, { 72, 72, 72 },{ 72, 72, 72 },{ 72, 72, 72 },{ 72, 72, 72 },{ 71, 71, 71 }, { 71, 71, 71 },{ 71, 71, 71 },{ 71, 71, 71 },{ 70, 70, 70 },{ 70, 70, 70 }, { 70, 70, 70 },{ 70, 70, 70 },{ 69, 69, 69 },{ 69, 69, 69 },{ 69, 69, 69 }, { 69, 69, 69 },{ 68, 68, 68 },{ 68, 68, 68 },{ 68, 68, 68 },{ 68, 68, 68 }, { 67, 67, 67 },{ 67, 67, 67 },{ 67, 67, 67 },{ 67, 67, 67 },{ 66, 66, 66 }, { 66, 66, 66 },{ 66, 66, 66 },{ 66, 66, 66 },{ 65, 65, 65 },{ 65, 65, 65 }, { 65, 65, 65 },{ 65, 65, 65 },{ 64, 64, 64 },{ 64, 64, 64 },{ 64, 64, 64 }, { 64, 64, 64 },{ 63, 63, 63 },{ 63, 63, 63 },{ 63, 63, 63 },{ 63, 63, 63 }, { 62, 62, 62 },{ 62, 62, 62 },{ 62, 62, 62 },{ 62, 62, 62 },{ 61, 61, 61 }, { 61, 61, 61 },{ 61, 61, 61 },{ 60, 60, 60 },{ 60, 60, 60 },{ 60, 60, 60 }, { 60, 60, 60 },{ 59, 59, 59 },{ 59, 59, 59 },{ 59, 59, 59 },{ 59, 59, 59 }, { 58, 58, 58 },{ 58, 58, 58 },{ 58, 58, 58 },{ 58, 58, 58 },{ 57, 57, 57 }, { 57, 57, 57 },{ 57, 57, 57 },{ 57, 57, 57 },{ 56, 56, 56 },{ 56, 56, 56 }, { 56, 56, 56 },{ 56, 56, 56 },{ 55, 55, 55 },{ 55, 55, 55 },{ 55, 55, 55 }, { 55, 55, 55 },{ 54, 54, 54 },{ 54, 54, 54 },{ 54, 54, 54 },{ 54, 54, 54 }, { 53, 53, 53 },{ 53, 53, 53 },{ 53, 53, 53 },{ 53, 53, 53 },{ 52, 52, 52 }, { 52, 52, 52 },{ 52, 52, 52 },{ 52, 52, 52 },{ 51, 51, 51 },{ 51, 51, 51 }, { 51, 51, 51 },{ 51, 51, 51 },{ 50, 50, 50 },{ 50, 50, 50 },{ 50, 50, 50 }, { 50, 50, 50 },{ 49, 49, 49 },{ 49, 49, 49 },{ 49, 49, 49 },{ 48, 48, 48 }, { 48, 48, 48 },{ 48, 48, 48 },{ 48, 48, 48 },{ 47, 47, 47 },{ 47, 47, 47 }, { 47, 47, 47 },{ 47, 47, 47 },{ 46, 46, 46 },{ 46, 46, 46 },{ 46, 46, 46 }, { 46, 46, 46 },{ 45, 45, 45 },{ 45, 45, 45 },{ 45, 45, 45 },{ 45, 45, 45 }, { 44, 44, 44 },{ 44, 44, 44 },{ 44, 44, 44 },{ 44, 44, 44 },{ 43, 43, 43 }, { 43, 43, 43 },{ 43, 43, 43 },{ 43, 43, 43 },{ 42, 42, 42 },{ 42, 42, 42 }, { 42, 42, 42 },{ 42, 42, 42 },{ 41, 41, 41 },{ 41, 41, 41 },{ 41, 41, 41 }, { 41, 41, 41 },{ 40, 40, 40 },{ 40, 40, 40 },{ 40, 40, 40 },{ 40, 40, 40 }, { 39, 39, 39 },{ 39, 39, 39 },{ 39, 39, 39 },{ 39, 39, 39 },{ 38, 38, 38 }, { 38, 38, 38 },{ 38, 38, 38 },{ 38, 38, 38 },{ 37, 37, 37 },{ 37, 37, 37 }, { 37, 37, 37 },{ 37, 37, 37 },{ 36, 36, 36 },{ 36, 36, 36 },{ 36, 36, 36 }, { 35, 35, 35 },{ 35, 35, 35 },{ 35, 35, 35 },{ 35, 35, 35 },{ 34, 34, 34 }, { 34, 34, 34 },{ 34, 34, 34 },{ 34, 34, 34 },{ 33, 33, 33 },{ 33, 33, 33 }, { 33, 33, 33 },{ 33, 33, 33 },{ 32, 32, 32 },{ 32, 32, 32 },{ 32, 32, 32 }, { 32, 32, 32 },{ 31, 31, 31 },{ 31, 31, 31 },{ 31, 31, 31 },{ 31, 31, 31 }, { 30, 30, 30 },{ 30, 30, 30 },{ 30, 30, 30 },{ 30, 30, 30 },{ 29, 29, 29 }, { 29, 29, 29 },{ 29, 29, 29 },{ 29, 29, 29 },{ 28, 28, 28 },{ 28, 28, 28 }, { 28, 28, 28 },{ 28, 28, 28 },{ 27, 27, 27 },{ 27, 27, 27 },{ 27, 27, 27 }, { 27, 27, 27 },{ 26, 26, 26 },{ 26, 26, 26 },{ 26, 26, 26 },{ 26, 26, 26 }, { 25, 25, 25 },{ 25, 25, 25 },{ 25, 25, 25 },{ 25, 25, 25 },{ 24, 24, 24 }, { 24, 24, 24 },{ 24, 24, 24 },{ 23, 23, 23 },{ 23, 23, 23 },{ 23, 23, 23 }, { 23, 23, 23 },{ 22, 22, 22 },{ 22, 22, 22 },{ 22, 22, 22 },{ 22, 22, 22 }, { 21, 21, 21 },{ 21, 21, 21 },{ 21, 21, 21 },{ 21, 21, 21 },{ 20, 20, 20 }, { 20, 20, 20 },{ 20, 20, 20 },{ 20, 20, 20 },{ 19, 19, 19 },{ 19, 19, 19 }, { 19, 19, 19 },{ 19, 19, 19 },{ 18, 18, 18 },{ 18, 18, 18 },{ 18, 18, 18 }, { 18, 18, 18 },{ 17, 17, 17 },{ 17, 17, 17 },{ 17, 17, 17 },{ 17, 17, 17 }, { 16, 16, 16 },{ 16, 16, 16 },{ 16, 16, 16 },{ 16, 16, 16 },{ 15, 15, 15 }, { 15, 15, 15 },{ 15, 15, 15 },{ 15, 15, 15 },{ 14, 14, 14 },{ 14, 14, 14 }, { 14, 14, 14 },{ 14, 14, 14 },{ 13, 13, 13 },{ 13, 13, 13 },{ 13, 13, 13 }, { 13, 13, 13 },{ 12, 12, 12 },{ 12, 12, 12 },{ 12, 12, 12 },{ 11, 11, 11 }, { 11, 11, 11 },{ 11, 11, 11 },{ 11, 11, 11 },{ 10, 10, 10 },{ 10, 10, 10 }, { 10, 10, 10 },{ 10, 10, 10 },{ 9, 9, 9 },{ 9, 9, 9 },{ 9, 9, 9 }, { 9, 9, 9 },{ 8, 8, 8 },{ 8, 8, 8 },{ 8, 8, 8 },{ 8, 8, 8 }, { 7, 7, 7 },{ 7, 7, 7 },{ 7, 7, 7 },{ 7, 7, 7 },{ 6, 6, 6 }, { 6, 6, 6 },{ 6, 6, 6 },{ 6, 6, 6 },{ 5, 5, 5 },{ 5, 5, 5 }, { 5, 5, 5 },{ 5, 5, 5 },{ 4, 4, 4 },{ 4, 4, 4 },{ 4, 4, 4 }, { 4, 4, 4 },{ 3, 3, 3 },{ 3, 3, 3 },{ 3, 3, 3 },{ 3, 3, 3 }, { 2, 2, 2 },{ 2, 2, 2 },{ 2, 2, 2 },{ 2, 2, 2 },{ 1, 1, 1 }, { 1, 1, 1 },{ 1, 1, 1 },{ 1, 1, 1 },{ 0, 0, 0 },{ 0, 0, 0 } }; const rgb_t hot_colormap[1000] = { { 11, 0, 0 },{ 11, 0, 0 },{ 12, 0, 0 },{ 13, 0, 0 },{ 13, 0, 0 }, { 14, 0, 0 },{ 15, 0, 0 },{ 15, 0, 0 },{ 16, 0, 0 },{ 17, 0, 0 }, { 17, 0, 0 },{ 18, 0, 0 },{ 19, 0, 0 },{ 19, 0, 0 },{ 20, 0, 0 }, { 21, 0, 0 },{ 21, 0, 0 },{ 22, 0, 0 },{ 23, 0, 0 },{ 23, 0, 0 }, { 24, 0, 0 },{ 25, 0, 0 },{ 25, 0, 0 },{ 26, 0, 0 },{ 27, 0, 0 }, { 27, 0, 0 },{ 28, 0, 0 },{ 29, 0, 0 },{ 29, 0, 0 },{ 30, 0, 0 }, { 31, 0, 0 },{ 31, 0, 0 },{ 32, 0, 0 },{ 33, 0, 0 },{ 33, 0, 0 }, { 34, 0, 0 },{ 35, 0, 0 },{ 35, 0, 0 },{ 36, 0, 0 },{ 37, 0, 0 }, { 37, 0, 0 },{ 38, 0, 0 },{ 39, 0, 0 },{ 39, 0, 0 },{ 40, 0, 0 }, { 41, 0, 0 },{ 41, 0, 0 },{ 42, 0, 0 },{ 43, 0, 0 },{ 43, 0, 0 }, { 44, 0, 0 },{ 45, 0, 0 },{ 45, 0, 0 },{ 46, 0, 0 },{ 47, 0, 0 }, { 47, 0, 0 },{ 48, 0, 0 },{ 49, 0, 0 },{ 49, 0, 0 },{ 50, 0, 0 }, { 51, 0, 0 },{ 51, 0, 0 },{ 52, 0, 0 },{ 53, 0, 0 },{ 54, 0, 0 }, { 54, 0, 0 },{ 55, 0, 0 },{ 56, 0, 0 },{ 56, 0, 0 },{ 57, 0, 0 }, { 58, 0, 0 },{ 58, 0, 0 },{ 59, 0, 0 },{ 60, 0, 0 },{ 60, 0, 0 }, { 61, 0, 0 },{ 62, 0, 0 },{ 62, 0, 0 },{ 63, 0, 0 },{ 64, 0, 0 }, { 64, 0, 0 },{ 65, 0, 0 },{ 66, 0, 0 },{ 66, 0, 0 },{ 67, 0, 0 }, { 68, 0, 0 },{ 68, 0, 0 },{ 69, 0, 0 },{ 70, 0, 0 },{ 70, 0, 0 }, { 71, 0, 0 },{ 72, 0, 0 },{ 72, 0, 0 },{ 73, 0, 0 },{ 74, 0, 0 }, { 74, 0, 0 },{ 75, 0, 0 },{ 76, 0, 0 },{ 76, 0, 0 },{ 77, 0, 0 }, { 78, 0, 0 },{ 78, 0, 0 },{ 79, 0, 0 },{ 80, 0, 0 },{ 80, 0, 0 }, { 81, 0, 0 },{ 82, 0, 0 },{ 82, 0, 0 },{ 83, 0, 0 },{ 84, 0, 0 }, { 84, 0, 0 },{ 85, 0, 0 },{ 86, 0, 0 },{ 86, 0, 0 },{ 87, 0, 0 }, { 88, 0, 0 },{ 88, 0, 0 },{ 89, 0, 0 },{ 90, 0, 0 },{ 90, 0, 0 }, { 91, 0, 0 },{ 92, 0, 0 },{ 92, 0, 0 },{ 93, 0, 0 },{ 94, 0, 0 }, { 94, 0, 0 },{ 95, 0, 0 },{ 96, 0, 0 },{ 96, 0, 0 },{ 97, 0, 0 }, { 98, 0, 0 },{ 98, 0, 0 },{ 99, 0, 0 },{ 100, 0, 0 },{ 100, 0, 0 }, { 101, 0, 0 },{ 102, 0, 0 },{ 102, 0, 0 },{ 103, 0, 0 },{ 104, 0, 0 }, { 104, 0, 0 },{ 105, 0, 0 },{ 106, 0, 0 },{ 106, 0, 0 },{ 107, 0, 0 }, { 108, 0, 0 },{ 108, 0, 0 },{ 109, 0, 0 },{ 110, 0, 0 },{ 110, 0, 0 }, { 111, 0, 0 },{ 112, 0, 0 },{ 112, 0, 0 },{ 113, 0, 0 },{ 114, 0, 0 }, { 114, 0, 0 },{ 115, 0, 0 },{ 116, 0, 0 },{ 116, 0, 0 },{ 117, 0, 0 }, { 118, 0, 0 },{ 119, 0, 0 },{ 119, 0, 0 },{ 120, 0, 0 },{ 121, 0, 0 }, { 121, 0, 0 },{ 122, 0, 0 },{ 123, 0, 0 },{ 123, 0, 0 },{ 124, 0, 0 }, { 125, 0, 0 },{ 125, 0, 0 },{ 126, 0, 0 },{ 127, 0, 0 },{ 127, 0, 0 }, { 128, 0, 0 },{ 129, 0, 0 },{ 129, 0, 0 },{ 130, 0, 0 },{ 131, 0, 0 }, { 131, 0, 0 },{ 132, 0, 0 },{ 133, 0, 0 },{ 133, 0, 0 },{ 134, 0, 0 }, { 135, 0, 0 },{ 135, 0, 0 },{ 136, 0, 0 },{ 137, 0, 0 },{ 137, 0, 0 }, { 138, 0, 0 },{ 139, 0, 0 },{ 139, 0, 0 },{ 140, 0, 0 },{ 141, 0, 0 }, { 141, 0, 0 },{ 142, 0, 0 },{ 143, 0, 0 },{ 143, 0, 0 },{ 144, 0, 0 }, { 145, 0, 0 },{ 145, 0, 0 },{ 146, 0, 0 },{ 147, 0, 0 },{ 147, 0, 0 }, { 148, 0, 0 },{ 149, 0, 0 },{ 149, 0, 0 },{ 150, 0, 0 },{ 151, 0, 0 }, { 151, 0, 0 },{ 152, 0, 0 },{ 153, 0, 0 },{ 153, 0, 0 },{ 154, 0, 0 }, { 155, 0, 0 },{ 155, 0, 0 },{ 156, 0, 0 },{ 157, 0, 0 },{ 157, 0, 0 }, { 158, 0, 0 },{ 159, 0, 0 },{ 159, 0, 0 },{ 160, 0, 0 },{ 161, 0, 0 }, { 161, 0, 0 },{ 162, 0, 0 },{ 163, 0, 0 },{ 163, 0, 0 },{ 164, 0, 0 }, { 165, 0, 0 },{ 165, 0, 0 },{ 166, 0, 0 },{ 167, 0, 0 },{ 167, 0, 0 }, { 168, 0, 0 },{ 169, 0, 0 },{ 169, 0, 0 },{ 170, 0, 0 },{ 171, 0, 0 }, { 171, 0, 0 },{ 172, 0, 0 },{ 173, 0, 0 },{ 173, 0, 0 },{ 174, 0, 0 }, { 175, 0, 0 },{ 175, 0, 0 },{ 176, 0, 0 },{ 177, 0, 0 },{ 177, 0, 0 }, { 178, 0, 0 },{ 179, 0, 0 },{ 179, 0, 0 },{ 180, 0, 0 },{ 181, 0, 0 }, { 181, 0, 0 },{ 182, 0, 0 },{ 183, 0, 0 },{ 183, 0, 0 },{ 184, 0, 0 }, { 185, 0, 0 },{ 186, 0, 0 },{ 186, 0, 0 },{ 187, 0, 0 },{ 188, 0, 0 }, { 188, 0, 0 },{ 189, 0, 0 },{ 190, 0, 0 },{ 190, 0, 0 },{ 191, 0, 0 }, { 192, 0, 0 },{ 192, 0, 0 },{ 193, 0, 0 },{ 194, 0, 0 },{ 194, 0, 0 }, { 195, 0, 0 },{ 196, 0, 0 },{ 196, 0, 0 },{ 197, 0, 0 },{ 198, 0, 0 }, { 198, 0, 0 },{ 199, 0, 0 },{ 200, 0, 0 },{ 200, 0, 0 },{ 201, 0, 0 }, { 202, 0, 0 },{ 202, 0, 0 },{ 203, 0, 0 },{ 204, 0, 0 },{ 204, 0, 0 }, { 205, 0, 0 },{ 206, 0, 0 },{ 206, 0, 0 },{ 207, 0, 0 },{ 208, 0, 0 }, { 208, 0, 0 },{ 209, 0, 0 },{ 210, 0, 0 },{ 210, 0, 0 },{ 211, 0, 0 }, { 212, 0, 0 },{ 212, 0, 0 },{ 213, 0, 0 },{ 214, 0, 0 },{ 214, 0, 0 }, { 215, 0, 0 },{ 216, 0, 0 },{ 216, 0, 0 },{ 217, 0, 0 },{ 218, 0, 0 }, { 218, 0, 0 },{ 219, 0, 0 },{ 220, 0, 0 },{ 220, 0, 0 },{ 221, 0, 0 }, { 222, 0, 0 },{ 222, 0, 0 },{ 223, 0, 0 },{ 224, 0, 0 },{ 224, 0, 0 }, { 225, 0, 0 },{ 226, 0, 0 },{ 226, 0, 0 },{ 227, 0, 0 },{ 228, 0, 0 }, { 228, 0, 0 },{ 229, 0, 0 },{ 230, 0, 0 },{ 230, 0, 0 },{ 231, 0, 0 }, { 232, 0, 0 },{ 232, 0, 0 },{ 233, 0, 0 },{ 234, 0, 0 },{ 234, 0, 0 }, { 235, 0, 0 },{ 236, 0, 0 },{ 236, 0, 0 },{ 237, 0, 0 },{ 238, 0, 0 }, { 238, 0, 0 },{ 239, 0, 0 },{ 240, 0, 0 },{ 240, 0, 0 },{ 241, 0, 0 }, { 242, 0, 0 },{ 242, 0, 0 },{ 243, 0, 0 },{ 244, 0, 0 },{ 244, 0, 0 }, { 245, 0, 0 },{ 246, 0, 0 },{ 246, 0, 0 },{ 247, 0, 0 },{ 248, 0, 0 }, { 248, 0, 0 },{ 249, 0, 0 },{ 250, 0, 0 },{ 251, 0, 0 },{ 251, 0, 0 }, { 252, 0, 0 },{ 253, 0, 0 },{ 253, 0, 0 },{ 254, 0, 0 },{ 255, 0, 0 }, { 255, 0, 0 },{ 255, 1, 0 },{ 255, 2, 0 },{ 255, 2, 0 },{ 255, 3, 0 }, { 255, 4, 0 },{ 255, 4, 0 },{ 255, 5, 0 },{ 255, 6, 0 },{ 255, 6, 0 }, { 255, 7, 0 },{ 255, 8, 0 },{ 255, 8, 0 },{ 255, 9, 0 },{ 255, 10, 0 }, { 255, 10, 0 },{ 255, 11, 0 },{ 255, 12, 0 },{ 255, 12, 0 },{ 255, 13, 0 }, { 255, 14, 0 },{ 255, 14, 0 },{ 255, 15, 0 },{ 255, 16, 0 },{ 255, 16, 0 }, { 255, 17, 0 },{ 255, 18, 0 },{ 255, 18, 0 },{ 255, 19, 0 },{ 255, 20, 0 }, { 255, 20, 0 },{ 255, 21, 0 },{ 255, 22, 0 },{ 255, 22, 0 },{ 255, 23, 0 }, { 255, 24, 0 },{ 255, 24, 0 },{ 255, 25, 0 },{ 255, 26, 0 },{ 255, 26, 0 }, { 255, 27, 0 },{ 255, 28, 0 },{ 255, 28, 0 },{ 255, 29, 0 },{ 255, 30, 0 }, { 255, 30, 0 },{ 255, 31, 0 },{ 255, 32, 0 },{ 255, 32, 0 },{ 255, 33, 0 }, { 255, 34, 0 },{ 255, 34, 0 },{ 255, 35, 0 },{ 255, 36, 0 },{ 255, 36, 0 }, { 255, 37, 0 },{ 255, 38, 0 },{ 255, 38, 0 },{ 255, 39, 0 },{ 255, 40, 0 }, { 255, 40, 0 },{ 255, 41, 0 },{ 255, 42, 0 },{ 255, 42, 0 },{ 255, 43, 0 }, { 255, 44, 0 },{ 255, 44, 0 },{ 255, 45, 0 },{ 255, 46, 0 },{ 255, 46, 0 }, { 255, 47, 0 },{ 255, 48, 0 },{ 255, 48, 0 },{ 255, 49, 0 },{ 255, 50, 0 }, { 255, 50, 0 },{ 255, 51, 0 },{ 255, 52, 0 },{ 255, 52, 0 },{ 255, 53, 0 }, { 255, 54, 0 },{ 255, 54, 0 },{ 255, 55, 0 },{ 255, 56, 0 },{ 255, 56, 0 }, { 255, 57, 0 },{ 255, 58, 0 },{ 255, 58, 0 },{ 255, 59, 0 },{ 255, 60, 0 }, { 255, 60, 0 },{ 255, 61, 0 },{ 255, 62, 0 },{ 255, 63, 0 },{ 255, 63, 0 }, { 255, 64, 0 },{ 255, 65, 0 },{ 255, 65, 0 },{ 255, 66, 0 },{ 255, 67, 0 }, { 255, 67, 0 },{ 255, 68, 0 },{ 255, 69, 0 },{ 255, 69, 0 },{ 255, 70, 0 }, { 255, 71, 0 },{ 255, 71, 0 },{ 255, 72, 0 },{ 255, 73, 0 },{ 255, 73, 0 }, { 255, 74, 0 },{ 255, 75, 0 },{ 255, 75, 0 },{ 255, 76, 0 },{ 255, 77, 0 }, { 255, 77, 0 },{ 255, 78, 0 },{ 255, 79, 0 },{ 255, 79, 0 },{ 255, 80, 0 }, { 255, 81, 0 },{ 255, 81, 0 },{ 255, 82, 0 },{ 255, 83, 0 },{ 255, 83, 0 }, { 255, 84, 0 },{ 255, 85, 0 },{ 255, 85, 0 },{ 255, 86, 0 },{ 255, 87, 0 }, { 255, 87, 0 },{ 255, 88, 0 },{ 255, 89, 0 },{ 255, 89, 0 },{ 255, 90, 0 }, { 255, 91, 0 },{ 255, 91, 0 },{ 255, 92, 0 },{ 255, 93, 0 },{ 255, 93, 0 }, { 255, 94, 0 },{ 255, 95, 0 },{ 255, 95, 0 },{ 255, 96, 0 },{ 255, 97, 0 }, { 255, 97, 0 },{ 255, 98, 0 },{ 255, 99, 0 },{ 255, 99, 0 },{ 255, 100, 0 }, { 255, 101, 0 },{ 255, 101, 0 },{ 255, 102, 0 },{ 255, 103, 0 },{ 255, 103, 0 }, { 255, 104, 0 },{ 255, 105, 0 },{ 255, 105, 0 },{ 255, 106, 0 },{ 255, 107, 0 }, { 255, 107, 0 },{ 255, 108, 0 },{ 255, 109, 0 },{ 255, 109, 0 },{ 255, 110, 0 }, { 255, 111, 0 },{ 255, 111, 0 },{ 255, 112, 0 },{ 255, 113, 0 },{ 255, 113, 0 }, { 255, 114, 0 },{ 255, 115, 0 },{ 255, 115, 0 },{ 255, 116, 0 },{ 255, 117, 0 }, { 255, 117, 0 },{ 255, 118, 0 },{ 255, 119, 0 },{ 255, 119, 0 },{ 255, 120, 0 }, { 255, 121, 0 },{ 255, 121, 0 },{ 255, 122, 0 },{ 255, 123, 0 },{ 255, 123, 0 }, { 255, 124, 0 },{ 255, 125, 0 },{ 255, 125, 0 },{ 255, 126, 0 },{ 255, 127, 0 }, { 255, 128, 0 },{ 255, 128, 0 },{ 255, 129, 0 },{ 255, 130, 0 },{ 255, 130, 0 }, { 255, 131, 0 },{ 255, 132, 0 },{ 255, 132, 0 },{ 255, 133, 0 },{ 255, 134, 0 }, { 255, 134, 0 },{ 255, 135, 0 },{ 255, 136, 0 },{ 255, 136, 0 },{ 255, 137, 0 }, { 255, 138, 0 },{ 255, 138, 0 },{ 255, 139, 0 },{ 255, 140, 0 },{ 255, 140, 0 }, { 255, 141, 0 },{ 255, 142, 0 },{ 255, 142, 0 },{ 255, 143, 0 },{ 255, 144, 0 }, { 255, 144, 0 },{ 255, 145, 0 },{ 255, 146, 0 },{ 255, 146, 0 },{ 255, 147, 0 }, { 255, 148, 0 },{ 255, 148, 0 },{ 255, 149, 0 },{ 255, 150, 0 },{ 255, 150, 0 }, { 255, 151, 0 },{ 255, 152, 0 },{ 255, 152, 0 },{ 255, 153, 0 },{ 255, 154, 0 }, { 255, 154, 0 },{ 255, 155, 0 },{ 255, 156, 0 },{ 255, 156, 0 },{ 255, 157, 0 }, { 255, 158, 0 },{ 255, 158, 0 },{ 255, 159, 0 },{ 255, 160, 0 },{ 255, 160, 0 }, { 255, 161, 0 },{ 255, 162, 0 },{ 255, 162, 0 },{ 255, 163, 0 },{ 255, 164, 0 }, { 255, 164, 0 },{ 255, 165, 0 },{ 255, 166, 0 },{ 255, 166, 0 },{ 255, 167, 0 }, { 255, 168, 0 },{ 255, 168, 0 },{ 255, 169, 0 },{ 255, 170, 0 },{ 255, 170, 0 }, { 255, 171, 0 },{ 255, 172, 0 },{ 255, 172, 0 },{ 255, 173, 0 },{ 255, 174, 0 }, { 255, 174, 0 },{ 255, 175, 0 },{ 255, 176, 0 },{ 255, 176, 0 },{ 255, 177, 0 }, { 255, 178, 0 },{ 255, 178, 0 },{ 255, 179, 0 },{ 255, 180, 0 },{ 255, 180, 0 }, { 255, 181, 0 },{ 255, 182, 0 },{ 255, 182, 0 },{ 255, 183, 0 },{ 255, 184, 0 }, { 255, 184, 0 },{ 255, 185, 0 },{ 255, 186, 0 },{ 255, 186, 0 },{ 255, 187, 0 }, { 255, 188, 0 },{ 255, 188, 0 },{ 255, 189, 0 },{ 255, 190, 0 },{ 255, 190, 0 }, { 255, 191, 0 },{ 255, 192, 0 },{ 255, 192, 0 },{ 255, 193, 0 },{ 255, 194, 0 }, { 255, 195, 0 },{ 255, 195, 0 },{ 255, 196, 0 },{ 255, 197, 0 },{ 255, 197, 0 }, { 255, 198, 0 },{ 255, 199, 0 },{ 255, 199, 0 },{ 255, 200, 0 },{ 255, 201, 0 }, { 255, 201, 0 },{ 255, 202, 0 },{ 255, 203, 0 },{ 255, 203, 0 },{ 255, 204, 0 }, { 255, 205, 0 },{ 255, 205, 0 },{ 255, 206, 0 },{ 255, 207, 0 },{ 255, 207, 0 }, { 255, 208, 0 },{ 255, 209, 0 },{ 255, 209, 0 },{ 255, 210, 0 },{ 255, 211, 0 }, { 255, 211, 0 },{ 255, 212, 0 },{ 255, 213, 0 },{ 255, 213, 0 },{ 255, 214, 0 }, { 255, 215, 0 },{ 255, 215, 0 },{ 255, 216, 0 },{ 255, 217, 0 },{ 255, 217, 0 }, { 255, 218, 0 },{ 255, 219, 0 },{ 255, 219, 0 },{ 255, 220, 0 },{ 255, 221, 0 }, { 255, 221, 0 },{ 255, 222, 0 },{ 255, 223, 0 },{ 255, 223, 0 },{ 255, 224, 0 }, { 255, 225, 0 },{ 255, 225, 0 },{ 255, 226, 0 },{ 255, 227, 0 },{ 255, 227, 0 }, { 255, 228, 0 },{ 255, 229, 0 },{ 255, 229, 0 },{ 255, 230, 0 },{ 255, 231, 0 }, { 255, 231, 0 },{ 255, 232, 0 },{ 255, 233, 0 },{ 255, 233, 0 },{ 255, 234, 0 }, { 255, 235, 0 },{ 255, 235, 0 },{ 255, 236, 0 },{ 255, 237, 0 },{ 255, 237, 0 }, { 255, 238, 0 },{ 255, 239, 0 },{ 255, 239, 0 },{ 255, 240, 0 },{ 255, 241, 0 }, { 255, 241, 0 },{ 255, 242, 0 },{ 255, 243, 0 },{ 255, 243, 0 },{ 255, 244, 0 }, { 255, 245, 0 },{ 255, 245, 0 },{ 255, 246, 0 },{ 255, 247, 0 },{ 255, 247, 0 }, { 255, 248, 0 },{ 255, 249, 0 },{ 255, 249, 0 },{ 255, 250, 0 },{ 255, 251, 0 }, { 255, 251, 0 },{ 255, 252, 0 },{ 255, 253, 0 },{ 255, 253, 0 },{ 255, 254, 0 }, { 255, 255, 0 },{ 255, 255, 1 },{ 255, 255, 2 },{ 255, 255, 3 },{ 255, 255, 4 }, { 255, 255, 5 },{ 255, 255, 6 },{ 255, 255, 7 },{ 255, 255, 8 },{ 255, 255, 9 }, { 255, 255, 10 },{ 255, 255, 11 },{ 255, 255, 12 },{ 255, 255, 13 },{ 255, 255, 14 }, { 255, 255, 15 },{ 255, 255, 16 },{ 255, 255, 17 },{ 255, 255, 18 },{ 255, 255, 19 }, { 255, 255, 20 },{ 255, 255, 21 },{ 255, 255, 22 },{ 255, 255, 23 },{ 255, 255, 24 }, { 255, 255, 25 },{ 255, 255, 26 },{ 255, 255, 27 },{ 255, 255, 28 },{ 255, 255, 29 }, { 255, 255, 30 },{ 255, 255, 31 },{ 255, 255, 32 },{ 255, 255, 33 },{ 255, 255, 34 }, { 255, 255, 35 },{ 255, 255, 36 },{ 255, 255, 37 },{ 255, 255, 38 },{ 255, 255, 39 }, { 255, 255, 40 },{ 255, 255, 41 },{ 255, 255, 42 },{ 255, 255, 43 },{ 255, 255, 44 }, { 255, 255, 45 },{ 255, 255, 46 },{ 255, 255, 47 },{ 255, 255, 48 },{ 255, 255, 49 }, { 255, 255, 50 },{ 255, 255, 51 },{ 255, 255, 52 },{ 255, 255, 53 },{ 255, 255, 54 }, { 255, 255, 55 },{ 255, 255, 56 },{ 255, 255, 57 },{ 255, 255, 58 },{ 255, 255, 59 }, { 255, 255, 60 },{ 255, 255, 61 },{ 255, 255, 62 },{ 255, 255, 63 },{ 255, 255, 64 }, { 255, 255, 65 },{ 255, 255, 66 },{ 255, 255, 67 },{ 255, 255, 68 },{ 255, 255, 69 }, { 255, 255, 70 },{ 255, 255, 71 },{ 255, 255, 72 },{ 255, 255, 73 },{ 255, 255, 74 }, { 255, 255, 75 },{ 255, 255, 76 },{ 255, 255, 77 },{ 255, 255, 78 },{ 255, 255, 79 }, { 255, 255, 80 },{ 255, 255, 81 },{ 255, 255, 82 },{ 255, 255, 83 },{ 255, 255, 84 }, { 255, 255, 85 },{ 255, 255, 86 },{ 255, 255, 87 },{ 255, 255, 88 },{ 255, 255, 89 }, { 255, 255, 90 },{ 255, 255, 91 },{ 255, 255, 92 },{ 255, 255, 93 },{ 255, 255, 94 }, { 255, 255, 95 },{ 255, 255, 96 },{ 255, 255, 97 },{ 255, 255, 98 },{ 255, 255, 99 }, { 255, 255, 100 },{ 255, 255, 101 },{ 255, 255, 102 },{ 255, 255, 103 },{ 255, 255, 104 }, { 255, 255, 105 },{ 255, 255, 106 },{ 255, 255, 107 },{ 255, 255, 108 },{ 255, 255, 109 }, { 255, 255, 110 },{ 255, 255, 111 },{ 255, 255, 112 },{ 255, 255, 113 },{ 255, 255, 114 }, { 255, 255, 115 },{ 255, 255, 116 },{ 255, 255, 117 },{ 255, 255, 118 },{ 255, 255, 119 }, { 255, 255, 120 },{ 255, 255, 121 },{ 255, 255, 122 },{ 255, 255, 123 },{ 255, 255, 124 }, { 255, 255, 125 },{ 255, 255, 126 },{ 255, 255, 127 },{ 255, 255, 128 },{ 255, 255, 129 }, { 255, 255, 130 },{ 255, 255, 131 },{ 255, 255, 132 },{ 255, 255, 133 },{ 255, 255, 134 }, { 255, 255, 135 },{ 255, 255, 136 },{ 255, 255, 137 },{ 255, 255, 138 },{ 255, 255, 139 }, { 255, 255, 140 },{ 255, 255, 141 },{ 255, 255, 142 },{ 255, 255, 143 },{ 255, 255, 144 }, { 255, 255, 145 },{ 255, 255, 146 },{ 255, 255, 147 },{ 255, 255, 148 },{ 255, 255, 149 }, { 255, 255, 150 },{ 255, 255, 151 },{ 255, 255, 152 },{ 255, 255, 153 },{ 255, 255, 154 }, { 255, 255, 155 },{ 255, 255, 157 },{ 255, 255, 158 },{ 255, 255, 159 },{ 255, 255, 160 }, { 255, 255, 161 },{ 255, 255, 162 },{ 255, 255, 163 },{ 255, 255, 164 },{ 255, 255, 165 }, { 255, 255, 166 },{ 255, 255, 167 },{ 255, 255, 168 },{ 255, 255, 169 },{ 255, 255, 170 }, { 255, 255, 171 },{ 255, 255, 172 },{ 255, 255, 173 },{ 255, 255, 174 },{ 255, 255, 175 }, { 255, 255, 176 },{ 255, 255, 177 },{ 255, 255, 178 },{ 255, 255, 179 },{ 255, 255, 180 }, { 255, 255, 181 },{ 255, 255, 182 },{ 255, 255, 183 },{ 255, 255, 184 },{ 255, 255, 185 }, { 255, 255, 186 },{ 255, 255, 187 },{ 255, 255, 188 },{ 255, 255, 189 },{ 255, 255, 190 }, { 255, 255, 191 },{ 255, 255, 192 },{ 255, 255, 193 },{ 255, 255, 194 },{ 255, 255, 195 }, { 255, 255, 196 },{ 255, 255, 197 },{ 255, 255, 198 },{ 255, 255, 199 },{ 255, 255, 200 }, { 255, 255, 201 },{ 255, 255, 202 },{ 255, 255, 203 },{ 255, 255, 204 },{ 255, 255, 205 }, { 255, 255, 206 },{ 255, 255, 207 },{ 255, 255, 208 },{ 255, 255, 209 },{ 255, 255, 210 }, { 255, 255, 211 },{ 255, 255, 212 },{ 255, 255, 213 },{ 255, 255, 214 },{ 255, 255, 215 }, { 255, 255, 216 },{ 255, 255, 217 },{ 255, 255, 218 },{ 255, 255, 219 },{ 255, 255, 220 }, { 255, 255, 221 },{ 255, 255, 222 },{ 255, 255, 223 },{ 255, 255, 224 },{ 255, 255, 225 }, { 255, 255, 226 },{ 255, 255, 227 },{ 255, 255, 228 },{ 255, 255, 229 },{ 255, 255, 230 }, { 255, 255, 231 },{ 255, 255, 232 },{ 255, 255, 233 },{ 255, 255, 234 },{ 255, 255, 235 }, { 255, 255, 236 },{ 255, 255, 237 },{ 255, 255, 238 },{ 255, 255, 239 },{ 255, 255, 240 }, { 255, 255, 241 },{ 255, 255, 242 },{ 255, 255, 243 },{ 255, 255, 244 },{ 255, 255, 245 }, { 255, 255, 246 },{ 255, 255, 247 },{ 255, 255, 248 },{ 255, 255, 249 },{ 255, 255, 250 }, { 255, 255, 251 },{ 255, 255, 252 },{ 255, 255, 253 },{ 255, 255, 254 },{ 255, 255, 255 } }; const rgb_t hsv_colormap[1000] = { { 255, 0, 0 },{ 255, 2, 0 },{ 255, 3, 0 },{ 255, 5, 0 },{ 255, 6, 0 }, { 255, 8, 0 },{ 255, 9, 0 },{ 255, 11, 0 },{ 255, 12, 0 },{ 255, 14, 0 }, { 255, 15, 0 },{ 255, 17, 0 },{ 255, 18, 0 },{ 255, 20, 0 },{ 255, 21, 0 }, { 255, 23, 0 },{ 255, 24, 0 },{ 255, 26, 0 },{ 255, 27, 0 },{ 255, 29, 0 }, { 255, 30, 0 },{ 255, 32, 0 },{ 255, 33, 0 },{ 255, 35, 0 },{ 255, 36, 0 }, { 255, 38, 0 },{ 255, 39, 0 },{ 255, 41, 0 },{ 255, 42, 0 },{ 255, 44, 0 }, { 255, 45, 0 },{ 255, 47, 0 },{ 255, 48, 0 },{ 255, 50, 0 },{ 255, 51, 0 }, { 255, 53, 0 },{ 255, 54, 0 },{ 255, 56, 0 },{ 255, 57, 0 },{ 255, 59, 0 }, { 255, 60, 0 },{ 255, 62, 0 },{ 255, 63, 0 },{ 255, 65, 0 },{ 255, 66, 0 }, { 255, 68, 0 },{ 255, 69, 0 },{ 255, 71, 0 },{ 255, 72, 0 },{ 255, 74, 0 }, { 255, 75, 0 },{ 255, 77, 0 },{ 255, 78, 0 },{ 255, 80, 0 },{ 255, 81, 0 }, { 255, 83, 0 },{ 255, 84, 0 },{ 255, 86, 0 },{ 255, 87, 0 },{ 255, 89, 0 }, { 255, 90, 0 },{ 255, 92, 0 },{ 255, 93, 0 },{ 255, 95, 0 },{ 255, 96, 0 }, { 255, 98, 0 },{ 255, 100, 0 },{ 255, 101, 0 },{ 255, 103, 0 },{ 255, 104, 0 }, { 255, 106, 0 },{ 255, 107, 0 },{ 255, 109, 0 },{ 255, 110, 0 },{ 255, 112, 0 }, { 255, 113, 0 },{ 255, 115, 0 },{ 255, 116, 0 },{ 255, 118, 0 },{ 255, 119, 0 }, { 255, 121, 0 },{ 255, 122, 0 },{ 255, 124, 0 },{ 255, 125, 0 },{ 255, 127, 0 }, { 255, 128, 0 },{ 255, 130, 0 },{ 255, 131, 0 },{ 255, 133, 0 },{ 255, 134, 0 }, { 255, 136, 0 },{ 255, 137, 0 },{ 255, 139, 0 },{ 255, 140, 0 },{ 255, 142, 0 }, { 255, 143, 0 },{ 255, 145, 0 },{ 255, 146, 0 },{ 255, 148, 0 },{ 255, 149, 0 }, { 255, 151, 0 },{ 255, 152, 0 },{ 255, 154, 0 },{ 255, 155, 0 },{ 255, 157, 0 }, { 255, 158, 0 },{ 255, 160, 0 },{ 255, 161, 0 },{ 255, 163, 0 },{ 255, 164, 0 }, { 255, 166, 0 },{ 255, 167, 0 },{ 255, 169, 0 },{ 255, 170, 0 },{ 255, 172, 0 }, { 255, 173, 0 },{ 255, 175, 0 },{ 255, 176, 0 },{ 255, 178, 0 },{ 255, 179, 0 }, { 255, 181, 0 },{ 255, 182, 0 },{ 255, 184, 0 },{ 255, 185, 0 },{ 255, 187, 0 }, { 255, 188, 0 },{ 255, 190, 0 },{ 255, 191, 0 },{ 255, 193, 0 },{ 255, 194, 0 }, { 255, 196, 0 },{ 255, 197, 0 },{ 255, 199, 0 },{ 255, 201, 0 },{ 255, 202, 0 }, { 255, 204, 0 },{ 255, 205, 0 },{ 255, 207, 0 },{ 255, 208, 0 },{ 255, 210, 0 }, { 255, 211, 0 },{ 255, 213, 0 },{ 255, 214, 0 },{ 255, 216, 0 },{ 255, 217, 0 }, { 255, 219, 0 },{ 255, 220, 0 },{ 255, 222, 0 },{ 255, 223, 0 },{ 255, 225, 0 }, { 255, 226, 0 },{ 255, 228, 0 },{ 255, 229, 0 },{ 255, 231, 0 },{ 255, 232, 0 }, { 255, 234, 0 },{ 255, 235, 0 },{ 255, 237, 0 },{ 255, 238, 0 },{ 255, 239, 0 }, { 254, 240, 0 },{ 254, 242, 0 },{ 253, 243, 0 },{ 253, 244, 0 },{ 252, 245, 0 }, { 252, 246, 0 },{ 251, 247, 0 },{ 251, 248, 0 },{ 250, 249, 0 },{ 250, 250, 0 }, { 249, 251, 0 },{ 249, 252, 0 },{ 248, 253, 0 },{ 248, 254, 0 },{ 247, 255, 0 }, { 246, 255, 0 },{ 245, 255, 0 },{ 243, 255, 0 },{ 242, 255, 0 },{ 240, 255, 0 }, { 239, 255, 0 },{ 237, 255, 0 },{ 236, 255, 0 },{ 234, 255, 0 },{ 233, 255, 0 }, { 231, 255, 0 },{ 230, 255, 0 },{ 228, 255, 0 },{ 227, 255, 0 },{ 225, 255, 0 }, { 224, 255, 0 },{ 222, 255, 0 },{ 221, 255, 0 },{ 219, 255, 0 },{ 218, 255, 0 }, { 216, 255, 0 },{ 215, 255, 0 },{ 213, 255, 0 },{ 211, 255, 0 },{ 210, 255, 0 }, { 208, 255, 0 },{ 207, 255, 0 },{ 205, 255, 0 },{ 204, 255, 0 },{ 202, 255, 0 }, { 201, 255, 0 },{ 199, 255, 0 },{ 198, 255, 0 },{ 196, 255, 0 },{ 195, 255, 0 }, { 193, 255, 0 },{ 192, 255, 0 },{ 190, 255, 0 },{ 189, 255, 0 },{ 187, 255, 0 }, { 186, 255, 0 },{ 184, 255, 0 },{ 183, 255, 0 },{ 181, 255, 0 },{ 180, 255, 0 }, { 178, 255, 0 },{ 177, 255, 0 },{ 175, 255, 0 },{ 174, 255, 0 },{ 172, 255, 0 }, { 171, 255, 0 },{ 169, 255, 0 },{ 168, 255, 0 },{ 166, 255, 0 },{ 165, 255, 0 }, { 163, 255, 0 },{ 162, 255, 0 },{ 160, 255, 0 },{ 159, 255, 0 },{ 157, 255, 0 }, { 156, 255, 0 },{ 154, 255, 0 },{ 153, 255, 0 },{ 151, 255, 0 },{ 150, 255, 0 }, { 148, 255, 0 },{ 147, 255, 0 },{ 145, 255, 0 },{ 144, 255, 0 },{ 142, 255, 0 }, { 141, 255, 0 },{ 139, 255, 0 },{ 138, 255, 0 },{ 136, 255, 0 },{ 135, 255, 0 }, { 133, 255, 0 },{ 132, 255, 0 },{ 130, 255, 0 },{ 129, 255, 0 },{ 127, 255, 0 }, { 126, 255, 0 },{ 124, 255, 0 },{ 123, 255, 0 },{ 121, 255, 0 },{ 120, 255, 0 }, { 118, 255, 0 },{ 117, 255, 0 },{ 115, 255, 0 },{ 114, 255, 0 },{ 112, 255, 0 }, { 110, 255, 0 },{ 109, 255, 0 },{ 107, 255, 0 },{ 106, 255, 0 },{ 104, 255, 0 }, { 103, 255, 0 },{ 101, 255, 0 },{ 100, 255, 0 },{ 98, 255, 0 },{ 97, 255, 0 }, { 95, 255, 0 },{ 94, 255, 0 },{ 92, 255, 0 },{ 91, 255, 0 },{ 89, 255, 0 }, { 88, 255, 0 },{ 86, 255, 0 },{ 85, 255, 0 },{ 83, 255, 0 },{ 82, 255, 0 }, { 80, 255, 0 },{ 79, 255, 0 },{ 77, 255, 0 },{ 76, 255, 0 },{ 74, 255, 0 }, { 73, 255, 0 },{ 71, 255, 0 },{ 70, 255, 0 },{ 68, 255, 0 },{ 67, 255, 0 }, { 65, 255, 0 },{ 64, 255, 0 },{ 62, 255, 0 },{ 61, 255, 0 },{ 59, 255, 0 }, { 58, 255, 0 },{ 56, 255, 0 },{ 55, 255, 0 },{ 53, 255, 0 },{ 52, 255, 0 }, { 50, 255, 0 },{ 49, 255, 0 },{ 47, 255, 0 },{ 46, 255, 0 },{ 44, 255, 0 }, { 43, 255, 0 },{ 41, 255, 0 },{ 40, 255, 0 },{ 38, 255, 0 },{ 37, 255, 0 }, { 35, 255, 0 },{ 34, 255, 0 },{ 32, 255, 0 },{ 31, 255, 0 },{ 29, 255, 0 }, { 28, 255, 0 },{ 26, 255, 0 },{ 25, 255, 0 },{ 23, 255, 0 },{ 22, 255, 0 }, { 20, 255, 0 },{ 19, 255, 0 },{ 17, 255, 0 },{ 16, 255, 0 },{ 14, 255, 0 }, { 12, 255, 0 },{ 11, 255, 0 },{ 9, 255, 0 },{ 8, 255, 0 },{ 7, 255, 1 }, { 7, 255, 2 },{ 6, 255, 3 },{ 6, 255, 4 },{ 5, 255, 5 },{ 5, 255, 6 }, { 4, 255, 7 },{ 4, 255, 8 },{ 3, 255, 9 },{ 3, 255, 10 },{ 2, 255, 11 }, { 2, 255, 12 },{ 1, 255, 13 },{ 1, 255, 14 },{ 0, 255, 15 },{ 0, 255, 16 }, { 0, 255, 18 },{ 0, 255, 19 },{ 0, 255, 21 },{ 0, 255, 22 },{ 0, 255, 24 }, { 0, 255, 25 },{ 0, 255, 27 },{ 0, 255, 28 },{ 0, 255, 30 },{ 0, 255, 31 }, { 0, 255, 33 },{ 0, 255, 34 },{ 0, 255, 36 },{ 0, 255, 37 },{ 0, 255, 39 }, { 0, 255, 40 },{ 0, 255, 42 },{ 0, 255, 43 },{ 0, 255, 45 },{ 0, 255, 46 }, { 0, 255, 48 },{ 0, 255, 49 },{ 0, 255, 51 },{ 0, 255, 52 },{ 0, 255, 54 }, { 0, 255, 55 },{ 0, 255, 57 },{ 0, 255, 58 },{ 0, 255, 60 },{ 0, 255, 61 }, { 0, 255, 63 },{ 0, 255, 64 },{ 0, 255, 66 },{ 0, 255, 67 },{ 0, 255, 69 }, { 0, 255, 70 },{ 0, 255, 72 },{ 0, 255, 73 },{ 0, 255, 75 },{ 0, 255, 76 }, { 0, 255, 78 },{ 0, 255, 79 },{ 0, 255, 81 },{ 0, 255, 82 },{ 0, 255, 84 }, { 0, 255, 86 },{ 0, 255, 87 },{ 0, 255, 89 },{ 0, 255, 90 },{ 0, 255, 92 }, { 0, 255, 93 },{ 0, 255, 95 },{ 0, 255, 96 },{ 0, 255, 98 },{ 0, 255, 99 }, { 0, 255, 101 },{ 0, 255, 102 },{ 0, 255, 104 },{ 0, 255, 105 },{ 0, 255, 107 }, { 0, 255, 108 },{ 0, 255, 110 },{ 0, 255, 111 },{ 0, 255, 113 },{ 0, 255, 114 }, { 0, 255, 116 },{ 0, 255, 117 },{ 0, 255, 119 },{ 0, 255, 120 },{ 0, 255, 122 }, { 0, 255, 123 },{ 0, 255, 125 },{ 0, 255, 126 },{ 0, 255, 128 },{ 0, 255, 129 }, { 0, 255, 131 },{ 0, 255, 132 },{ 0, 255, 134 },{ 0, 255, 135 },{ 0, 255, 137 }, { 0, 255, 138 },{ 0, 255, 140 },{ 0, 255, 141 },{ 0, 255, 143 },{ 0, 255, 144 }, { 0, 255, 146 },{ 0, 255, 147 },{ 0, 255, 149 },{ 0, 255, 150 },{ 0, 255, 152 }, { 0, 255, 153 },{ 0, 255, 155 },{ 0, 255, 156 },{ 0, 255, 158 },{ 0, 255, 159 }, { 0, 255, 161 },{ 0, 255, 162 },{ 0, 255, 164 },{ 0, 255, 165 },{ 0, 255, 167 }, { 0, 255, 168 },{ 0, 255, 170 },{ 0, 255, 171 },{ 0, 255, 173 },{ 0, 255, 174 }, { 0, 255, 176 },{ 0, 255, 177 },{ 0, 255, 179 },{ 0, 255, 180 },{ 0, 255, 182 }, { 0, 255, 183 },{ 0, 255, 185 },{ 0, 255, 187 },{ 0, 255, 188 },{ 0, 255, 190 }, { 0, 255, 191 },{ 0, 255, 193 },{ 0, 255, 194 },{ 0, 255, 196 },{ 0, 255, 197 }, { 0, 255, 199 },{ 0, 255, 200 },{ 0, 255, 202 },{ 0, 255, 203 },{ 0, 255, 205 }, { 0, 255, 206 },{ 0, 255, 208 },{ 0, 255, 209 },{ 0, 255, 211 },{ 0, 255, 212 }, { 0, 255, 214 },{ 0, 255, 215 },{ 0, 255, 217 },{ 0, 255, 218 },{ 0, 255, 220 }, { 0, 255, 221 },{ 0, 255, 223 },{ 0, 255, 224 },{ 0, 255, 226 },{ 0, 255, 227 }, { 0, 255, 229 },{ 0, 255, 230 },{ 0, 255, 232 },{ 0, 255, 233 },{ 0, 255, 235 }, { 0, 255, 236 },{ 0, 255, 238 },{ 0, 255, 239 },{ 0, 255, 241 },{ 0, 255, 242 }, { 0, 255, 244 },{ 0, 255, 245 },{ 0, 255, 247 },{ 0, 255, 248 },{ 0, 255, 250 }, { 0, 255, 251 },{ 0, 255, 253 },{ 0, 255, 254 },{ 0, 254, 255 },{ 0, 253, 255 }, { 0, 251, 255 },{ 0, 250, 255 },{ 0, 248, 255 },{ 0, 247, 255 },{ 0, 245, 255 }, { 0, 244, 255 },{ 0, 242, 255 },{ 0, 241, 255 },{ 0, 239, 255 },{ 0, 238, 255 }, { 0, 236, 255 },{ 0, 235, 255 },{ 0, 233, 255 },{ 0, 232, 255 },{ 0, 230, 255 }, { 0, 229, 255 },{ 0, 227, 255 },{ 0, 225, 255 },{ 0, 224, 255 },{ 0, 222, 255 }, { 0, 221, 255 },{ 0, 219, 255 },{ 0, 218, 255 },{ 0, 216, 255 },{ 0, 215, 255 }, { 0, 213, 255 },{ 0, 212, 255 },{ 0, 210, 255 },{ 0, 209, 255 },{ 0, 207, 255 }, { 0, 206, 255 },{ 0, 204, 255 },{ 0, 203, 255 },{ 0, 201, 255 },{ 0, 200, 255 }, { 0, 198, 255 },{ 0, 197, 255 },{ 0, 195, 255 },{ 0, 194, 255 },{ 0, 192, 255 }, { 0, 191, 255 },{ 0, 189, 255 },{ 0, 188, 255 },{ 0, 186, 255 },{ 0, 185, 255 }, { 0, 183, 255 },{ 0, 182, 255 },{ 0, 180, 255 },{ 0, 179, 255 },{ 0, 177, 255 }, { 0, 176, 255 },{ 0, 174, 255 },{ 0, 173, 255 },{ 0, 171, 255 },{ 0, 170, 255 }, { 0, 168, 255 },{ 0, 167, 255 },{ 0, 165, 255 },{ 0, 164, 255 },{ 0, 162, 255 }, { 0, 161, 255 },{ 0, 159, 255 },{ 0, 158, 255 },{ 0, 156, 255 },{ 0, 155, 255 }, { 0, 153, 255 },{ 0, 152, 255 },{ 0, 150, 255 },{ 0, 149, 255 },{ 0, 147, 255 }, { 0, 146, 255 },{ 0, 144, 255 },{ 0, 143, 255 },{ 0, 141, 255 },{ 0, 140, 255 }, { 0, 138, 255 },{ 0, 137, 255 },{ 0, 135, 255 },{ 0, 134, 255 },{ 0, 132, 255 }, { 0, 131, 255 },{ 0, 129, 255 },{ 0, 128, 255 },{ 0, 126, 255 },{ 0, 124, 255 }, { 0, 123, 255 },{ 0, 121, 255 },{ 0, 120, 255 },{ 0, 118, 255 },{ 0, 117, 255 }, { 0, 115, 255 },{ 0, 114, 255 },{ 0, 112, 255 },{ 0, 111, 255 },{ 0, 109, 255 }, { 0, 108, 255 },{ 0, 106, 255 },{ 0, 105, 255 },{ 0, 103, 255 },{ 0, 102, 255 }, { 0, 100, 255 },{ 0, 99, 255 },{ 0, 97, 255 },{ 0, 96, 255 },{ 0, 94, 255 }, { 0, 93, 255 },{ 0, 91, 255 },{ 0, 90, 255 },{ 0, 88, 255 },{ 0, 87, 255 }, { 0, 85, 255 },{ 0, 84, 255 },{ 0, 82, 255 },{ 0, 81, 255 },{ 0, 79, 255 }, { 0, 78, 255 },{ 0, 76, 255 },{ 0, 75, 255 },{ 0, 73, 255 },{ 0, 72, 255 }, { 0, 70, 255 },{ 0, 69, 255 },{ 0, 67, 255 },{ 0, 66, 255 },{ 0, 64, 255 }, { 0, 63, 255 },{ 0, 61, 255 },{ 0, 60, 255 },{ 0, 58, 255 },{ 0, 57, 255 }, { 0, 55, 255 },{ 0, 54, 255 },{ 0, 52, 255 },{ 0, 51, 255 },{ 0, 49, 255 }, { 0, 48, 255 },{ 0, 46, 255 },{ 0, 45, 255 },{ 0, 43, 255 },{ 0, 42, 255 }, { 0, 40, 255 },{ 0, 39, 255 },{ 0, 37, 255 },{ 0, 36, 255 },{ 0, 34, 255 }, { 0, 33, 255 },{ 0, 31, 255 },{ 0, 30, 255 },{ 0, 28, 255 },{ 0, 26, 255 }, { 0, 25, 255 },{ 0, 23, 255 },{ 0, 22, 255 },{ 0, 20, 255 },{ 0, 19, 255 }, { 0, 17, 255 },{ 0, 16, 255 },{ 1, 15, 255 },{ 1, 14, 255 },{ 2, 13, 255 }, { 2, 12, 255 },{ 3, 11, 255 },{ 3, 10, 255 },{ 4, 9, 255 },{ 4, 8, 255 }, { 5, 7, 255 },{ 5, 6, 255 },{ 6, 5, 255 },{ 6, 4, 255 },{ 7, 3, 255 }, { 7, 2, 255 },{ 8, 1, 255 },{ 8, 0, 255 },{ 10, 0, 255 },{ 11, 0, 255 }, { 13, 0, 255 },{ 14, 0, 255 },{ 16, 0, 255 },{ 17, 0, 255 },{ 19, 0, 255 }, { 20, 0, 255 },{ 22, 0, 255 },{ 23, 0, 255 },{ 25, 0, 255 },{ 26, 0, 255 }, { 28, 0, 255 },{ 29, 0, 255 },{ 31, 0, 255 },{ 32, 0, 255 },{ 34, 0, 255 }, { 35, 0, 255 },{ 37, 0, 255 },{ 38, 0, 255 },{ 40, 0, 255 },{ 41, 0, 255 }, { 43, 0, 255 },{ 44, 0, 255 },{ 46, 0, 255 },{ 47, 0, 255 },{ 49, 0, 255 }, { 50, 0, 255 },{ 52, 0, 255 },{ 53, 0, 255 },{ 55, 0, 255 },{ 56, 0, 255 }, { 58, 0, 255 },{ 59, 0, 255 },{ 61, 0, 255 },{ 62, 0, 255 },{ 64, 0, 255 }, { 65, 0, 255 },{ 67, 0, 255 },{ 68, 0, 255 },{ 70, 0, 255 },{ 72, 0, 255 }, { 73, 0, 255 },{ 75, 0, 255 },{ 76, 0, 255 },{ 78, 0, 255 },{ 79, 0, 255 }, { 81, 0, 255 },{ 82, 0, 255 },{ 84, 0, 255 },{ 85, 0, 255 },{ 87, 0, 255 }, { 88, 0, 255 },{ 90, 0, 255 },{ 91, 0, 255 },{ 93, 0, 255 },{ 94, 0, 255 }, { 96, 0, 255 },{ 97, 0, 255 },{ 99, 0, 255 },{ 100, 0, 255 },{ 102, 0, 255 }, { 103, 0, 255 },{ 105, 0, 255 },{ 106, 0, 255 },{ 108, 0, 255 },{ 109, 0, 255 }, { 111, 0, 255 },{ 112, 0, 255 },{ 114, 0, 255 },{ 115, 0, 255 },{ 117, 0, 255 }, { 118, 0, 255 },{ 120, 0, 255 },{ 121, 0, 255 },{ 123, 0, 255 },{ 124, 0, 255 }, { 126, 0, 255 },{ 127, 0, 255 },{ 129, 0, 255 },{ 130, 0, 255 },{ 132, 0, 255 }, { 133, 0, 255 },{ 135, 0, 255 },{ 136, 0, 255 },{ 138, 0, 255 },{ 139, 0, 255 }, { 141, 0, 255 },{ 142, 0, 255 },{ 144, 0, 255 },{ 145, 0, 255 },{ 147, 0, 255 }, { 148, 0, 255 },{ 150, 0, 255 },{ 151, 0, 255 },{ 153, 0, 255 },{ 154, 0, 255 }, { 156, 0, 255 },{ 157, 0, 255 },{ 159, 0, 255 },{ 160, 0, 255 },{ 162, 0, 255 }, { 163, 0, 255 },{ 165, 0, 255 },{ 166, 0, 255 },{ 168, 0, 255 },{ 169, 0, 255 }, { 171, 0, 255 },{ 173, 0, 255 },{ 174, 0, 255 },{ 176, 0, 255 },{ 177, 0, 255 }, { 179, 0, 255 },{ 180, 0, 255 },{ 182, 0, 255 },{ 183, 0, 255 },{ 185, 0, 255 }, { 186, 0, 255 },{ 188, 0, 255 },{ 189, 0, 255 },{ 191, 0, 255 },{ 192, 0, 255 }, { 194, 0, 255 },{ 195, 0, 255 },{ 197, 0, 255 },{ 198, 0, 255 },{ 200, 0, 255 }, { 201, 0, 255 },{ 203, 0, 255 },{ 204, 0, 255 },{ 206, 0, 255 },{ 207, 0, 255 }, { 209, 0, 255 },{ 210, 0, 255 },{ 212, 0, 255 },{ 213, 0, 255 },{ 215, 0, 255 }, { 216, 0, 255 },{ 218, 0, 255 },{ 219, 0, 255 },{ 221, 0, 255 },{ 222, 0, 255 }, { 224, 0, 255 },{ 225, 0, 255 },{ 227, 0, 255 },{ 228, 0, 255 },{ 230, 0, 255 }, { 231, 0, 255 },{ 233, 0, 255 },{ 234, 0, 255 },{ 236, 0, 255 },{ 237, 0, 255 }, { 239, 0, 255 },{ 240, 0, 255 },{ 242, 0, 255 },{ 243, 0, 255 },{ 245, 0, 255 }, { 246, 0, 255 },{ 247, 0, 254 },{ 248, 0, 253 },{ 248, 0, 252 },{ 249, 0, 251 }, { 249, 0, 250 },{ 250, 0, 249 },{ 250, 0, 248 },{ 251, 0, 247 },{ 251, 0, 246 }, { 252, 0, 245 },{ 252, 0, 244 },{ 253, 0, 243 },{ 253, 0, 242 },{ 254, 0, 241 }, { 254, 0, 240 },{ 255, 0, 239 },{ 255, 0, 238 },{ 255, 0, 236 },{ 255, 0, 235 }, { 255, 0, 233 },{ 255, 0, 232 },{ 255, 0, 230 },{ 255, 0, 229 },{ 255, 0, 227 }, { 255, 0, 226 },{ 255, 0, 224 },{ 255, 0, 223 },{ 255, 0, 221 },{ 255, 0, 220 }, { 255, 0, 218 },{ 255, 0, 217 },{ 255, 0, 215 },{ 255, 0, 214 },{ 255, 0, 212 }, { 255, 0, 211 },{ 255, 0, 209 },{ 255, 0, 208 },{ 255, 0, 206 },{ 255, 0, 205 }, { 255, 0, 203 },{ 255, 0, 202 },{ 255, 0, 200 },{ 255, 0, 199 },{ 255, 0, 197 }, { 255, 0, 196 },{ 255, 0, 194 },{ 255, 0, 193 },{ 255, 0, 191 },{ 255, 0, 190 }, { 255, 0, 188 },{ 255, 0, 187 },{ 255, 0, 185 },{ 255, 0, 184 },{ 255, 0, 182 }, { 255, 0, 181 },{ 255, 0, 179 },{ 255, 0, 178 },{ 255, 0, 176 },{ 255, 0, 175 }, { 255, 0, 173 },{ 255, 0, 172 },{ 255, 0, 170 },{ 255, 0, 169 },{ 255, 0, 167 }, { 255, 0, 166 },{ 255, 0, 164 },{ 255, 0, 163 },{ 255, 0, 161 },{ 255, 0, 160 }, { 255, 0, 158 },{ 255, 0, 157 },{ 255, 0, 155 },{ 255, 0, 154 },{ 255, 0, 152 }, { 255, 0, 151 },{ 255, 0, 149 },{ 255, 0, 148 },{ 255, 0, 146 },{ 255, 0, 145 }, { 255, 0, 143 },{ 255, 0, 141 },{ 255, 0, 140 },{ 255, 0, 138 },{ 255, 0, 137 }, { 255, 0, 135 },{ 255, 0, 134 },{ 255, 0, 132 },{ 255, 0, 131 },{ 255, 0, 129 }, { 255, 0, 128 },{ 255, 0, 126 },{ 255, 0, 125 },{ 255, 0, 123 },{ 255, 0, 122 }, { 255, 0, 120 },{ 255, 0, 119 },{ 255, 0, 117 },{ 255, 0, 116 },{ 255, 0, 114 }, { 255, 0, 113 },{ 255, 0, 111 },{ 255, 0, 110 },{ 255, 0, 108 },{ 255, 0, 107 }, { 255, 0, 105 },{ 255, 0, 104 },{ 255, 0, 102 },{ 255, 0, 101 },{ 255, 0, 99 }, { 255, 0, 98 },{ 255, 0, 96 },{ 255, 0, 95 },{ 255, 0, 93 },{ 255, 0, 92 }, { 255, 0, 90 },{ 255, 0, 89 },{ 255, 0, 87 },{ 255, 0, 86 },{ 255, 0, 84 }, { 255, 0, 83 },{ 255, 0, 81 },{ 255, 0, 80 },{ 255, 0, 78 },{ 255, 0, 77 }, { 255, 0, 75 },{ 255, 0, 74 },{ 255, 0, 72 },{ 255, 0, 71 },{ 255, 0, 69 }, { 255, 0, 68 },{ 255, 0, 66 },{ 255, 0, 65 },{ 255, 0, 63 },{ 255, 0, 62 }, { 255, 0, 60 },{ 255, 0, 59 },{ 255, 0, 57 },{ 255, 0, 56 },{ 255, 0, 54 }, { 255, 0, 53 },{ 255, 0, 51 },{ 255, 0, 50 },{ 255, 0, 48 },{ 255, 0, 47 }, { 255, 0, 45 },{ 255, 0, 44 },{ 255, 0, 42 },{ 255, 0, 40 },{ 255, 0, 39 }, { 255, 0, 37 },{ 255, 0, 36 },{ 255, 0, 34 },{ 255, 0, 33 },{ 255, 0, 31 }, { 255, 0, 30 },{ 255, 0, 28 },{ 255, 0, 27 },{ 255, 0, 25 },{ 255, 0, 24 } }; const rgb_t jet_colormap[1000] = { { 29, 0, 102 },{ 23, 0, 107 },{ 17, 0, 112 },{ 12, 0, 117 },{ 6, 0, 122 }, { 0, 0, 127 },{ 0, 0, 128 },{ 0, 0, 129 },{ 0, 0, 129 },{ 0, 0, 130 }, { 0, 0, 131 },{ 0, 0, 132 },{ 0, 0, 133 },{ 0, 0, 133 },{ 0, 0, 134 }, { 0, 0, 135 },{ 0, 0, 136 },{ 0, 0, 137 },{ 0, 0, 138 },{ 0, 0, 140 }, { 0, 0, 141 },{ 0, 0, 142 },{ 0, 0, 143 },{ 0, 0, 145 },{ 0, 0, 146 }, { 0, 0, 147 },{ 0, 0, 148 },{ 0, 0, 150 },{ 0, 0, 151 },{ 0, 0, 152 }, { 0, 0, 153 },{ 0, 0, 154 },{ 0, 0, 156 },{ 0, 0, 157 },{ 0, 0, 158 }, { 0, 0, 159 },{ 0, 0, 160 },{ 0, 0, 161 },{ 0, 0, 163 },{ 0, 0, 164 }, { 0, 0, 165 },{ 0, 0, 166 },{ 0, 0, 168 },{ 0, 0, 169 },{ 0, 0, 170 }, { 0, 0, 171 },{ 0, 0, 173 },{ 0, 0, 174 },{ 0, 0, 175 },{ 0, 0, 176 }, { 0, 0, 178 },{ 0, 0, 179 },{ 0, 0, 180 },{ 0, 0, 181 },{ 0, 0, 183 }, { 0, 0, 184 },{ 0, 0, 185 },{ 0, 0, 186 },{ 0, 0, 188 },{ 0, 0, 189 }, { 0, 0, 190 },{ 0, 0, 191 },{ 0, 0, 193 },{ 0, 0, 194 },{ 0, 0, 195 }, { 0, 0, 196 },{ 0, 0, 197 },{ 0, 0, 198 },{ 0, 0, 200 },{ 0, 0, 201 }, { 0, 0, 202 },{ 0, 0, 203 },{ 0, 0, 204 },{ 0, 0, 206 },{ 0, 0, 207 }, { 0, 0, 208 },{ 0, 0, 209 },{ 0, 0, 211 },{ 0, 0, 212 },{ 0, 0, 213 }, { 0, 0, 214 },{ 0, 0, 216 },{ 0, 0, 217 },{ 0, 0, 218 },{ 0, 0, 219 }, { 0, 0, 221 },{ 0, 0, 222 },{ 0, 0, 223 },{ 0, 0, 225 },{ 0, 0, 226 }, { 0, 0, 227 },{ 0, 0, 228 },{ 0, 0, 230 },{ 0, 0, 231 },{ 0, 0, 232 }, { 0, 0, 233 },{ 0, 0, 234 },{ 0, 0, 234 },{ 0, 0, 235 },{ 0, 0, 236 }, { 0, 0, 237 },{ 0, 0, 238 },{ 0, 0, 239 },{ 0, 0, 239 },{ 0, 0, 240 }, { 0, 0, 241 },{ 0, 0, 242 },{ 0, 0, 243 },{ 0, 0, 244 },{ 0, 0, 246 }, { 0, 0, 247 },{ 0, 0, 248 },{ 0, 0, 249 },{ 0, 0, 250 },{ 0, 0, 251 }, { 0, 0, 253 },{ 0, 0, 254 },{ 0, 0, 254 },{ 0, 0, 254 },{ 0, 0, 254 }, { 0, 0, 254 },{ 0, 0, 254 },{ 0, 0, 255 },{ 0, 0, 255 },{ 0, 0, 255 }, { 0, 0, 255 },{ 0, 0, 255 },{ 0, 0, 255 },{ 0, 1, 255 },{ 0, 1, 255 }, { 0, 2, 255 },{ 0, 3, 255 },{ 0, 3, 255 },{ 0, 4, 255 },{ 0, 5, 255 }, { 0, 6, 255 },{ 0, 6, 255 },{ 0, 7, 255 },{ 0, 8, 255 },{ 0, 9, 255 }, { 0, 10, 255 },{ 0, 11, 255 },{ 0, 12, 255 },{ 0, 13, 255 },{ 0, 14, 255 }, { 0, 15, 255 },{ 0, 16, 255 },{ 0, 17, 255 },{ 0, 18, 255 },{ 0, 19, 255 }, { 0, 21, 255 },{ 0, 22, 255 },{ 0, 23, 255 },{ 0, 24, 255 },{ 0, 25, 255 }, { 0, 26, 255 },{ 0, 27, 255 },{ 0, 28, 255 },{ 0, 29, 255 },{ 0, 30, 255 }, { 0, 31, 255 },{ 0, 32, 255 },{ 0, 34, 255 },{ 0, 35, 255 },{ 0, 36, 255 }, { 0, 37, 255 },{ 0, 38, 255 },{ 0, 39, 255 },{ 0, 40, 255 },{ 0, 41, 255 }, { 0, 42, 255 },{ 0, 43, 255 },{ 0, 44, 255 },{ 0, 45, 255 },{ 0, 46, 255 }, { 0, 48, 255 },{ 0, 49, 255 },{ 0, 50, 255 },{ 0, 51, 255 },{ 0, 52, 255 }, { 0, 53, 255 },{ 0, 54, 255 },{ 0, 55, 255 },{ 0, 56, 255 },{ 0, 57, 255 }, { 0, 58, 255 },{ 0, 58, 255 },{ 0, 59, 255 },{ 0, 60, 255 },{ 0, 60, 255 }, { 0, 61, 255 },{ 0, 62, 255 },{ 0, 63, 255 },{ 0, 63, 255 },{ 0, 64, 255 }, { 0, 65, 255 },{ 0, 66, 255 },{ 0, 67, 255 },{ 0, 68, 255 },{ 0, 69, 255 }, { 0, 71, 255 },{ 0, 72, 255 },{ 0, 73, 255 },{ 0, 74, 255 },{ 0, 75, 255 }, { 0, 76, 255 },{ 0, 77, 255 },{ 0, 78, 255 },{ 0, 79, 255 },{ 0, 80, 255 }, { 0, 81, 255 },{ 0, 82, 255 },{ 0, 84, 255 },{ 0, 85, 255 },{ 0, 86, 255 }, { 0, 87, 255 },{ 0, 88, 255 },{ 0, 89, 255 },{ 0, 90, 255 },{ 0, 91, 255 }, { 0, 92, 255 },{ 0, 93, 255 },{ 0, 94, 255 },{ 0, 95, 255 },{ 0, 96, 255 }, { 0, 98, 255 },{ 0, 99, 255 },{ 0, 100, 255 },{ 0, 101, 255 },{ 0, 102, 255 }, { 0, 103, 255 },{ 0, 104, 255 },{ 0, 105, 255 },{ 0, 106, 255 },{ 0, 107, 255 }, { 0, 108, 255 },{ 0, 109, 255 },{ 0, 111, 255 },{ 0, 112, 255 },{ 0, 113, 255 }, { 0, 114, 255 },{ 0, 115, 255 },{ 0, 116, 255 },{ 0, 117, 255 },{ 0, 118, 255 }, { 0, 119, 255 },{ 0, 120, 255 },{ 0, 121, 255 },{ 0, 122, 255 },{ 0, 123, 255 }, { 0, 125, 255 },{ 0, 126, 255 },{ 0, 127, 255 },{ 0, 128, 255 },{ 0, 129, 255 }, { 0, 130, 255 },{ 0, 131, 255 },{ 0, 132, 255 },{ 0, 133, 255 },{ 0, 134, 255 }, { 0, 135, 255 },{ 0, 136, 255 },{ 0, 138, 255 },{ 0, 139, 255 },{ 0, 140, 255 }, { 0, 141, 255 },{ 0, 142, 255 },{ 0, 143, 255 },{ 0, 144, 255 },{ 0, 145, 255 }, { 0, 146, 255 },{ 0, 147, 255 },{ 0, 148, 255 },{ 0, 149, 255 },{ 0, 150, 255 }, { 0, 150, 255 },{ 0, 151, 255 },{ 0, 152, 255 },{ 0, 153, 255 },{ 0, 153, 255 }, { 0, 154, 255 },{ 0, 155, 255 },{ 0, 155, 255 },{ 0, 156, 255 },{ 0, 157, 255 }, { 0, 158, 255 },{ 0, 159, 255 },{ 0, 161, 255 },{ 0, 162, 255 },{ 0, 163, 255 }, { 0, 164, 255 },{ 0, 165, 255 },{ 0, 166, 255 },{ 0, 167, 255 },{ 0, 168, 255 }, { 0, 169, 255 },{ 0, 170, 255 },{ 0, 171, 255 },{ 0, 172, 255 },{ 0, 173, 255 }, { 0, 175, 255 },{ 0, 176, 255 },{ 0, 177, 255 },{ 0, 178, 255 },{ 0, 179, 255 }, { 0, 180, 255 },{ 0, 181, 255 },{ 0, 182, 255 },{ 0, 183, 255 },{ 0, 184, 255 }, { 0, 185, 255 },{ 0, 186, 255 },{ 0, 188, 255 },{ 0, 189, 255 },{ 0, 190, 255 }, { 0, 191, 255 },{ 0, 192, 255 },{ 0, 193, 255 },{ 0, 194, 255 },{ 0, 195, 255 }, { 0, 196, 255 },{ 0, 197, 255 },{ 0, 198, 255 },{ 0, 199, 255 },{ 0, 200, 255 }, { 0, 202, 255 },{ 0, 203, 255 },{ 0, 204, 255 },{ 0, 205, 255 },{ 0, 206, 255 }, { 0, 207, 255 },{ 0, 208, 255 },{ 0, 209, 255 },{ 0, 210, 255 },{ 0, 211, 255 }, { 0, 212, 255 },{ 0, 213, 255 },{ 0, 215, 255 },{ 0, 216, 255 },{ 0, 217, 255 }, { 0, 218, 254 },{ 0, 219, 253 },{ 0, 220, 252 },{ 0, 221, 252 },{ 0, 222, 251 }, { 0, 223, 250 },{ 0, 224, 250 },{ 0, 225, 249 },{ 0, 226, 248 },{ 0, 227, 247 }, { 0, 229, 247 },{ 1, 230, 246 },{ 2, 231, 245 },{ 3, 232, 244 },{ 3, 233, 243 }, { 4, 234, 242 },{ 5, 235, 241 },{ 5, 236, 240 },{ 6, 237, 239 },{ 7, 238, 238 }, { 8, 239, 238 },{ 8, 240, 237 },{ 9, 241, 236 },{ 10, 242, 236 },{ 10, 242, 235 }, { 11, 243, 235 },{ 11, 244, 234 },{ 12, 245, 234 },{ 13, 245, 233 },{ 13, 246, 232 }, { 14, 247, 232 },{ 15, 247, 231 },{ 15, 248, 231 },{ 16, 249, 230 },{ 17, 249, 229 }, { 18, 250, 228 },{ 18, 251, 227 },{ 19, 251, 226 },{ 20, 252, 225 },{ 21, 253, 224 }, { 22, 253, 224 },{ 23, 254, 223 },{ 23, 254, 222 },{ 24, 255, 221 },{ 25, 255, 220 }, { 26, 255, 219 },{ 27, 255, 218 },{ 28, 255, 218 },{ 29, 255, 217 },{ 30, 255, 216 }, { 30, 255, 215 },{ 31, 255, 214 },{ 32, 255, 214 },{ 33, 255, 213 },{ 34, 255, 212 }, { 35, 255, 211 },{ 36, 255, 210 },{ 37, 255, 209 },{ 38, 255, 208 },{ 39, 255, 207 }, { 39, 255, 207 },{ 40, 255, 206 },{ 41, 255, 205 },{ 42, 255, 204 },{ 43, 255, 203 }, { 44, 255, 202 },{ 45, 255, 201 },{ 46, 255, 200 },{ 47, 255, 199 },{ 48, 255, 198 }, { 48, 255, 198 },{ 49, 255, 197 },{ 50, 255, 196 },{ 51, 255, 195 },{ 52, 255, 194 }, { 53, 255, 193 },{ 54, 255, 192 },{ 55, 255, 191 },{ 55, 255, 191 },{ 56, 255, 190 }, { 57, 255, 189 },{ 58, 255, 188 },{ 59, 255, 187 },{ 60, 255, 186 },{ 60, 255, 186 }, { 61, 255, 185 },{ 62, 255, 184 },{ 63, 255, 183 },{ 64, 255, 182 },{ 65, 255, 181 }, { 65, 255, 181 },{ 66, 255, 180 },{ 67, 255, 179 },{ 68, 255, 178 },{ 69, 255, 177 }, { 70, 255, 176 },{ 71, 255, 175 },{ 72, 255, 174 },{ 73, 255, 173 },{ 74, 255, 172 }, { 74, 255, 172 },{ 75, 255, 171 },{ 76, 255, 170 },{ 77, 255, 169 },{ 78, 255, 168 }, { 79, 255, 167 },{ 80, 255, 166 },{ 81, 255, 165 },{ 82, 255, 164 },{ 83, 255, 163 }, { 83, 255, 163 },{ 84, 255, 162 },{ 84, 255, 162 },{ 85, 255, 161 },{ 85, 255, 161 }, { 86, 255, 160 },{ 87, 255, 159 },{ 87, 255, 159 },{ 88, 255, 158 },{ 88, 255, 158 }, { 89, 255, 157 },{ 89, 255, 157 },{ 90, 255, 156 },{ 91, 255, 155 },{ 92, 255, 154 }, { 93, 255, 153 },{ 94, 255, 152 },{ 95, 255, 151 },{ 96, 255, 150 },{ 97, 255, 149 }, { 97, 255, 149 },{ 98, 255, 148 },{ 99, 255, 147 },{ 100, 255, 146 },{ 101, 255, 145 }, { 102, 255, 144 },{ 102, 255, 143 },{ 103, 255, 142 },{ 104, 255, 141 },{ 105, 255, 140 }, { 106, 255, 140 },{ 107, 255, 139 },{ 107, 255, 138 },{ 108, 255, 137 },{ 109, 255, 136 }, { 110, 255, 135 },{ 111, 255, 134 },{ 112, 255, 134 },{ 113, 255, 133 },{ 114, 255, 132 }, { 114, 255, 131 },{ 115, 255, 130 },{ 116, 255, 130 },{ 117, 255, 129 },{ 118, 255, 128 }, { 119, 255, 127 },{ 120, 255, 126 },{ 121, 255, 125 },{ 122, 255, 124 },{ 123, 255, 123 }, { 123, 255, 123 },{ 124, 255, 122 },{ 125, 255, 121 },{ 126, 255, 120 },{ 127, 255, 119 }, { 128, 255, 118 },{ 129, 255, 117 },{ 130, 255, 116 },{ 130, 255, 115 },{ 131, 255, 114 }, { 132, 255, 114 },{ 133, 255, 113 },{ 134, 255, 112 },{ 134, 255, 111 },{ 135, 255, 110 }, { 136, 255, 109 },{ 137, 255, 108 },{ 138, 255, 107 },{ 139, 255, 107 },{ 140, 255, 106 }, { 140, 255, 105 },{ 141, 255, 104 },{ 142, 255, 103 },{ 143, 255, 102 },{ 144, 255, 102 }, { 145, 255, 101 },{ 146, 255, 100 },{ 147, 255, 99 },{ 148, 255, 98 },{ 149, 255, 97 }, { 149, 255, 97 },{ 150, 255, 96 },{ 151, 255, 95 },{ 152, 255, 94 },{ 153, 255, 93 }, { 154, 255, 92 },{ 155, 255, 91 },{ 156, 255, 90 },{ 157, 255, 89 },{ 157, 255, 89 }, { 158, 255, 88 },{ 158, 255, 88 },{ 159, 255, 87 },{ 159, 255, 87 },{ 160, 255, 86 }, { 161, 255, 85 },{ 161, 255, 85 },{ 162, 255, 84 },{ 162, 255, 84 },{ 163, 255, 83 }, { 163, 255, 83 },{ 164, 255, 82 },{ 165, 255, 81 },{ 166, 255, 80 },{ 167, 255, 79 }, { 168, 255, 78 },{ 169, 255, 77 },{ 170, 255, 76 },{ 171, 255, 75 },{ 172, 255, 74 }, { 172, 255, 74 },{ 173, 255, 73 },{ 174, 255, 72 },{ 175, 255, 71 },{ 176, 255, 70 }, { 177, 255, 69 },{ 178, 255, 68 },{ 179, 255, 67 },{ 180, 255, 66 },{ 181, 255, 65 }, { 181, 255, 65 },{ 182, 255, 64 },{ 183, 255, 63 },{ 184, 255, 62 },{ 185, 255, 61 }, { 186, 255, 60 },{ 186, 255, 60 },{ 187, 255, 59 },{ 188, 255, 58 },{ 189, 255, 57 }, { 190, 255, 56 },{ 191, 255, 55 },{ 191, 255, 55 },{ 192, 255, 54 },{ 193, 255, 53 }, { 194, 255, 52 },{ 195, 255, 51 },{ 196, 255, 50 },{ 197, 255, 49 },{ 198, 255, 48 }, { 198, 255, 48 },{ 199, 255, 47 },{ 200, 255, 46 },{ 201, 255, 45 },{ 202, 255, 44 }, { 203, 255, 43 },{ 204, 255, 42 },{ 205, 255, 41 },{ 206, 255, 40 },{ 207, 255, 39 }, { 207, 255, 39 },{ 208, 255, 38 },{ 209, 255, 37 },{ 210, 255, 36 },{ 211, 255, 35 }, { 212, 255, 34 },{ 213, 255, 33 },{ 214, 255, 32 },{ 214, 255, 31 },{ 215, 255, 30 }, { 216, 255, 30 },{ 217, 255, 29 },{ 218, 255, 28 },{ 218, 255, 27 },{ 219, 255, 26 }, { 220, 255, 25 },{ 221, 255, 24 },{ 222, 255, 23 },{ 223, 255, 23 },{ 224, 255, 22 }, { 224, 255, 21 },{ 225, 255, 20 },{ 226, 255, 19 },{ 227, 255, 18 },{ 228, 255, 18 }, { 229, 255, 17 },{ 230, 255, 16 },{ 231, 255, 15 },{ 231, 255, 15 },{ 232, 255, 14 }, { 232, 255, 13 },{ 233, 255, 13 },{ 234, 255, 12 },{ 234, 255, 11 },{ 235, 255, 11 }, { 235, 255, 10 },{ 236, 255, 10 },{ 236, 255, 9 },{ 237, 255, 8 },{ 238, 254, 8 }, { 238, 253, 7 },{ 239, 252, 6 },{ 240, 251, 5 },{ 241, 250, 5 },{ 242, 249, 4 }, { 243, 248, 3 },{ 244, 247, 3 },{ 245, 246, 2 },{ 246, 246, 1 },{ 247, 245, 0 }, { 247, 243, 0 },{ 248, 242, 0 },{ 249, 242, 0 },{ 250, 241, 0 },{ 250, 240, 0 }, { 251, 239, 0 },{ 252, 238, 0 },{ 252, 237, 0 },{ 253, 236, 0 },{ 254, 235, 0 }, { 255, 234, 0 },{ 255, 233, 0 },{ 255, 232, 0 },{ 255, 231, 0 },{ 255, 230, 0 }, { 255, 229, 0 },{ 255, 228, 0 },{ 255, 227, 0 },{ 255, 226, 0 },{ 255, 225, 0 }, { 255, 224, 0 },{ 255, 223, 0 },{ 255, 222, 0 },{ 255, 221, 0 },{ 255, 220, 0 }, { 255, 219, 0 },{ 255, 218, 0 },{ 255, 217, 0 },{ 255, 216, 0 },{ 255, 215, 0 }, { 255, 214, 0 },{ 255, 213, 0 },{ 255, 212, 0 },{ 255, 211, 0 },{ 255, 210, 0 }, { 255, 209, 0 },{ 255, 208, 0 },{ 255, 207, 0 },{ 255, 206, 0 },{ 255, 205, 0 }, { 255, 204, 0 },{ 255, 203, 0 },{ 255, 202, 0 },{ 255, 201, 0 },{ 255, 200, 0 }, { 255, 199, 0 },{ 255, 198, 0 },{ 255, 197, 0 },{ 255, 196, 0 },{ 255, 195, 0 }, { 255, 194, 0 },{ 255, 193, 0 },{ 255, 192, 0 },{ 255, 191, 0 },{ 255, 190, 0 }, { 255, 189, 0 },{ 255, 188, 0 },{ 255, 187, 0 },{ 255, 186, 0 },{ 255, 185, 0 }, { 255, 184, 0 },{ 255, 183, 0 },{ 255, 182, 0 },{ 255, 180, 0 },{ 255, 179, 0 }, { 255, 178, 0 },{ 255, 177, 0 },{ 255, 176, 0 },{ 255, 176, 0 },{ 255, 175, 0 }, { 255, 175, 0 },{ 255, 174, 0 },{ 255, 173, 0 },{ 255, 173, 0 },{ 255, 172, 0 }, { 255, 171, 0 },{ 255, 171, 0 },{ 255, 170, 0 },{ 255, 169, 0 },{ 255, 168, 0 }, { 255, 167, 0 },{ 255, 166, 0 },{ 255, 165, 0 },{ 255, 164, 0 },{ 255, 163, 0 }, { 255, 162, 0 },{ 255, 161, 0 },{ 255, 160, 0 },{ 255, 159, 0 },{ 255, 158, 0 }, { 255, 157, 0 },{ 255, 156, 0 },{ 255, 155, 0 },{ 255, 154, 0 },{ 255, 153, 0 }, { 255, 152, 0 },{ 255, 151, 0 },{ 255, 150, 0 },{ 255, 150, 0 },{ 255, 149, 0 }, { 255, 147, 0 },{ 255, 146, 0 },{ 255, 146, 0 },{ 255, 145, 0 },{ 255, 144, 0 }, { 255, 143, 0 },{ 255, 142, 0 },{ 255, 141, 0 },{ 255, 140, 0 },{ 255, 139, 0 }, { 255, 138, 0 },{ 255, 137, 0 },{ 255, 136, 0 },{ 255, 135, 0 },{ 255, 134, 0 }, { 255, 133, 0 },{ 255, 132, 0 },{ 255, 131, 0 },{ 255, 130, 0 },{ 255, 129, 0 }, { 255, 128, 0 },{ 255, 127, 0 },{ 255, 126, 0 },{ 255, 125, 0 },{ 255, 124, 0 }, { 255, 123, 0 },{ 255, 122, 0 },{ 255, 121, 0 },{ 255, 120, 0 },{ 255, 119, 0 }, { 255, 118, 0 },{ 255, 117, 0 },{ 255, 116, 0 },{ 255, 115, 0 },{ 255, 114, 0 }, { 255, 113, 0 },{ 255, 112, 0 },{ 255, 111, 0 },{ 255, 109, 0 },{ 255, 108, 0 }, { 255, 107, 0 },{ 255, 106, 0 },{ 255, 105, 0 },{ 255, 104, 0 },{ 255, 103, 0 }, { 255, 102, 0 },{ 255, 101, 0 },{ 255, 100, 0 },{ 255, 99, 0 },{ 255, 98, 0 }, { 255, 97, 0 },{ 255, 96, 0 },{ 255, 95, 0 },{ 255, 94, 0 },{ 255, 93, 0 }, { 255, 92, 0 },{ 255, 91, 0 },{ 255, 91, 0 },{ 255, 90, 0 },{ 255, 90, 0 }, { 255, 89, 0 },{ 255, 88, 0 },{ 255, 88, 0 },{ 255, 87, 0 },{ 255, 86, 0 }, { 255, 86, 0 },{ 255, 85, 0 },{ 255, 84, 0 },{ 255, 83, 0 },{ 255, 82, 0 }, { 255, 81, 0 },{ 255, 80, 0 },{ 255, 79, 0 },{ 255, 78, 0 },{ 255, 77, 0 }, { 255, 76, 0 },{ 255, 75, 0 },{ 255, 74, 0 },{ 255, 73, 0 },{ 255, 72, 0 }, { 255, 71, 0 },{ 255, 70, 0 },{ 255, 69, 0 },{ 255, 68, 0 },{ 255, 67, 0 }, { 255, 66, 0 },{ 255, 65, 0 },{ 255, 64, 0 },{ 255, 63, 0 },{ 255, 62, 0 }, { 255, 61, 0 },{ 255, 60, 0 },{ 255, 59, 0 },{ 255, 58, 0 },{ 255, 57, 0 }, { 255, 56, 0 },{ 255, 55, 0 },{ 255, 54, 0 },{ 255, 54, 0 },{ 255, 53, 0 }, { 255, 51, 0 },{ 255, 50, 0 },{ 255, 49, 0 },{ 255, 48, 0 },{ 255, 47, 0 }, { 255, 46, 0 },{ 255, 45, 0 },{ 255, 44, 0 },{ 255, 43, 0 },{ 255, 42, 0 }, { 255, 41, 0 },{ 255, 40, 0 },{ 255, 39, 0 },{ 255, 38, 0 },{ 255, 37, 0 }, { 255, 36, 0 },{ 255, 35, 0 },{ 255, 34, 0 },{ 255, 33, 0 },{ 255, 32, 0 }, { 255, 31, 0 },{ 255, 30, 0 },{ 255, 29, 0 },{ 255, 28, 0 },{ 255, 27, 0 }, { 255, 26, 0 },{ 255, 25, 0 },{ 255, 24, 0 },{ 254, 23, 0 },{ 254, 22, 0 }, { 254, 21, 0 },{ 254, 20, 0 },{ 254, 19, 0 },{ 254, 18, 0 },{ 253, 17, 0 }, { 251, 16, 0 },{ 250, 15, 0 },{ 249, 14, 0 },{ 248, 13, 0 },{ 247, 12, 0 }, { 246, 11, 0 },{ 244, 10, 0 },{ 243, 9, 0 },{ 242, 8, 0 },{ 241, 7, 0 }, { 240, 6, 0 },{ 239, 6, 0 },{ 239, 5, 0 },{ 238, 4, 0 },{ 237, 4, 0 }, { 236, 3, 0 },{ 235, 3, 0 },{ 234, 2, 0 },{ 234, 1, 0 },{ 233, 1, 0 }, { 232, 0, 0 },{ 231, 0, 0 },{ 230, 0, 0 },{ 228, 0, 0 },{ 227, 0, 0 }, { 226, 0, 0 },{ 225, 0, 0 },{ 223, 0, 0 },{ 222, 0, 0 },{ 221, 0, 0 }, { 219, 0, 0 },{ 218, 0, 0 },{ 217, 0, 0 },{ 216, 0, 0 },{ 214, 0, 0 }, { 213, 0, 0 },{ 212, 0, 0 },{ 211, 0, 0 },{ 209, 0, 0 },{ 208, 0, 0 }, { 207, 0, 0 },{ 206, 0, 0 },{ 204, 0, 0 },{ 203, 0, 0 },{ 202, 0, 0 }, { 201, 0, 0 },{ 200, 0, 0 },{ 198, 0, 0 },{ 197, 0, 0 },{ 196, 0, 0 }, { 195, 0, 0 },{ 194, 0, 0 },{ 193, 0, 0 },{ 191, 0, 0 },{ 190, 0, 0 }, { 189, 0, 0 },{ 188, 0, 0 },{ 186, 0, 0 },{ 185, 0, 0 },{ 184, 0, 0 }, { 183, 0, 0 },{ 181, 0, 0 },{ 180, 0, 0 },{ 179, 0, 0 },{ 178, 0, 0 }, { 176, 0, 0 },{ 175, 0, 0 },{ 174, 0, 0 },{ 173, 0, 0 },{ 171, 0, 0 }, { 170, 0, 0 },{ 169, 0, 0 },{ 168, 0, 0 },{ 166, 0, 0 },{ 165, 0, 0 }, { 164, 0, 0 },{ 163, 0, 0 },{ 161, 0, 0 },{ 160, 0, 0 },{ 159, 0, 0 }, { 158, 0, 0 },{ 157, 0, 0 },{ 156, 0, 0 },{ 154, 0, 0 },{ 153, 0, 0 }, { 152, 0, 0 },{ 151, 0, 0 },{ 150, 0, 0 },{ 148, 0, 0 },{ 147, 0, 0 }, { 146, 0, 0 },{ 145, 0, 0 },{ 143, 0, 0 },{ 142, 0, 0 },{ 141, 0, 0 }, { 140, 0, 0 },{ 138, 0, 0 },{ 137, 0, 0 },{ 136, 0, 0 },{ 135, 0, 0 }, { 134, 0, 0 },{ 133, 0, 0 },{ 133, 0, 0 },{ 132, 0, 0 },{ 131, 0, 0 }, { 130, 0, 0 },{ 129, 0, 0 },{ 129, 0, 0 },{ 128, 0, 0 },{ 127, 0, 0 }, { 122, 0, 9 },{ 117, 0, 18 },{ 112, 0, 27 },{ 107, 0, 36 },{ 102, 0, 45 } }; const rgb_t prism_colormap[1000] = { { 255, 0, 0 },{ 255, 2, 0 },{ 255, 4, 0 },{ 255, 6, 0 },{ 255, 8, 0 }, { 255, 10, 0 },{ 255, 11, 0 },{ 255, 13, 0 },{ 255, 15, 0 },{ 255, 17, 0 }, { 255, 19, 0 },{ 255, 21, 0 },{ 255, 23, 0 },{ 255, 25, 0 },{ 255, 27, 0 }, { 255, 29, 0 },{ 255, 31, 0 },{ 255, 33, 0 },{ 255, 34, 0 },{ 255, 36, 0 }, { 255, 38, 0 },{ 255, 40, 0 },{ 255, 42, 0 },{ 255, 44, 0 },{ 255, 46, 0 }, { 255, 48, 0 },{ 255, 50, 0 },{ 255, 52, 0 },{ 255, 54, 0 },{ 255, 56, 0 }, { 255, 57, 0 },{ 255, 59, 0 },{ 255, 61, 0 },{ 255, 63, 0 },{ 255, 65, 0 }, { 255, 67, 0 },{ 255, 69, 0 },{ 255, 71, 0 },{ 255, 73, 0 },{ 255, 75, 0 }, { 255, 77, 0 },{ 255, 78, 0 },{ 255, 80, 0 },{ 255, 82, 0 },{ 255, 84, 0 }, { 255, 86, 0 },{ 255, 88, 0 },{ 255, 90, 0 },{ 255, 92, 0 },{ 255, 94, 0 }, { 255, 96, 0 },{ 255, 98, 0 },{ 255, 100, 0 },{ 255, 101, 0 },{ 255, 103, 0 }, { 255, 105, 0 },{ 255, 107, 0 },{ 255, 109, 0 },{ 255, 111, 0 },{ 255, 113, 0 }, { 255, 115, 0 },{ 255, 117, 0 },{ 255, 119, 0 },{ 255, 121, 0 },{ 255, 123, 0 }, { 255, 124, 0 },{ 255, 126, 0 },{ 255, 128, 0 },{ 255, 130, 0 },{ 255, 132, 0 }, { 255, 134, 0 },{ 255, 136, 0 },{ 255, 138, 0 },{ 255, 140, 0 },{ 255, 142, 0 }, { 255, 144, 0 },{ 255, 145, 0 },{ 255, 147, 0 },{ 255, 149, 0 },{ 255, 151, 0 }, { 255, 153, 0 },{ 255, 155, 0 },{ 255, 157, 0 },{ 255, 159, 0 },{ 255, 161, 0 }, { 255, 163, 0 },{ 255, 165, 0 },{ 255, 167, 0 },{ 255, 168, 0 },{ 255, 170, 0 }, { 255, 172, 0 },{ 255, 174, 0 },{ 255, 176, 0 },{ 255, 178, 0 },{ 255, 180, 0 }, { 255, 182, 0 },{ 255, 184, 0 },{ 255, 186, 0 },{ 255, 188, 0 },{ 255, 190, 0 }, { 255, 191, 0 },{ 255, 193, 0 },{ 255, 195, 0 },{ 255, 197, 0 },{ 255, 199, 0 }, { 255, 201, 0 },{ 255, 203, 0 },{ 255, 205, 0 },{ 255, 207, 0 },{ 255, 209, 0 }, { 255, 211, 0 },{ 255, 212, 0 },{ 255, 214, 0 },{ 255, 216, 0 },{ 255, 218, 0 }, { 255, 220, 0 },{ 255, 222, 0 },{ 255, 224, 0 },{ 255, 226, 0 },{ 255, 228, 0 }, { 255, 230, 0 },{ 255, 232, 0 },{ 255, 234, 0 },{ 255, 235, 0 },{ 255, 237, 0 }, { 255, 239, 0 },{ 255, 241, 0 },{ 255, 243, 0 },{ 255, 245, 0 },{ 255, 247, 0 }, { 255, 249, 0 },{ 255, 251, 0 },{ 255, 253, 0 },{ 255, 255, 0 },{ 252, 255, 0 }, { 248, 255, 0 },{ 244, 255, 0 },{ 240, 255, 0 },{ 237, 255, 0 },{ 233, 255, 0 }, { 229, 255, 0 },{ 225, 255, 0 },{ 221, 255, 0 },{ 217, 255, 0 },{ 214, 255, 0 }, { 210, 255, 0 },{ 206, 255, 0 },{ 202, 255, 0 },{ 198, 255, 0 },{ 195, 255, 0 }, { 191, 255, 0 },{ 187, 255, 0 },{ 183, 255, 0 },{ 179, 255, 0 },{ 175, 255, 0 }, { 172, 255, 0 },{ 168, 255, 0 },{ 164, 255, 0 },{ 160, 255, 0 },{ 156, 255, 0 }, { 152, 255, 0 },{ 149, 255, 0 },{ 145, 255, 0 },{ 141, 255, 0 },{ 137, 255, 0 }, { 133, 255, 0 },{ 129, 255, 0 },{ 126, 255, 0 },{ 122, 255, 0 },{ 118, 255, 0 }, { 114, 255, 0 },{ 110, 255, 0 },{ 106, 255, 0 },{ 103, 255, 0 },{ 99, 255, 0 }, { 95, 255, 0 },{ 91, 255, 0 },{ 87, 255, 0 },{ 83, 255, 0 },{ 80, 255, 0 }, { 76, 255, 0 },{ 72, 255, 0 },{ 68, 255, 0 },{ 64, 255, 0 },{ 60, 255, 0 }, { 57, 255, 0 },{ 53, 255, 0 },{ 49, 255, 0 },{ 45, 255, 0 },{ 41, 255, 0 }, { 38, 255, 0 },{ 34, 255, 0 },{ 30, 255, 0 },{ 26, 255, 0 },{ 22, 255, 0 }, { 18, 255, 0 },{ 15, 255, 0 },{ 11, 255, 0 },{ 7, 255, 0 },{ 3, 255, 0 }, { 0, 254, 1 },{ 0, 250, 5 },{ 0, 247, 8 },{ 0, 243, 12 },{ 0, 239, 16 }, { 0, 235, 20 },{ 0, 231, 24 },{ 0, 227, 28 },{ 0, 224, 31 },{ 0, 220, 35 }, { 0, 216, 39 },{ 0, 212, 43 },{ 0, 208, 47 },{ 0, 204, 51 },{ 0, 201, 54 }, { 0, 197, 58 },{ 0, 193, 62 },{ 0, 189, 66 },{ 0, 185, 70 },{ 0, 181, 74 }, { 0, 178, 77 },{ 0, 174, 81 },{ 0, 170, 85 },{ 0, 166, 89 },{ 0, 162, 93 }, { 0, 159, 96 },{ 0, 155, 100 },{ 0, 151, 104 },{ 0, 147, 108 },{ 0, 143, 112 }, { 0, 139, 116 },{ 0, 136, 119 },{ 0, 132, 123 },{ 0, 128, 127 },{ 0, 124, 131 }, { 0, 120, 135 },{ 0, 116, 139 },{ 0, 113, 142 },{ 0, 109, 146 },{ 0, 105, 150 }, { 0, 101, 154 },{ 0, 97, 158 },{ 0, 93, 162 },{ 0, 90, 165 },{ 0, 86, 169 }, { 0, 82, 173 },{ 0, 78, 177 },{ 0, 74, 181 },{ 0, 70, 185 },{ 0, 67, 188 }, { 0, 63, 192 },{ 0, 59, 196 },{ 0, 55, 200 },{ 0, 51, 204 },{ 0, 47, 208 }, { 0, 44, 211 },{ 0, 40, 215 },{ 0, 36, 219 },{ 0, 32, 223 },{ 0, 28, 227 }, { 0, 25, 230 },{ 0, 21, 234 },{ 0, 17, 238 },{ 0, 13, 242 },{ 0, 9, 246 }, { 0, 5, 250 },{ 0, 2, 253 },{ 2, 0, 255 },{ 4, 0, 255 },{ 7, 0, 255 }, { 9, 0, 255 },{ 12, 0, 255 },{ 14, 0, 255 },{ 17, 0, 255 },{ 19, 0, 255 }, { 22, 0, 255 },{ 25, 0, 255 },{ 27, 0, 255 },{ 30, 0, 255 },{ 32, 0, 255 }, { 35, 0, 255 },{ 37, 0, 255 },{ 40, 0, 255 },{ 42, 0, 255 },{ 45, 0, 255 }, { 47, 0, 255 },{ 50, 0, 255 },{ 53, 0, 255 },{ 55, 0, 255 },{ 58, 0, 255 }, { 60, 0, 255 },{ 63, 0, 255 },{ 65, 0, 255 },{ 68, 0, 255 },{ 70, 0, 255 }, { 73, 0, 255 },{ 76, 0, 255 },{ 78, 0, 255 },{ 81, 0, 255 },{ 83, 0, 255 }, { 86, 0, 255 },{ 88, 0, 255 },{ 91, 0, 255 },{ 93, 0, 255 },{ 96, 0, 255 }, { 99, 0, 255 },{ 101, 0, 255 },{ 104, 0, 255 },{ 106, 0, 255 },{ 109, 0, 255 }, { 111, 0, 255 },{ 114, 0, 255 },{ 116, 0, 255 },{ 119, 0, 255 },{ 122, 0, 255 }, { 124, 0, 255 },{ 127, 0, 255 },{ 129, 0, 255 },{ 132, 0, 255 },{ 134, 0, 255 }, { 137, 0, 255 },{ 139, 0, 255 },{ 142, 0, 255 },{ 144, 0, 255 },{ 147, 0, 255 }, { 150, 0, 255 },{ 152, 0, 255 },{ 155, 0, 255 },{ 157, 0, 255 },{ 160, 0, 255 }, { 162, 0, 255 },{ 165, 0, 255 },{ 167, 0, 255 },{ 170, 0, 255 },{ 171, 0, 251 }, { 173, 0, 247 },{ 174, 0, 244 },{ 175, 0, 240 },{ 176, 0, 236 },{ 178, 0, 232 }, { 179, 0, 228 },{ 180, 0, 224 },{ 181, 0, 221 },{ 183, 0, 217 },{ 184, 0, 213 }, { 185, 0, 209 },{ 187, 0, 205 },{ 188, 0, 201 },{ 189, 0, 198 },{ 190, 0, 194 }, { 192, 0, 190 },{ 193, 0, 186 },{ 194, 0, 182 },{ 196, 0, 178 },{ 197, 0, 175 }, { 198, 0, 171 },{ 199, 0, 167 },{ 201, 0, 163 },{ 202, 0, 159 },{ 203, 0, 155 }, { 204, 0, 152 },{ 206, 0, 148 },{ 207, 0, 144 },{ 208, 0, 140 },{ 210, 0, 136 }, { 211, 0, 132 },{ 212, 0, 129 },{ 213, 0, 125 },{ 215, 0, 121 },{ 216, 0, 117 }, { 217, 0, 113 },{ 218, 0, 110 },{ 220, 0, 106 },{ 221, 0, 102 },{ 222, 0, 98 }, { 224, 0, 94 },{ 225, 0, 90 },{ 226, 0, 87 },{ 227, 0, 83 },{ 229, 0, 79 }, { 230, 0, 75 },{ 231, 0, 71 },{ 233, 0, 67 },{ 234, 0, 64 },{ 235, 0, 60 }, { 236, 0, 56 },{ 238, 0, 52 },{ 239, 0, 48 },{ 240, 0, 44 },{ 241, 0, 41 }, { 243, 0, 37 },{ 244, 0, 33 },{ 245, 0, 29 },{ 247, 0, 25 },{ 248, 0, 21 }, { 249, 0, 18 },{ 250, 0, 14 },{ 252, 0, 10 },{ 253, 0, 6 },{ 254, 0, 2 }, { 255, 1, 0 },{ 255, 3, 0 },{ 255, 5, 0 },{ 255, 7, 0 },{ 255, 8, 0 }, { 255, 10, 0 },{ 255, 12, 0 },{ 255, 14, 0 },{ 255, 16, 0 },{ 255, 18, 0 }, { 255, 20, 0 },{ 255, 22, 0 },{ 255, 24, 0 },{ 255, 26, 0 },{ 255, 28, 0 }, { 255, 29, 0 },{ 255, 31, 0 },{ 255, 33, 0 },{ 255, 35, 0 },{ 255, 37, 0 }, { 255, 39, 0 },{ 255, 41, 0 },{ 255, 43, 0 },{ 255, 45, 0 },{ 255, 47, 0 }, { 255, 49, 0 },{ 255, 51, 0 },{ 255, 52, 0 },{ 255, 54, 0 },{ 255, 56, 0 }, { 255, 58, 0 },{ 255, 60, 0 },{ 255, 62, 0 },{ 255, 64, 0 },{ 255, 66, 0 }, { 255, 68, 0 },{ 255, 70, 0 },{ 255, 72, 0 },{ 255, 74, 0 },{ 255, 75, 0 }, { 255, 77, 0 },{ 255, 79, 0 },{ 255, 81, 0 },{ 255, 83, 0 },{ 255, 85, 0 }, { 255, 87, 0 },{ 255, 89, 0 },{ 255, 91, 0 },{ 255, 93, 0 },{ 255, 95, 0 }, { 255, 96, 0 },{ 255, 98, 0 },{ 255, 100, 0 },{ 255, 102, 0 },{ 255, 104, 0 }, { 255, 106, 0 },{ 255, 108, 0 },{ 255, 110, 0 },{ 255, 112, 0 },{ 255, 114, 0 }, { 255, 116, 0 },{ 255, 118, 0 },{ 255, 119, 0 },{ 255, 121, 0 },{ 255, 123, 0 }, { 255, 125, 0 },{ 255, 127, 0 },{ 255, 129, 0 },{ 255, 131, 0 },{ 255, 133, 0 }, { 255, 135, 0 },{ 255, 137, 0 },{ 255, 139, 0 },{ 255, 141, 0 },{ 255, 142, 0 }, { 255, 144, 0 },{ 255, 146, 0 },{ 255, 148, 0 },{ 255, 150, 0 },{ 255, 152, 0 }, { 255, 154, 0 },{ 255, 156, 0 },{ 255, 158, 0 },{ 255, 160, 0 },{ 255, 162, 0 }, { 255, 163, 0 },{ 255, 165, 0 },{ 255, 167, 0 },{ 255, 169, 0 },{ 255, 171, 0 }, { 255, 173, 0 },{ 255, 175, 0 },{ 255, 177, 0 },{ 255, 179, 0 },{ 255, 181, 0 }, { 255, 183, 0 },{ 255, 185, 0 },{ 255, 186, 0 },{ 255, 188, 0 },{ 255, 190, 0 }, { 255, 192, 0 },{ 255, 194, 0 },{ 255, 196, 0 },{ 255, 198, 0 },{ 255, 200, 0 }, { 255, 202, 0 },{ 255, 204, 0 },{ 255, 206, 0 },{ 255, 208, 0 },{ 255, 209, 0 }, { 255, 211, 0 },{ 255, 213, 0 },{ 255, 215, 0 },{ 255, 217, 0 },{ 255, 219, 0 }, { 255, 221, 0 },{ 255, 223, 0 },{ 255, 225, 0 },{ 255, 227, 0 },{ 255, 229, 0 }, { 255, 230, 0 },{ 255, 232, 0 },{ 255, 234, 0 },{ 255, 236, 0 },{ 255, 238, 0 }, { 255, 240, 0 },{ 255, 242, 0 },{ 255, 244, 0 },{ 255, 246, 0 },{ 255, 248, 0 }, { 255, 250, 0 },{ 255, 252, 0 },{ 255, 253, 0 },{ 254, 255, 0 },{ 250, 255, 0 }, { 247, 255, 0 },{ 243, 255, 0 },{ 239, 255, 0 },{ 235, 255, 0 },{ 231, 255, 0 }, { 227, 255, 0 },{ 224, 255, 0 },{ 220, 255, 0 },{ 216, 255, 0 },{ 212, 255, 0 }, { 208, 255, 0 },{ 204, 255, 0 },{ 201, 255, 0 },{ 197, 255, 0 },{ 193, 255, 0 }, { 189, 255, 0 },{ 185, 255, 0 },{ 181, 255, 0 },{ 178, 255, 0 },{ 174, 255, 0 }, { 170, 255, 0 },{ 166, 255, 0 },{ 162, 255, 0 },{ 159, 255, 0 },{ 155, 255, 0 }, { 151, 255, 0 },{ 147, 255, 0 },{ 143, 255, 0 },{ 139, 255, 0 },{ 136, 255, 0 }, { 132, 255, 0 },{ 128, 255, 0 },{ 124, 255, 0 },{ 120, 255, 0 },{ 116, 255, 0 }, { 113, 255, 0 },{ 109, 255, 0 },{ 105, 255, 0 },{ 101, 255, 0 },{ 97, 255, 0 }, { 93, 255, 0 },{ 90, 255, 0 },{ 86, 255, 0 },{ 82, 255, 0 },{ 78, 255, 0 }, { 74, 255, 0 },{ 70, 255, 0 },{ 67, 255, 0 },{ 63, 255, 0 },{ 59, 255, 0 }, { 55, 255, 0 },{ 51, 255, 0 },{ 47, 255, 0 },{ 44, 255, 0 },{ 40, 255, 0 }, { 36, 255, 0 },{ 32, 255, 0 },{ 28, 255, 0 },{ 25, 255, 0 },{ 21, 255, 0 }, { 17, 255, 0 },{ 13, 255, 0 },{ 9, 255, 0 },{ 5, 255, 0 },{ 2, 255, 0 }, { 0, 253, 2 },{ 0, 249, 6 },{ 0, 245, 10 },{ 0, 241, 14 },{ 0, 237, 18 }, { 0, 234, 21 },{ 0, 230, 25 },{ 0, 226, 29 },{ 0, 222, 33 },{ 0, 218, 37 }, { 0, 214, 41 },{ 0, 211, 44 },{ 0, 207, 48 },{ 0, 203, 52 },{ 0, 199, 56 }, { 0, 195, 60 },{ 0, 191, 64 },{ 0, 188, 67 },{ 0, 184, 71 },{ 0, 180, 75 }, { 0, 176, 79 },{ 0, 172, 83 },{ 0, 168, 87 },{ 0, 165, 90 },{ 0, 161, 94 }, { 0, 157, 98 },{ 0, 153, 102 },{ 0, 149, 106 },{ 0, 145, 110 },{ 0, 142, 113 }, { 0, 138, 117 },{ 0, 134, 121 },{ 0, 130, 125 },{ 0, 126, 129 },{ 0, 123, 132 }, { 0, 119, 136 },{ 0, 115, 140 },{ 0, 111, 144 },{ 0, 107, 148 },{ 0, 103, 152 }, { 0, 100, 155 },{ 0, 96, 159 },{ 0, 92, 163 },{ 0, 88, 167 },{ 0, 84, 171 }, { 0, 80, 175 },{ 0, 77, 178 },{ 0, 73, 182 },{ 0, 69, 186 },{ 0, 65, 190 }, { 0, 61, 194 },{ 0, 57, 198 },{ 0, 54, 201 },{ 0, 50, 205 },{ 0, 46, 209 }, { 0, 42, 213 },{ 0, 38, 217 },{ 0, 34, 221 },{ 0, 31, 224 },{ 0, 27, 228 }, { 0, 23, 232 },{ 0, 19, 236 },{ 0, 15, 240 },{ 0, 11, 244 },{ 0, 8, 247 }, { 0, 4, 251 },{ 0, 0, 255 },{ 3, 0, 255 },{ 5, 0, 255 },{ 8, 0, 255 }, { 10, 0, 255 },{ 13, 0, 255 },{ 15, 0, 255 },{ 18, 0, 255 },{ 20, 0, 255 }, { 23, 0, 255 },{ 26, 0, 255 },{ 28, 0, 255 },{ 31, 0, 255 },{ 33, 0, 255 }, { 36, 0, 255 },{ 38, 0, 255 },{ 41, 0, 255 },{ 43, 0, 255 },{ 46, 0, 255 }, { 48, 0, 255 },{ 51, 0, 255 },{ 54, 0, 255 },{ 56, 0, 255 },{ 59, 0, 255 }, { 61, 0, 255 },{ 64, 0, 255 },{ 66, 0, 255 },{ 69, 0, 255 },{ 71, 0, 255 }, { 74, 0, 255 },{ 77, 0, 255 },{ 79, 0, 255 },{ 82, 0, 255 },{ 84, 0, 255 }, { 87, 0, 255 },{ 89, 0, 255 },{ 92, 0, 255 },{ 94, 0, 255 },{ 97, 0, 255 }, { 100, 0, 255 },{ 102, 0, 255 },{ 105, 0, 255 },{ 107, 0, 255 },{ 110, 0, 255 }, { 112, 0, 255 },{ 115, 0, 255 },{ 117, 0, 255 },{ 120, 0, 255 },{ 123, 0, 255 }, { 125, 0, 255 },{ 128, 0, 255 },{ 130, 0, 255 },{ 133, 0, 255 },{ 135, 0, 255 }, { 138, 0, 255 },{ 140, 0, 255 },{ 143, 0, 255 },{ 145, 0, 255 },{ 148, 0, 255 }, { 151, 0, 255 },{ 153, 0, 255 },{ 156, 0, 255 },{ 158, 0, 255 },{ 161, 0, 255 }, { 163, 0, 255 },{ 166, 0, 255 },{ 168, 0, 255 },{ 171, 0, 253 },{ 172, 0, 250 }, { 173, 0, 246 },{ 174, 0, 242 },{ 176, 0, 238 },{ 177, 0, 234 },{ 178, 0, 230 }, { 179, 0, 227 },{ 181, 0, 223 },{ 182, 0, 219 },{ 183, 0, 215 },{ 185, 0, 211 }, { 186, 0, 208 },{ 187, 0, 204 },{ 188, 0, 200 },{ 190, 0, 196 },{ 191, 0, 192 }, { 192, 0, 188 },{ 193, 0, 185 },{ 195, 0, 181 },{ 196, 0, 177 },{ 197, 0, 173 }, { 199, 0, 169 },{ 200, 0, 165 },{ 201, 0, 162 },{ 202, 0, 158 },{ 204, 0, 154 }, { 205, 0, 150 },{ 206, 0, 146 },{ 208, 0, 142 },{ 209, 0, 139 },{ 210, 0, 135 }, { 211, 0, 131 },{ 213, 0, 127 },{ 214, 0, 123 },{ 215, 0, 119 },{ 216, 0, 116 }, { 218, 0, 112 },{ 219, 0, 108 },{ 220, 0, 104 },{ 222, 0, 100 },{ 223, 0, 96 }, { 224, 0, 93 },{ 225, 0, 89 },{ 227, 0, 85 },{ 228, 0, 81 },{ 229, 0, 77 }, { 230, 0, 74 },{ 232, 0, 70 },{ 233, 0, 66 },{ 234, 0, 62 },{ 236, 0, 58 }, { 237, 0, 54 },{ 238, 0, 51 },{ 239, 0, 47 },{ 241, 0, 43 },{ 242, 0, 39 }, { 243, 0, 35 },{ 245, 0, 31 },{ 246, 0, 28 },{ 247, 0, 24 },{ 248, 0, 20 }, { 250, 0, 16 },{ 251, 0, 12 },{ 252, 0, 8 },{ 253, 0, 5 },{ 255, 0, 1 }, { 255, 2, 0 },{ 255, 3, 0 },{ 255, 5, 0 },{ 255, 7, 0 },{ 255, 9, 0 }, { 255, 11, 0 },{ 255, 13, 0 },{ 255, 15, 0 },{ 255, 17, 0 },{ 255, 19, 0 }, { 255, 21, 0 },{ 255, 23, 0 },{ 255, 25, 0 },{ 255, 26, 0 },{ 255, 28, 0 }, { 255, 30, 0 },{ 255, 32, 0 },{ 255, 34, 0 },{ 255, 36, 0 },{ 255, 38, 0 }, { 255, 40, 0 },{ 255, 42, 0 },{ 255, 44, 0 },{ 255, 46, 0 },{ 255, 47, 0 }, { 255, 49, 0 },{ 255, 51, 0 },{ 255, 53, 0 },{ 255, 55, 0 },{ 255, 57, 0 }, { 255, 59, 0 },{ 255, 61, 0 },{ 255, 63, 0 },{ 255, 65, 0 },{ 255, 67, 0 }, { 255, 69, 0 },{ 255, 70, 0 },{ 255, 72, 0 },{ 255, 74, 0 },{ 255, 76, 0 }, { 255, 78, 0 },{ 255, 80, 0 },{ 255, 82, 0 },{ 255, 84, 0 },{ 255, 86, 0 }, { 255, 88, 0 },{ 255, 90, 0 },{ 255, 92, 0 },{ 255, 93, 0 },{ 255, 95, 0 }, { 255, 97, 0 },{ 255, 99, 0 },{ 255, 101, 0 },{ 255, 103, 0 },{ 255, 105, 0 }, { 255, 107, 0 },{ 255, 109, 0 },{ 255, 111, 0 },{ 255, 113, 0 },{ 255, 114, 0 }, { 255, 116, 0 },{ 255, 118, 0 },{ 255, 120, 0 },{ 255, 122, 0 },{ 255, 124, 0 }, { 255, 126, 0 },{ 255, 128, 0 },{ 255, 130, 0 },{ 255, 132, 0 },{ 255, 134, 0 }, { 255, 136, 0 },{ 255, 137, 0 },{ 255, 139, 0 },{ 255, 141, 0 },{ 255, 143, 0 }, { 255, 145, 0 },{ 255, 147, 0 },{ 255, 149, 0 },{ 255, 151, 0 },{ 255, 153, 0 }, { 255, 155, 0 },{ 255, 157, 0 },{ 255, 159, 0 },{ 255, 160, 0 },{ 255, 162, 0 }, { 255, 164, 0 },{ 255, 166, 0 },{ 255, 168, 0 },{ 255, 170, 0 },{ 255, 172, 0 }, { 255, 174, 0 },{ 255, 176, 0 },{ 255, 178, 0 },{ 255, 180, 0 },{ 255, 181, 0 }, { 255, 183, 0 },{ 255, 185, 0 },{ 255, 187, 0 },{ 255, 189, 0 },{ 255, 191, 0 }, { 255, 193, 0 },{ 255, 195, 0 },{ 255, 197, 0 },{ 255, 199, 0 },{ 255, 201, 0 }, { 255, 203, 0 },{ 255, 204, 0 },{ 255, 206, 0 },{ 255, 208, 0 },{ 255, 210, 0 }, { 255, 212, 0 },{ 255, 214, 0 },{ 255, 216, 0 },{ 255, 218, 0 },{ 255, 220, 0 }, { 255, 222, 0 },{ 255, 224, 0 },{ 255, 226, 0 },{ 255, 227, 0 },{ 255, 229, 0 }, { 255, 231, 0 },{ 255, 233, 0 },{ 255, 235, 0 },{ 255, 237, 0 },{ 255, 239, 0 }, { 255, 241, 0 },{ 255, 243, 0 },{ 255, 245, 0 },{ 255, 247, 0 },{ 255, 248, 0 }, { 255, 250, 0 },{ 255, 252, 0 },{ 255, 254, 0 },{ 253, 255, 0 },{ 249, 255, 0 }, { 245, 255, 0 },{ 241, 255, 0 },{ 237, 255, 0 },{ 234, 255, 0 },{ 230, 255, 0 }, { 226, 255, 0 },{ 222, 255, 0 },{ 218, 255, 0 },{ 214, 255, 0 },{ 211, 255, 0 }, { 207, 255, 0 },{ 203, 255, 0 },{ 199, 255, 0 },{ 195, 255, 0 },{ 191, 255, 0 }, { 188, 255, 0 },{ 184, 255, 0 },{ 180, 255, 0 },{ 176, 255, 0 },{ 172, 255, 0 }, { 168, 255, 0 },{ 165, 255, 0 },{ 161, 255, 0 },{ 157, 255, 0 },{ 153, 255, 0 }, { 149, 255, 0 },{ 145, 255, 0 },{ 142, 255, 0 },{ 138, 255, 0 },{ 134, 255, 0 }, { 130, 255, 0 },{ 126, 255, 0 },{ 123, 255, 0 },{ 119, 255, 0 },{ 115, 255, 0 }, { 111, 255, 0 },{ 107, 255, 0 },{ 103, 255, 0 },{ 100, 255, 0 },{ 96, 255, 0 }, { 92, 255, 0 },{ 88, 255, 0 },{ 84, 255, 0 },{ 80, 255, 0 },{ 77, 255, 0 }, { 73, 255, 0 },{ 69, 255, 0 },{ 65, 255, 0 },{ 61, 255, 0 },{ 57, 255, 0 }, { 54, 255, 0 },{ 50, 255, 0 },{ 46, 255, 0 },{ 42, 255, 0 },{ 38, 255, 0 }, { 34, 255, 0 },{ 31, 255, 0 },{ 27, 255, 0 },{ 23, 255, 0 },{ 19, 255, 0 }, { 15, 255, 0 },{ 11, 255, 0 },{ 8, 255, 0 },{ 4, 255, 0 },{ 0, 255, 0 } }; const rgb_t vga_colormap[1000] = { { 255, 255, 255 },{ 254, 254, 254 },{ 253, 253, 253 },{ 252, 252, 252 },{ 251, 251, 251 }, { 250, 250, 250 },{ 249, 249, 249 },{ 248, 248, 248 },{ 247, 247, 247 },{ 246, 246, 246 }, { 245, 245, 245 },{ 244, 244, 244 },{ 244, 244, 244 },{ 243, 243, 243 },{ 242, 242, 242 }, { 241, 241, 241 },{ 240, 240, 240 },{ 239, 239, 239 },{ 238, 238, 238 },{ 237, 237, 237 }, { 236, 236, 236 },{ 235, 235, 235 },{ 234, 234, 234 },{ 233, 233, 233 },{ 232, 232, 232 }, { 231, 231, 231 },{ 230, 230, 230 },{ 229, 229, 229 },{ 228, 228, 228 },{ 227, 227, 227 }, { 226, 226, 226 },{ 225, 225, 225 },{ 224, 224, 224 },{ 223, 223, 223 },{ 222, 222, 222 }, { 221, 221, 221 },{ 221, 221, 221 },{ 220, 220, 220 },{ 219, 219, 219 },{ 218, 218, 218 }, { 217, 217, 217 },{ 216, 216, 216 },{ 215, 215, 215 },{ 214, 214, 214 },{ 213, 213, 213 }, { 212, 212, 212 },{ 211, 211, 211 },{ 210, 210, 210 },{ 209, 209, 209 },{ 208, 208, 208 }, { 207, 207, 207 },{ 206, 206, 206 },{ 205, 205, 205 },{ 204, 204, 204 },{ 203, 203, 203 }, { 202, 202, 202 },{ 201, 201, 201 },{ 200, 200, 200 },{ 199, 199, 199 },{ 199, 199, 199 }, { 198, 198, 198 },{ 197, 197, 197 },{ 196, 196, 196 },{ 195, 195, 195 },{ 194, 194, 194 }, { 193, 193, 193 },{ 192, 192, 192 },{ 192, 190, 190 },{ 193, 187, 187 },{ 194, 184, 184 }, { 195, 181, 181 },{ 195, 179, 179 },{ 196, 176, 176 },{ 197, 173, 173 },{ 198, 170, 170 }, { 199, 167, 167 },{ 200, 164, 164 },{ 201, 161, 161 },{ 202, 159, 159 },{ 203, 156, 156 }, { 204, 153, 153 },{ 205, 150, 150 },{ 206, 147, 147 },{ 207, 144, 144 },{ 208, 141, 141 }, { 209, 138, 138 },{ 210, 136, 136 },{ 211, 133, 133 },{ 212, 130, 130 },{ 213, 127, 127 }, { 214, 124, 124 },{ 215, 121, 121 },{ 216, 118, 118 },{ 217, 115, 115 },{ 217, 113, 113 }, { 218, 110, 110 },{ 219, 107, 107 },{ 220, 104, 104 },{ 221, 101, 101 },{ 222, 98, 98 }, { 223, 95, 95 },{ 224, 92, 92 },{ 225, 90, 90 },{ 226, 87, 87 },{ 227, 84, 84 }, { 228, 81, 81 },{ 229, 78, 78 },{ 230, 75, 75 },{ 231, 72, 72 },{ 232, 69, 69 }, { 233, 67, 67 },{ 234, 64, 64 },{ 235, 61, 61 },{ 236, 58, 58 },{ 237, 55, 55 }, { 238, 52, 52 },{ 239, 49, 49 },{ 239, 47, 47 },{ 240, 44, 44 },{ 241, 41, 41 }, { 242, 38, 38 },{ 243, 35, 35 },{ 244, 32, 32 },{ 245, 29, 29 },{ 246, 26, 26 }, { 247, 24, 24 },{ 248, 21, 21 },{ 249, 18, 18 },{ 250, 15, 15 },{ 251, 12, 12 }, { 252, 9, 9 },{ 253, 6, 6 },{ 254, 3, 3 },{ 255, 1, 1 },{ 255, 3, 0 }, { 255, 7, 0 },{ 255, 11, 0 },{ 255, 15, 0 },{ 255, 18, 0 },{ 255, 22, 0 }, { 255, 26, 0 },{ 255, 30, 0 },{ 255, 34, 0 },{ 255, 38, 0 },{ 255, 41, 0 }, { 255, 45, 0 },{ 255, 49, 0 },{ 255, 53, 0 },{ 255, 57, 0 },{ 255, 60, 0 }, { 255, 64, 0 },{ 255, 68, 0 },{ 255, 72, 0 },{ 255, 76, 0 },{ 255, 80, 0 }, { 255, 83, 0 },{ 255, 87, 0 },{ 255, 91, 0 },{ 255, 95, 0 },{ 255, 99, 0 }, { 255, 103, 0 },{ 255, 106, 0 },{ 255, 110, 0 },{ 255, 114, 0 },{ 255, 118, 0 }, { 255, 122, 0 },{ 255, 126, 0 },{ 255, 129, 0 },{ 255, 133, 0 },{ 255, 137, 0 }, { 255, 141, 0 },{ 255, 145, 0 },{ 255, 149, 0 },{ 255, 152, 0 },{ 255, 156, 0 }, { 255, 160, 0 },{ 255, 164, 0 },{ 255, 168, 0 },{ 255, 172, 0 },{ 255, 175, 0 }, { 255, 179, 0 },{ 255, 183, 0 },{ 255, 187, 0 },{ 255, 191, 0 },{ 255, 195, 0 }, { 255, 198, 0 },{ 255, 202, 0 },{ 255, 206, 0 },{ 255, 210, 0 },{ 255, 214, 0 }, { 255, 217, 0 },{ 255, 221, 0 },{ 255, 225, 0 },{ 255, 229, 0 },{ 255, 233, 0 }, { 255, 237, 0 },{ 255, 240, 0 },{ 255, 244, 0 },{ 255, 248, 0 },{ 255, 252, 0 }, { 254, 255, 0 },{ 250, 255, 0 },{ 247, 255, 0 },{ 243, 255, 0 },{ 239, 255, 0 }, { 235, 255, 0 },{ 231, 255, 0 },{ 227, 255, 0 },{ 224, 255, 0 },{ 220, 255, 0 }, { 216, 255, 0 },{ 212, 255, 0 },{ 208, 255, 0 },{ 204, 255, 0 },{ 201, 255, 0 }, { 197, 255, 0 },{ 193, 255, 0 },{ 189, 255, 0 },{ 185, 255, 0 },{ 181, 255, 0 }, { 178, 255, 0 },{ 174, 255, 0 },{ 170, 255, 0 },{ 166, 255, 0 },{ 162, 255, 0 }, { 159, 255, 0 },{ 155, 255, 0 },{ 151, 255, 0 },{ 147, 255, 0 },{ 143, 255, 0 }, { 139, 255, 0 },{ 136, 255, 0 },{ 132, 255, 0 },{ 128, 255, 0 },{ 124, 255, 0 }, { 120, 255, 0 },{ 116, 255, 0 },{ 113, 255, 0 },{ 109, 255, 0 },{ 105, 255, 0 }, { 101, 255, 0 },{ 97, 255, 0 },{ 93, 255, 0 },{ 90, 255, 0 },{ 86, 255, 0 }, { 82, 255, 0 },{ 78, 255, 0 },{ 74, 255, 0 },{ 70, 255, 0 },{ 67, 255, 0 }, { 63, 255, 0 },{ 59, 255, 0 },{ 55, 255, 0 },{ 51, 255, 0 },{ 47, 255, 0 }, { 44, 255, 0 },{ 40, 255, 0 },{ 36, 255, 0 },{ 32, 255, 0 },{ 28, 255, 0 }, { 25, 255, 0 },{ 21, 255, 0 },{ 17, 255, 0 },{ 13, 255, 0 },{ 9, 255, 0 }, { 5, 255, 0 },{ 2, 255, 0 },{ 0, 255, 2 },{ 0, 255, 6 },{ 0, 255, 10 }, { 0, 255, 14 },{ 0, 255, 18 },{ 0, 255, 21 },{ 0, 255, 25 },{ 0, 255, 29 }, { 0, 255, 33 },{ 0, 255, 37 },{ 0, 255, 41 },{ 0, 255, 44 },{ 0, 255, 48 }, { 0, 255, 52 },{ 0, 255, 56 },{ 0, 255, 60 },{ 0, 255, 64 },{ 0, 255, 67 }, { 0, 255, 71 },{ 0, 255, 75 },{ 0, 255, 79 },{ 0, 255, 83 },{ 0, 255, 87 }, { 0, 255, 90 },{ 0, 255, 94 },{ 0, 255, 98 },{ 0, 255, 102 },{ 0, 255, 106 }, { 0, 255, 110 },{ 0, 255, 113 },{ 0, 255, 117 },{ 0, 255, 121 },{ 0, 255, 125 }, { 0, 255, 129 },{ 0, 255, 132 },{ 0, 255, 136 },{ 0, 255, 140 },{ 0, 255, 144 }, { 0, 255, 148 },{ 0, 255, 152 },{ 0, 255, 155 },{ 0, 255, 159 },{ 0, 255, 163 }, { 0, 255, 167 },{ 0, 255, 171 },{ 0, 255, 175 },{ 0, 255, 178 },{ 0, 255, 182 }, { 0, 255, 186 },{ 0, 255, 190 },{ 0, 255, 194 },{ 0, 255, 198 },{ 0, 255, 201 }, { 0, 255, 205 },{ 0, 255, 209 },{ 0, 255, 213 },{ 0, 255, 217 },{ 0, 255, 221 }, { 0, 255, 224 },{ 0, 255, 228 },{ 0, 255, 232 },{ 0, 255, 236 },{ 0, 255, 240 }, { 0, 255, 244 },{ 0, 255, 247 },{ 0, 255, 251 },{ 0, 255, 255 },{ 0, 251, 255 }, { 0, 247, 255 },{ 0, 244, 255 },{ 0, 240, 255 },{ 0, 236, 255 },{ 0, 232, 255 }, { 0, 228, 255 },{ 0, 224, 255 },{ 0, 221, 255 },{ 0, 217, 255 },{ 0, 213, 255 }, { 0, 209, 255 },{ 0, 205, 255 },{ 0, 201, 255 },{ 0, 198, 255 },{ 0, 194, 255 }, { 0, 190, 255 },{ 0, 186, 255 },{ 0, 182, 255 },{ 0, 178, 255 },{ 0, 175, 255 }, { 0, 171, 255 },{ 0, 167, 255 },{ 0, 163, 255 },{ 0, 159, 255 },{ 0, 155, 255 }, { 0, 152, 255 },{ 0, 148, 255 },{ 0, 144, 255 },{ 0, 140, 255 },{ 0, 136, 255 }, { 0, 132, 255 },{ 0, 129, 255 },{ 0, 125, 255 },{ 0, 121, 255 },{ 0, 117, 255 }, { 0, 113, 255 },{ 0, 110, 255 },{ 0, 106, 255 },{ 0, 102, 255 },{ 0, 98, 255 }, { 0, 94, 255 },{ 0, 90, 255 },{ 0, 87, 255 },{ 0, 83, 255 },{ 0, 79, 255 }, { 0, 75, 255 },{ 0, 71, 255 },{ 0, 67, 255 },{ 0, 64, 255 },{ 0, 60, 255 }, { 0, 56, 255 },{ 0, 52, 255 },{ 0, 48, 255 },{ 0, 44, 255 },{ 0, 41, 255 }, { 0, 37, 255 },{ 0, 33, 255 },{ 0, 29, 255 },{ 0, 25, 255 },{ 0, 21, 255 }, { 0, 18, 255 },{ 0, 14, 255 },{ 0, 10, 255 },{ 0, 6, 255 },{ 0, 2, 255 }, { 2, 0, 255 },{ 5, 0, 255 },{ 9, 0, 255 },{ 13, 0, 255 },{ 17, 0, 255 }, { 21, 0, 255 },{ 25, 0, 255 },{ 28, 0, 255 },{ 32, 0, 255 },{ 36, 0, 255 }, { 40, 0, 255 },{ 44, 0, 255 },{ 47, 0, 255 },{ 51, 0, 255 },{ 55, 0, 255 }, { 59, 0, 255 },{ 63, 0, 255 },{ 67, 0, 255 },{ 70, 0, 255 },{ 74, 0, 255 }, { 78, 0, 255 },{ 82, 0, 255 },{ 86, 0, 255 },{ 90, 0, 255 },{ 93, 0, 255 }, { 97, 0, 255 },{ 101, 0, 255 },{ 105, 0, 255 },{ 109, 0, 255 },{ 113, 0, 255 }, { 116, 0, 255 },{ 120, 0, 255 },{ 124, 0, 255 },{ 128, 0, 255 },{ 132, 0, 255 }, { 136, 0, 255 },{ 139, 0, 255 },{ 143, 0, 255 },{ 147, 0, 255 },{ 151, 0, 255 }, { 155, 0, 255 },{ 159, 0, 255 },{ 162, 0, 255 },{ 166, 0, 255 },{ 170, 0, 255 }, { 174, 0, 255 },{ 178, 0, 255 },{ 181, 0, 255 },{ 185, 0, 255 },{ 189, 0, 255 }, { 193, 0, 255 },{ 197, 0, 255 },{ 201, 0, 255 },{ 204, 0, 255 },{ 208, 0, 255 }, { 212, 0, 255 },{ 216, 0, 255 },{ 220, 0, 255 },{ 224, 0, 255 },{ 227, 0, 255 }, { 231, 0, 255 },{ 235, 0, 255 },{ 239, 0, 255 },{ 243, 0, 255 },{ 247, 0, 255 }, { 250, 0, 255 },{ 254, 0, 255 },{ 252, 0, 252 },{ 248, 0, 248 },{ 244, 0, 244 }, { 240, 0, 240 },{ 237, 0, 237 },{ 233, 0, 233 },{ 229, 0, 229 },{ 225, 0, 225 }, { 221, 0, 221 },{ 217, 0, 217 },{ 214, 0, 214 },{ 210, 0, 210 },{ 206, 0, 206 }, { 202, 0, 202 },{ 198, 0, 198 },{ 195, 0, 195 },{ 191, 0, 191 },{ 187, 0, 187 }, { 183, 0, 183 },{ 179, 0, 179 },{ 175, 0, 175 },{ 172, 0, 172 },{ 168, 0, 168 }, { 164, 0, 164 },{ 160, 0, 160 },{ 156, 0, 156 },{ 152, 0, 152 },{ 149, 0, 149 }, { 145, 0, 145 },{ 141, 0, 141 },{ 137, 0, 137 },{ 133, 0, 133 },{ 129, 0, 129 }, { 126, 0, 126 },{ 122, 0, 122 },{ 118, 0, 118 },{ 114, 0, 114 },{ 110, 0, 110 }, { 106, 0, 106 },{ 103, 0, 103 },{ 99, 0, 99 },{ 95, 0, 95 },{ 91, 0, 91 }, { 87, 0, 87 },{ 83, 0, 83 },{ 80, 0, 80 },{ 76, 0, 76 },{ 72, 0, 72 }, { 68, 0, 68 },{ 64, 0, 64 },{ 60, 0, 60 },{ 57, 0, 57 },{ 53, 0, 53 }, { 49, 0, 49 },{ 45, 0, 45 },{ 41, 0, 41 },{ 38, 0, 38 },{ 34, 0, 34 }, { 30, 0, 30 },{ 26, 0, 26 },{ 22, 0, 22 },{ 18, 0, 18 },{ 15, 0, 15 }, { 11, 0, 11 },{ 7, 0, 7 },{ 3, 0, 3 },{ 0, 0, 0 },{ 2, 2, 2 }, { 4, 4, 4 },{ 6, 6, 6 },{ 8, 8, 8 },{ 10, 10, 10 },{ 12, 12, 12 }, { 14, 14, 14 },{ 16, 16, 16 },{ 18, 18, 18 },{ 20, 20, 20 },{ 21, 21, 21 }, { 23, 23, 23 },{ 25, 25, 25 },{ 27, 27, 27 },{ 29, 29, 29 },{ 31, 31, 31 }, { 33, 33, 33 },{ 35, 35, 35 },{ 37, 37, 37 },{ 39, 39, 39 },{ 41, 41, 41 }, { 43, 43, 43 },{ 44, 44, 44 },{ 46, 46, 46 },{ 48, 48, 48 },{ 50, 50, 50 }, { 52, 52, 52 },{ 54, 54, 54 },{ 56, 56, 56 },{ 58, 58, 58 },{ 60, 60, 60 }, { 62, 62, 62 },{ 64, 64, 64 },{ 65, 65, 65 },{ 67, 67, 67 },{ 69, 69, 69 }, { 71, 71, 71 },{ 73, 73, 73 },{ 75, 75, 75 },{ 77, 77, 77 },{ 79, 79, 79 }, { 81, 81, 81 },{ 83, 83, 83 },{ 85, 85, 85 },{ 87, 87, 87 },{ 88, 88, 88 }, { 90, 90, 90 },{ 92, 92, 92 },{ 94, 94, 94 },{ 96, 96, 96 },{ 98, 98, 98 }, { 100, 100, 100 },{ 102, 102, 102 },{ 104, 104, 104 },{ 106, 106, 106 },{ 108, 108, 108 }, { 110, 110, 110 },{ 111, 111, 111 },{ 113, 113, 113 },{ 115, 115, 115 },{ 117, 117, 117 }, { 119, 119, 119 },{ 121, 121, 121 },{ 123, 123, 123 },{ 125, 125, 125 },{ 127, 127, 127 }, { 128, 126, 126 },{ 128, 124, 124 },{ 128, 123, 123 },{ 128, 121, 121 },{ 128, 119, 119 }, { 128, 117, 117 },{ 128, 115, 115 },{ 128, 113, 113 },{ 128, 111, 111 },{ 128, 109, 109 }, { 128, 107, 107 },{ 128, 105, 105 },{ 128, 103, 103 },{ 128, 101, 101 },{ 128, 100, 100 }, { 128, 98, 98 },{ 128, 96, 96 },{ 128, 94, 94 },{ 128, 92, 92 },{ 128, 90, 90 }, { 128, 88, 88 },{ 128, 86, 86 },{ 128, 84, 84 },{ 128, 82, 82 },{ 128, 80, 80 }, { 128, 78, 78 },{ 128, 77, 77 },{ 128, 75, 75 },{ 128, 73, 73 },{ 128, 71, 71 }, { 128, 69, 69 },{ 128, 67, 67 },{ 128, 65, 65 },{ 128, 63, 63 },{ 128, 61, 61 }, { 128, 59, 59 },{ 128, 57, 57 },{ 128, 56, 56 },{ 128, 54, 54 },{ 128, 52, 52 }, { 128, 50, 50 },{ 128, 48, 48 },{ 128, 46, 46 },{ 128, 44, 44 },{ 128, 42, 42 }, { 128, 40, 40 },{ 128, 38, 38 },{ 128, 36, 36 },{ 128, 34, 34 },{ 128, 33, 33 }, { 128, 31, 31 },{ 128, 29, 29 },{ 128, 27, 27 },{ 128, 25, 25 },{ 128, 23, 23 }, { 128, 21, 21 },{ 128, 19, 19 },{ 128, 17, 17 },{ 128, 15, 15 },{ 128, 13, 13 }, { 128, 11, 11 },{ 128, 10, 10 },{ 128, 8, 8 },{ 128, 6, 6 },{ 128, 4, 4 }, { 128, 2, 2 },{ 128, 0, 0 },{ 128, 2, 0 },{ 128, 4, 0 },{ 128, 6, 0 }, { 128, 8, 0 },{ 128, 10, 0 },{ 128, 11, 0 },{ 128, 13, 0 },{ 128, 15, 0 }, { 128, 17, 0 },{ 128, 19, 0 },{ 128, 21, 0 },{ 128, 23, 0 },{ 128, 25, 0 }, { 128, 27, 0 },{ 128, 29, 0 },{ 128, 31, 0 },{ 128, 33, 0 },{ 128, 34, 0 }, { 128, 36, 0 },{ 128, 38, 0 },{ 128, 40, 0 },{ 128, 42, 0 },{ 128, 44, 0 }, { 128, 46, 0 },{ 128, 48, 0 },{ 128, 50, 0 },{ 128, 52, 0 },{ 128, 54, 0 }, { 128, 56, 0 },{ 128, 57, 0 },{ 128, 59, 0 },{ 128, 61, 0 },{ 128, 63, 0 }, { 128, 65, 0 },{ 128, 67, 0 },{ 128, 69, 0 },{ 128, 71, 0 },{ 128, 73, 0 }, { 128, 75, 0 },{ 128, 77, 0 },{ 128, 78, 0 },{ 128, 80, 0 },{ 128, 82, 0 }, { 128, 84, 0 },{ 128, 86, 0 },{ 128, 88, 0 },{ 128, 90, 0 },{ 128, 92, 0 }, { 128, 94, 0 },{ 128, 96, 0 },{ 128, 98, 0 },{ 128, 100, 0 },{ 128, 101, 0 }, { 128, 103, 0 },{ 128, 105, 0 },{ 128, 107, 0 },{ 128, 109, 0 },{ 128, 111, 0 }, { 128, 113, 0 },{ 128, 115, 0 },{ 128, 117, 0 },{ 128, 119, 0 },{ 128, 121, 0 }, { 128, 123, 0 },{ 128, 124, 0 },{ 128, 126, 0 },{ 127, 128, 0 },{ 125, 128, 0 }, { 123, 128, 0 },{ 121, 128, 0 },{ 119, 128, 0 },{ 117, 128, 0 },{ 115, 128, 0 }, { 113, 128, 0 },{ 111, 128, 0 },{ 110, 128, 0 },{ 108, 128, 0 },{ 106, 128, 0 }, { 104, 128, 0 },{ 102, 128, 0 },{ 100, 128, 0 },{ 98, 128, 0 },{ 96, 128, 0 }, { 94, 128, 0 },{ 92, 128, 0 },{ 90, 128, 0 },{ 88, 128, 0 },{ 87, 128, 0 }, { 85, 128, 0 },{ 83, 128, 0 },{ 81, 128, 0 },{ 79, 128, 0 },{ 77, 128, 0 }, { 75, 128, 0 },{ 73, 128, 0 },{ 71, 128, 0 },{ 69, 128, 0 },{ 67, 128, 0 }, { 65, 128, 0 },{ 64, 128, 0 },{ 62, 128, 0 },{ 60, 128, 0 },{ 58, 128, 0 }, { 56, 128, 0 },{ 54, 128, 0 },{ 52, 128, 0 },{ 50, 128, 0 },{ 48, 128, 0 }, { 46, 128, 0 },{ 44, 128, 0 },{ 43, 128, 0 },{ 41, 128, 0 },{ 39, 128, 0 }, { 37, 128, 0 },{ 35, 128, 0 },{ 33, 128, 0 },{ 31, 128, 0 },{ 29, 128, 0 }, { 27, 128, 0 },{ 25, 128, 0 },{ 23, 128, 0 },{ 21, 128, 0 },{ 20, 128, 0 }, { 18, 128, 0 },{ 16, 128, 0 },{ 14, 128, 0 },{ 12, 128, 0 },{ 10, 128, 0 }, { 8, 128, 0 },{ 6, 128, 0 },{ 4, 128, 0 },{ 2, 128, 0 },{ 0, 128, 0 }, { 0, 128, 2 },{ 0, 128, 3 },{ 0, 128, 5 },{ 0, 128, 7 },{ 0, 128, 9 }, { 0, 128, 11 },{ 0, 128, 13 },{ 0, 128, 15 },{ 0, 128, 17 },{ 0, 128, 19 }, { 0, 128, 21 },{ 0, 128, 23 },{ 0, 128, 25 },{ 0, 128, 26 },{ 0, 128, 28 }, { 0, 128, 30 },{ 0, 128, 32 },{ 0, 128, 34 },{ 0, 128, 36 },{ 0, 128, 38 }, { 0, 128, 40 },{ 0, 128, 42 },{ 0, 128, 44 },{ 0, 128, 46 },{ 0, 128, 47 }, { 0, 128, 49 },{ 0, 128, 51 },{ 0, 128, 53 },{ 0, 128, 55 },{ 0, 128, 57 }, { 0, 128, 59 },{ 0, 128, 61 },{ 0, 128, 63 },{ 0, 128, 65 },{ 0, 128, 67 }, { 0, 128, 69 },{ 0, 128, 70 },{ 0, 128, 72 },{ 0, 128, 74 },{ 0, 128, 76 }, { 0, 128, 78 },{ 0, 128, 80 },{ 0, 128, 82 },{ 0, 128, 84 },{ 0, 128, 86 }, { 0, 128, 88 },{ 0, 128, 90 },{ 0, 128, 92 },{ 0, 128, 93 },{ 0, 128, 95 }, { 0, 128, 97 },{ 0, 128, 99 },{ 0, 128, 101 },{ 0, 128, 103 },{ 0, 128, 105 }, { 0, 128, 107 },{ 0, 128, 109 },{ 0, 128, 111 },{ 0, 128, 113 },{ 0, 128, 114 }, { 0, 128, 116 },{ 0, 128, 118 },{ 0, 128, 120 },{ 0, 128, 122 },{ 0, 128, 124 }, { 0, 128, 126 },{ 0, 127, 128 },{ 0, 125, 128 },{ 0, 123, 128 },{ 0, 121, 128 }, { 0, 119, 128 },{ 0, 118, 128 },{ 0, 116, 128 },{ 0, 114, 128 },{ 0, 112, 128 }, { 0, 110, 128 },{ 0, 108, 128 },{ 0, 106, 128 },{ 0, 104, 128 },{ 0, 102, 128 }, { 0, 100, 128 },{ 0, 98, 128 },{ 0, 96, 128 },{ 0, 95, 128 },{ 0, 93, 128 }, { 0, 91, 128 },{ 0, 89, 128 },{ 0, 87, 128 },{ 0, 85, 128 },{ 0, 83, 128 }, { 0, 81, 128 },{ 0, 79, 128 },{ 0, 77, 128 },{ 0, 75, 128 },{ 0, 74, 128 }, { 0, 72, 128 },{ 0, 70, 128 },{ 0, 68, 128 },{ 0, 66, 128 },{ 0, 64, 128 }, { 0, 62, 128 },{ 0, 60, 128 },{ 0, 58, 128 },{ 0, 56, 128 },{ 0, 54, 128 }, { 0, 52, 128 },{ 0, 51, 128 },{ 0, 49, 128 },{ 0, 47, 128 },{ 0, 45, 128 }, { 0, 43, 128 },{ 0, 41, 128 },{ 0, 39, 128 },{ 0, 37, 128 },{ 0, 35, 128 }, { 0, 33, 128 },{ 0, 31, 128 },{ 0, 29, 128 },{ 0, 28, 128 },{ 0, 26, 128 }, { 0, 24, 128 },{ 0, 22, 128 },{ 0, 20, 128 },{ 0, 18, 128 },{ 0, 16, 128 }, { 0, 14, 128 },{ 0, 12, 128 },{ 0, 10, 128 },{ 0, 8, 128 },{ 0, 7, 128 }, { 0, 5, 128 },{ 0, 3, 128 },{ 0, 1, 128 },{ 1, 0, 128 },{ 3, 0, 128 }, { 5, 0, 128 },{ 7, 0, 128 },{ 9, 0, 128 },{ 11, 0, 128 },{ 13, 0, 128 }, { 15, 0, 128 },{ 16, 0, 128 },{ 18, 0, 128 },{ 20, 0, 128 },{ 22, 0, 128 }, { 24, 0, 128 },{ 26, 0, 128 },{ 28, 0, 128 },{ 30, 0, 128 },{ 32, 0, 128 }, { 34, 0, 128 },{ 36, 0, 128 },{ 38, 0, 128 },{ 39, 0, 128 },{ 41, 0, 128 }, { 43, 0, 128 },{ 45, 0, 128 },{ 47, 0, 128 },{ 49, 0, 128 },{ 51, 0, 128 }, { 53, 0, 128 },{ 55, 0, 128 },{ 57, 0, 128 },{ 59, 0, 128 },{ 60, 0, 128 }, { 62, 0, 128 },{ 64, 0, 128 },{ 66, 0, 128 },{ 68, 0, 128 },{ 70, 0, 128 }, { 72, 0, 128 },{ 74, 0, 128 },{ 76, 0, 128 },{ 78, 0, 128 },{ 80, 0, 128 }, { 82, 0, 128 },{ 83, 0, 128 },{ 85, 0, 128 },{ 87, 0, 128 },{ 89, 0, 128 }, { 91, 0, 128 },{ 93, 0, 128 },{ 95, 0, 128 },{ 97, 0, 128 },{ 99, 0, 128 }, { 101, 0, 128 },{ 103, 0, 128 },{ 105, 0, 128 },{ 106, 0, 128 },{ 108, 0, 128 }, { 110, 0, 128 },{ 112, 0, 128 },{ 114, 0, 128 },{ 116, 0, 128 },{ 118, 0, 128 }, { 120, 0, 128 },{ 122, 0, 128 },{ 124, 0, 128 },{ 126, 0, 128 },{ 128, 0, 128 } }; const rgb_t yarg_colormap[1000] = { { 0, 0, 0 },{ 0, 0, 0 },{ 1, 1, 1 },{ 1, 1, 1 },{ 1, 1, 1 }, { 1, 1, 1 },{ 2, 2, 2 },{ 2, 2, 2 },{ 2, 2, 2 },{ 2, 2, 2 }, { 3, 3, 3 },{ 3, 3, 3 },{ 3, 3, 3 },{ 3, 3, 3 },{ 4, 4, 4 }, { 4, 4, 4 },{ 4, 4, 4 },{ 4, 4, 4 },{ 5, 5, 5 },{ 5, 5, 5 }, { 5, 5, 5 },{ 5, 5, 5 },{ 6, 6, 6 },{ 6, 6, 6 },{ 6, 6, 6 }, { 6, 6, 6 },{ 7, 7, 7 },{ 7, 7, 7 },{ 7, 7, 7 },{ 7, 7, 7 }, { 8, 8, 8 },{ 8, 8, 8 },{ 8, 8, 8 },{ 8, 8, 8 },{ 9, 9, 9 }, { 9, 9, 9 },{ 9, 9, 9 },{ 9, 9, 9 },{ 10, 10, 10 },{ 10, 10, 10 }, { 10, 10, 10 },{ 10, 10, 10 },{ 11, 11, 11 },{ 11, 11, 11 },{ 11, 11, 11 }, { 11, 11, 11 },{ 12, 12, 12 },{ 12, 12, 12 },{ 12, 12, 12 },{ 13, 13, 13 }, { 13, 13, 13 },{ 13, 13, 13 },{ 13, 13, 13 },{ 14, 14, 14 },{ 14, 14, 14 }, { 14, 14, 14 },{ 14, 14, 14 },{ 15, 15, 15 },{ 15, 15, 15 },{ 15, 15, 15 }, { 15, 15, 15 },{ 16, 16, 16 },{ 16, 16, 16 },{ 16, 16, 16 },{ 16, 16, 16 }, { 17, 17, 17 },{ 17, 17, 17 },{ 17, 17, 17 },{ 17, 17, 17 },{ 18, 18, 18 }, { 18, 18, 18 },{ 18, 18, 18 },{ 18, 18, 18 },{ 19, 19, 19 },{ 19, 19, 19 }, { 19, 19, 19 },{ 19, 19, 19 },{ 20, 20, 20 },{ 20, 20, 20 },{ 20, 20, 20 }, { 20, 20, 20 },{ 21, 21, 21 },{ 21, 21, 21 },{ 21, 21, 21 },{ 21, 21, 21 }, { 22, 22, 22 },{ 22, 22, 22 },{ 22, 22, 22 },{ 22, 22, 22 },{ 23, 23, 23 }, { 23, 23, 23 },{ 23, 23, 23 },{ 23, 23, 23 },{ 24, 24, 24 },{ 24, 24, 24 }, { 24, 24, 24 },{ 25, 25, 25 },{ 25, 25, 25 },{ 25, 25, 25 },{ 25, 25, 25 }, { 26, 26, 26 },{ 26, 26, 26 },{ 26, 26, 26 },{ 26, 26, 26 },{ 27, 27, 27 }, { 27, 27, 27 },{ 27, 27, 27 },{ 27, 27, 27 },{ 28, 28, 28 },{ 28, 28, 28 }, { 28, 28, 28 },{ 28, 28, 28 },{ 29, 29, 29 },{ 29, 29, 29 },{ 29, 29, 29 }, { 29, 29, 29 },{ 30, 30, 30 },{ 30, 30, 30 },{ 30, 30, 30 },{ 30, 30, 30 }, { 31, 31, 31 },{ 31, 31, 31 },{ 31, 31, 31 },{ 31, 31, 31 },{ 32, 32, 32 }, { 32, 32, 32 },{ 32, 32, 32 },{ 32, 32, 32 },{ 33, 33, 33 },{ 33, 33, 33 }, { 33, 33, 33 },{ 33, 33, 33 },{ 34, 34, 34 },{ 34, 34, 34 },{ 34, 34, 34 }, { 34, 34, 34 },{ 35, 35, 35 },{ 35, 35, 35 },{ 35, 35, 35 },{ 35, 35, 35 }, { 36, 36, 36 },{ 36, 36, 36 },{ 36, 36, 36 },{ 37, 37, 37 },{ 37, 37, 37 }, { 37, 37, 37 },{ 37, 37, 37 },{ 38, 38, 38 },{ 38, 38, 38 },{ 38, 38, 38 }, { 38, 38, 38 },{ 39, 39, 39 },{ 39, 39, 39 },{ 39, 39, 39 },{ 39, 39, 39 }, { 40, 40, 40 },{ 40, 40, 40 },{ 40, 40, 40 },{ 40, 40, 40 },{ 41, 41, 41 }, { 41, 41, 41 },{ 41, 41, 41 },{ 41, 41, 41 },{ 42, 42, 42 },{ 42, 42, 42 }, { 42, 42, 42 },{ 42, 42, 42 },{ 43, 43, 43 },{ 43, 43, 43 },{ 43, 43, 43 }, { 43, 43, 43 },{ 44, 44, 44 },{ 44, 44, 44 },{ 44, 44, 44 },{ 44, 44, 44 }, { 45, 45, 45 },{ 45, 45, 45 },{ 45, 45, 45 },{ 45, 45, 45 },{ 46, 46, 46 }, { 46, 46, 46 },{ 46, 46, 46 },{ 46, 46, 46 },{ 47, 47, 47 },{ 47, 47, 47 }, { 47, 47, 47 },{ 47, 47, 47 },{ 48, 48, 48 },{ 48, 48, 48 },{ 48, 48, 48 }, { 48, 48, 48 },{ 49, 49, 49 },{ 49, 49, 49 },{ 49, 49, 49 },{ 50, 50, 50 }, { 50, 50, 50 },{ 50, 50, 50 },{ 50, 50, 50 },{ 51, 51, 51 },{ 51, 51, 51 }, { 51, 51, 51 },{ 51, 51, 51 },{ 52, 52, 52 },{ 52, 52, 52 },{ 52, 52, 52 }, { 52, 52, 52 },{ 53, 53, 53 },{ 53, 53, 53 },{ 53, 53, 53 },{ 53, 53, 53 }, { 54, 54, 54 },{ 54, 54, 54 },{ 54, 54, 54 },{ 54, 54, 54 },{ 55, 55, 55 }, { 55, 55, 55 },{ 55, 55, 55 },{ 55, 55, 55 },{ 56, 56, 56 },{ 56, 56, 56 }, { 56, 56, 56 },{ 56, 56, 56 },{ 57, 57, 57 },{ 57, 57, 57 },{ 57, 57, 57 }, { 57, 57, 57 },{ 58, 58, 58 },{ 58, 58, 58 },{ 58, 58, 58 },{ 58, 58, 58 }, { 59, 59, 59 },{ 59, 59, 59 },{ 59, 59, 59 },{ 59, 59, 59 },{ 60, 60, 60 }, { 60, 60, 60 },{ 60, 60, 60 },{ 60, 60, 60 },{ 61, 61, 61 },{ 61, 61, 61 }, { 61, 61, 61 },{ 62, 62, 62 },{ 62, 62, 62 },{ 62, 62, 62 },{ 62, 62, 62 }, { 63, 63, 63 },{ 63, 63, 63 },{ 63, 63, 63 },{ 63, 63, 63 },{ 64, 64, 64 }, { 64, 64, 64 },{ 64, 64, 64 },{ 64, 64, 64 },{ 65, 65, 65 },{ 65, 65, 65 }, { 65, 65, 65 },{ 65, 65, 65 },{ 66, 66, 66 },{ 66, 66, 66 },{ 66, 66, 66 }, { 66, 66, 66 },{ 67, 67, 67 },{ 67, 67, 67 },{ 67, 67, 67 },{ 67, 67, 67 }, { 68, 68, 68 },{ 68, 68, 68 },{ 68, 68, 68 },{ 68, 68, 68 },{ 69, 69, 69 }, { 69, 69, 69 },{ 69, 69, 69 },{ 69, 69, 69 },{ 70, 70, 70 },{ 70, 70, 70 }, { 70, 70, 70 },{ 70, 70, 70 },{ 71, 71, 71 },{ 71, 71, 71 },{ 71, 71, 71 }, { 71, 71, 71 },{ 72, 72, 72 },{ 72, 72, 72 },{ 72, 72, 72 },{ 72, 72, 72 }, { 73, 73, 73 },{ 73, 73, 73 },{ 73, 73, 73 },{ 74, 74, 74 },{ 74, 74, 74 }, { 74, 74, 74 },{ 74, 74, 74 },{ 75, 75, 75 },{ 75, 75, 75 },{ 75, 75, 75 }, { 75, 75, 75 },{ 76, 76, 76 },{ 76, 76, 76 },{ 76, 76, 76 },{ 76, 76, 76 }, { 77, 77, 77 },{ 77, 77, 77 },{ 77, 77, 77 },{ 77, 77, 77 },{ 78, 78, 78 }, { 78, 78, 78 },{ 78, 78, 78 },{ 78, 78, 78 },{ 79, 79, 79 },{ 79, 79, 79 }, { 79, 79, 79 },{ 79, 79, 79 },{ 80, 80, 80 },{ 80, 80, 80 },{ 80, 80, 80 }, { 80, 80, 80 },{ 81, 81, 81 },{ 81, 81, 81 },{ 81, 81, 81 },{ 81, 81, 81 }, { 82, 82, 82 },{ 82, 82, 82 },{ 82, 82, 82 },{ 82, 82, 82 },{ 83, 83, 83 }, { 83, 83, 83 },{ 83, 83, 83 },{ 83, 83, 83 },{ 84, 84, 84 },{ 84, 84, 84 }, { 84, 84, 84 },{ 84, 84, 84 },{ 85, 85, 85 },{ 85, 85, 85 },{ 85, 85, 85 }, { 86, 86, 86 },{ 86, 86, 86 },{ 86, 86, 86 },{ 86, 86, 86 },{ 87, 87, 87 }, { 87, 87, 87 },{ 87, 87, 87 },{ 87, 87, 87 },{ 88, 88, 88 },{ 88, 88, 88 }, { 88, 88, 88 },{ 88, 88, 88 },{ 89, 89, 89 },{ 89, 89, 89 },{ 89, 89, 89 }, { 89, 89, 89 },{ 90, 90, 90 },{ 90, 90, 90 },{ 90, 90, 90 },{ 90, 90, 90 }, { 91, 91, 91 },{ 91, 91, 91 },{ 91, 91, 91 },{ 91, 91, 91 },{ 92, 92, 92 }, { 92, 92, 92 },{ 92, 92, 92 },{ 92, 92, 92 },{ 93, 93, 93 },{ 93, 93, 93 }, { 93, 93, 93 },{ 93, 93, 93 },{ 94, 94, 94 },{ 94, 94, 94 },{ 94, 94, 94 }, { 94, 94, 94 },{ 95, 95, 95 },{ 95, 95, 95 },{ 95, 95, 95 },{ 95, 95, 95 }, { 96, 96, 96 },{ 96, 96, 96 },{ 96, 96, 96 },{ 96, 96, 96 },{ 97, 97, 97 }, { 97, 97, 97 },{ 97, 97, 97 },{ 98, 98, 98 },{ 98, 98, 98 },{ 98, 98, 98 }, { 98, 98, 98 },{ 99, 99, 99 },{ 99, 99, 99 },{ 99, 99, 99 },{ 99, 99, 99 }, { 100, 100, 100 },{ 100, 100, 100 },{ 100, 100, 100 },{ 100, 100, 100 },{ 101, 101, 101 }, { 101, 101, 101 },{ 101, 101, 101 },{ 101, 101, 101 },{ 102, 102, 102 },{ 102, 102, 102 }, { 102, 102, 102 },{ 102, 102, 102 },{ 103, 103, 103 },{ 103, 103, 103 },{ 103, 103, 103 }, { 103, 103, 103 },{ 104, 104, 104 },{ 104, 104, 104 },{ 104, 104, 104 },{ 104, 104, 104 }, { 105, 105, 105 },{ 105, 105, 105 },{ 105, 105, 105 },{ 105, 105, 105 },{ 106, 106, 106 }, { 106, 106, 106 },{ 106, 106, 106 },{ 106, 106, 106 },{ 107, 107, 107 },{ 107, 107, 107 }, { 107, 107, 107 },{ 107, 107, 107 },{ 108, 108, 108 },{ 108, 108, 108 },{ 108, 108, 108 }, { 108, 108, 108 },{ 109, 109, 109 },{ 109, 109, 109 },{ 109, 109, 109 },{ 110, 110, 110 }, { 110, 110, 110 },{ 110, 110, 110 },{ 110, 110, 110 },{ 111, 111, 111 },{ 111, 111, 111 }, { 111, 111, 111 },{ 111, 111, 111 },{ 112, 112, 112 },{ 112, 112, 112 },{ 112, 112, 112 }, { 112, 112, 112 },{ 113, 113, 113 },{ 113, 113, 113 },{ 113, 113, 113 },{ 113, 113, 113 }, { 114, 114, 114 },{ 114, 114, 114 },{ 114, 114, 114 },{ 114, 114, 114 },{ 115, 115, 115 }, { 115, 115, 115 },{ 115, 115, 115 },{ 115, 115, 115 },{ 116, 116, 116 },{ 116, 116, 116 }, { 116, 116, 116 },{ 116, 116, 116 },{ 117, 117, 117 },{ 117, 117, 117 },{ 117, 117, 117 }, { 117, 117, 117 },{ 118, 118, 118 },{ 118, 118, 118 },{ 118, 118, 118 },{ 118, 118, 118 }, { 119, 119, 119 },{ 119, 119, 119 },{ 119, 119, 119 },{ 119, 119, 119 },{ 120, 120, 120 }, { 120, 120, 120 },{ 120, 120, 120 },{ 120, 120, 120 },{ 121, 121, 121 },{ 121, 121, 121 }, { 121, 121, 121 },{ 122, 122, 122 },{ 122, 122, 122 },{ 122, 122, 122 },{ 122, 122, 122 }, { 123, 123, 123 },{ 123, 123, 123 },{ 123, 123, 123 },{ 123, 123, 123 },{ 124, 124, 124 }, { 124, 124, 124 },{ 124, 124, 124 },{ 124, 124, 124 },{ 125, 125, 125 },{ 125, 125, 125 }, { 125, 125, 125 },{ 125, 125, 125 },{ 126, 126, 126 },{ 126, 126, 126 },{ 126, 126, 126 }, { 126, 126, 126 },{ 127, 127, 127 },{ 127, 127, 127 },{ 127, 127, 127 },{ 127, 127, 127 }, { 128, 128, 128 },{ 128, 128, 128 },{ 128, 128, 128 },{ 128, 128, 128 },{ 129, 129, 129 }, { 129, 129, 129 },{ 129, 129, 129 },{ 129, 129, 129 },{ 130, 130, 130 },{ 130, 130, 130 }, { 130, 130, 130 },{ 130, 130, 130 },{ 131, 131, 131 },{ 131, 131, 131 },{ 131, 131, 131 }, { 131, 131, 131 },{ 132, 132, 132 },{ 132, 132, 132 },{ 132, 132, 132 },{ 132, 132, 132 }, { 133, 133, 133 },{ 133, 133, 133 },{ 133, 133, 133 },{ 133, 133, 133 },{ 134, 134, 134 }, { 134, 134, 134 },{ 134, 134, 134 },{ 135, 135, 135 },{ 135, 135, 135 },{ 135, 135, 135 }, { 135, 135, 135 },{ 136, 136, 136 },{ 136, 136, 136 },{ 136, 136, 136 },{ 136, 136, 136 }, { 137, 137, 137 },{ 137, 137, 137 },{ 137, 137, 137 },{ 137, 137, 137 },{ 138, 138, 138 }, { 138, 138, 138 },{ 138, 138, 138 },{ 138, 138, 138 },{ 139, 139, 139 },{ 139, 139, 139 }, { 139, 139, 139 },{ 139, 139, 139 },{ 140, 140, 140 },{ 140, 140, 140 },{ 140, 140, 140 }, { 140, 140, 140 },{ 141, 141, 141 },{ 141, 141, 141 },{ 141, 141, 141 },{ 141, 141, 141 }, { 142, 142, 142 },{ 142, 142, 142 },{ 142, 142, 142 },{ 142, 142, 142 },{ 143, 143, 143 }, { 143, 143, 143 },{ 143, 143, 143 },{ 143, 143, 143 },{ 144, 144, 144 },{ 144, 144, 144 }, { 144, 144, 144 },{ 144, 144, 144 },{ 145, 145, 145 },{ 145, 145, 145 },{ 145, 145, 145 }, { 145, 145, 145 },{ 146, 146, 146 },{ 146, 146, 146 },{ 146, 146, 146 },{ 147, 147, 147 }, { 147, 147, 147 },{ 147, 147, 147 },{ 147, 147, 147 },{ 148, 148, 148 },{ 148, 148, 148 }, { 148, 148, 148 },{ 148, 148, 148 },{ 149, 149, 149 },{ 149, 149, 149 },{ 149, 149, 149 }, { 149, 149, 149 },{ 150, 150, 150 },{ 150, 150, 150 },{ 150, 150, 150 },{ 150, 150, 150 }, { 151, 151, 151 },{ 151, 151, 151 },{ 151, 151, 151 },{ 151, 151, 151 },{ 152, 152, 152 }, { 152, 152, 152 },{ 152, 152, 152 },{ 152, 152, 152 },{ 153, 153, 153 },{ 153, 153, 153 }, { 153, 153, 153 },{ 153, 153, 153 },{ 154, 154, 154 },{ 154, 154, 154 },{ 154, 154, 154 }, { 154, 154, 154 },{ 155, 155, 155 },{ 155, 155, 155 },{ 155, 155, 155 },{ 155, 155, 155 }, { 156, 156, 156 },{ 156, 156, 156 },{ 156, 156, 156 },{ 156, 156, 156 },{ 157, 157, 157 }, { 157, 157, 157 },{ 157, 157, 157 },{ 157, 157, 157 },{ 158, 158, 158 },{ 158, 158, 158 }, { 158, 158, 158 },{ 159, 159, 159 },{ 159, 159, 159 },{ 159, 159, 159 },{ 159, 159, 159 }, { 160, 160, 160 },{ 160, 160, 160 },{ 160, 160, 160 },{ 160, 160, 160 },{ 161, 161, 161 }, { 161, 161, 161 },{ 161, 161, 161 },{ 161, 161, 161 },{ 162, 162, 162 },{ 162, 162, 162 }, { 162, 162, 162 },{ 162, 162, 162 },{ 163, 163, 163 },{ 163, 163, 163 },{ 163, 163, 163 }, { 163, 163, 163 },{ 164, 164, 164 },{ 164, 164, 164 },{ 164, 164, 164 },{ 164, 164, 164 }, { 165, 165, 165 },{ 165, 165, 165 },{ 165, 165, 165 },{ 165, 165, 165 },{ 166, 166, 166 }, { 166, 166, 166 },{ 166, 166, 166 },{ 166, 166, 166 },{ 167, 167, 167 },{ 167, 167, 167 }, { 167, 167, 167 },{ 167, 167, 167 },{ 168, 168, 168 },{ 168, 168, 168 },{ 168, 168, 168 }, { 168, 168, 168 },{ 169, 169, 169 },{ 169, 169, 169 },{ 169, 169, 169 },{ 169, 169, 169 }, { 170, 170, 170 },{ 170, 170, 170 },{ 170, 170, 170 },{ 171, 171, 171 },{ 171, 171, 171 }, { 171, 171, 171 },{ 171, 171, 171 },{ 172, 172, 172 },{ 172, 172, 172 },{ 172, 172, 172 }, { 172, 172, 172 },{ 173, 173, 173 },{ 173, 173, 173 },{ 173, 173, 173 },{ 173, 173, 173 }, { 174, 174, 174 },{ 174, 174, 174 },{ 174, 174, 174 },{ 174, 174, 174 },{ 175, 175, 175 }, { 175, 175, 175 },{ 175, 175, 175 },{ 175, 175, 175 },{ 176, 176, 176 },{ 176, 176, 176 }, { 176, 176, 176 },{ 176, 176, 176 },{ 177, 177, 177 },{ 177, 177, 177 },{ 177, 177, 177 }, { 177, 177, 177 },{ 178, 178, 178 },{ 178, 178, 178 },{ 178, 178, 178 },{ 178, 178, 178 }, { 179, 179, 179 },{ 179, 179, 179 },{ 179, 179, 179 },{ 179, 179, 179 },{ 180, 180, 180 }, { 180, 180, 180 },{ 180, 180, 180 },{ 180, 180, 180 },{ 181, 181, 181 },{ 181, 181, 181 }, { 181, 181, 181 },{ 181, 181, 181 },{ 182, 182, 182 },{ 182, 182, 182 },{ 182, 182, 182 }, { 183, 183, 183 },{ 183, 183, 183 },{ 183, 183, 183 },{ 183, 183, 183 },{ 184, 184, 184 }, { 184, 184, 184 },{ 184, 184, 184 },{ 184, 184, 184 },{ 185, 185, 185 },{ 185, 185, 185 }, { 185, 185, 185 },{ 185, 185, 185 },{ 186, 186, 186 },{ 186, 186, 186 },{ 186, 186, 186 }, { 186, 186, 186 },{ 187, 187, 187 },{ 187, 187, 187 },{ 187, 187, 187 },{ 187, 187, 187 }, { 188, 188, 188 },{ 188, 188, 188 },{ 188, 188, 188 },{ 188, 188, 188 },{ 189, 189, 189 }, { 189, 189, 189 },{ 189, 189, 189 },{ 189, 189, 189 },{ 190, 190, 190 },{ 190, 190, 190 }, { 190, 190, 190 },{ 190, 190, 190 },{ 191, 191, 191 },{ 191, 191, 191 },{ 191, 191, 191 }, { 191, 191, 191 },{ 192, 192, 192 },{ 192, 192, 192 },{ 192, 192, 192 },{ 192, 192, 192 }, { 193, 193, 193 },{ 193, 193, 193 },{ 193, 193, 193 },{ 193, 193, 193 },{ 194, 194, 194 }, { 194, 194, 194 },{ 194, 194, 194 },{ 195, 195, 195 },{ 195, 195, 195 },{ 195, 195, 195 }, { 195, 195, 195 },{ 196, 196, 196 },{ 196, 196, 196 },{ 196, 196, 196 },{ 196, 196, 196 }, { 197, 197, 197 },{ 197, 197, 197 },{ 197, 197, 197 },{ 197, 197, 197 },{ 198, 198, 198 }, { 198, 198, 198 },{ 198, 198, 198 },{ 198, 198, 198 },{ 199, 199, 199 },{ 199, 199, 199 }, { 199, 199, 199 },{ 199, 199, 199 },{ 200, 200, 200 },{ 200, 200, 200 },{ 200, 200, 200 }, { 200, 200, 200 },{ 201, 201, 201 },{ 201, 201, 201 },{ 201, 201, 201 },{ 201, 201, 201 }, { 202, 202, 202 },{ 202, 202, 202 },{ 202, 202, 202 },{ 202, 202, 202 },{ 203, 203, 203 }, { 203, 203, 203 },{ 203, 203, 203 },{ 203, 203, 203 },{ 204, 204, 204 },{ 204, 204, 204 }, { 204, 204, 204 },{ 204, 204, 204 },{ 205, 205, 205 },{ 205, 205, 205 },{ 205, 205, 205 }, { 205, 205, 205 },{ 206, 206, 206 },{ 206, 206, 206 },{ 206, 206, 206 },{ 207, 207, 207 }, { 207, 207, 207 },{ 207, 207, 207 },{ 207, 207, 207 },{ 208, 208, 208 },{ 208, 208, 208 }, { 208, 208, 208 },{ 208, 208, 208 },{ 209, 209, 209 },{ 209, 209, 209 },{ 209, 209, 209 }, { 209, 209, 209 },{ 210, 210, 210 },{ 210, 210, 210 },{ 210, 210, 210 },{ 210, 210, 210 }, { 211, 211, 211 },{ 211, 211, 211 },{ 211, 211, 211 },{ 211, 211, 211 },{ 212, 212, 212 }, { 212, 212, 212 },{ 212, 212, 212 },{ 212, 212, 212 },{ 213, 213, 213 },{ 213, 213, 213 }, { 213, 213, 213 },{ 213, 213, 213 },{ 214, 214, 214 },{ 214, 214, 214 },{ 214, 214, 214 }, { 214, 214, 214 },{ 215, 215, 215 },{ 215, 215, 215 },{ 215, 215, 215 },{ 215, 215, 215 }, { 216, 216, 216 },{ 216, 216, 216 },{ 216, 216, 216 },{ 216, 216, 216 },{ 217, 217, 217 }, { 217, 217, 217 },{ 217, 217, 217 },{ 217, 217, 217 },{ 218, 218, 218 },{ 218, 218, 218 }, { 218, 218, 218 },{ 218, 218, 218 },{ 219, 219, 219 },{ 219, 219, 219 },{ 219, 219, 219 }, { 220, 220, 220 },{ 220, 220, 220 },{ 220, 220, 220 },{ 220, 220, 220 },{ 221, 221, 221 }, { 221, 221, 221 },{ 221, 221, 221 },{ 221, 221, 221 },{ 222, 222, 222 },{ 222, 222, 222 }, { 222, 222, 222 },{ 222, 222, 222 },{ 223, 223, 223 },{ 223, 223, 223 },{ 223, 223, 223 }, { 223, 223, 223 },{ 224, 224, 224 },{ 224, 224, 224 },{ 224, 224, 224 },{ 224, 224, 224 }, { 225, 225, 225 },{ 225, 225, 225 },{ 225, 225, 225 },{ 225, 225, 225 },{ 226, 226, 226 }, { 226, 226, 226 },{ 226, 226, 226 },{ 226, 226, 226 },{ 227, 227, 227 },{ 227, 227, 227 }, { 227, 227, 227 },{ 227, 227, 227 },{ 228, 228, 228 },{ 228, 228, 228 },{ 228, 228, 228 }, { 228, 228, 228 },{ 229, 229, 229 },{ 229, 229, 229 },{ 229, 229, 229 },{ 229, 229, 229 }, { 230, 230, 230 },{ 230, 230, 230 },{ 230, 230, 230 },{ 230, 230, 230 },{ 231, 231, 231 }, { 231, 231, 231 },{ 231, 231, 231 },{ 232, 232, 232 },{ 232, 232, 232 },{ 232, 232, 232 }, { 232, 232, 232 },{ 233, 233, 233 },{ 233, 233, 233 },{ 233, 233, 233 },{ 233, 233, 233 }, { 234, 234, 234 },{ 234, 234, 234 },{ 234, 234, 234 },{ 234, 234, 234 },{ 235, 235, 235 }, { 235, 235, 235 },{ 235, 235, 235 },{ 235, 235, 235 },{ 236, 236, 236 },{ 236, 236, 236 }, { 236, 236, 236 },{ 236, 236, 236 },{ 237, 237, 237 },{ 237, 237, 237 },{ 237, 237, 237 }, { 237, 237, 237 },{ 238, 238, 238 },{ 238, 238, 238 },{ 238, 238, 238 },{ 238, 238, 238 }, { 239, 239, 239 },{ 239, 239, 239 },{ 239, 239, 239 },{ 239, 239, 239 },{ 240, 240, 240 }, { 240, 240, 240 },{ 240, 240, 240 },{ 240, 240, 240 },{ 241, 241, 241 },{ 241, 241, 241 }, { 241, 241, 241 },{ 241, 241, 241 },{ 242, 242, 242 },{ 242, 242, 242 },{ 242, 242, 242 }, { 242, 242, 242 },{ 243, 243, 243 },{ 243, 243, 243 },{ 243, 243, 243 },{ 244, 244, 244 }, { 244, 244, 244 },{ 244, 244, 244 },{ 244, 244, 244 },{ 245, 245, 245 },{ 245, 245, 245 }, { 245, 245, 245 },{ 245, 245, 245 },{ 246, 246, 246 },{ 246, 246, 246 },{ 246, 246, 246 }, { 246, 246, 246 },{ 247, 247, 247 },{ 247, 247, 247 },{ 247, 247, 247 },{ 247, 247, 247 }, { 248, 248, 248 },{ 248, 248, 248 },{ 248, 248, 248 },{ 248, 248, 248 },{ 249, 249, 249 }, { 249, 249, 249 },{ 249, 249, 249 },{ 249, 249, 249 },{ 250, 250, 250 },{ 250, 250, 250 }, { 250, 250, 250 },{ 250, 250, 250 },{ 251, 251, 251 },{ 251, 251, 251 },{ 251, 251, 251 }, { 251, 251, 251 },{ 252, 252, 252 },{ 252, 252, 252 },{ 252, 252, 252 },{ 252, 252, 252 }, { 253, 253, 253 },{ 253, 253, 253 },{ 253, 253, 253 },{ 253, 253, 253 },{ 254, 254, 254 }, { 254, 254, 254 },{ 254, 254, 254 },{ 254, 254, 254 },{ 255, 255, 255 },{ 255, 255, 255 } }; }} //namespace // clang-format on #endif
AirSim/AirLib/include/common/common_utils/bitmap_image.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/bitmap_image.hpp", "repo_id": "AirSim", "token_count": 126395 }
10
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_World_hpp #define airsim_core_World_hpp #include <functional> #include "common/Common.hpp" #include "common/UpdatableContainer.hpp" #include "PhysicsEngineBase.hpp" #include "PhysicsBody.hpp" #include "common/common_utils/ScheduledExecutor.hpp" #include "common/ClockFactory.hpp" namespace msr { namespace airlib { class World : public UpdatableContainer<UpdatableObject*> { public: World(std::unique_ptr<PhysicsEngineBase> physics_engine) : physics_engine_(std::move(physics_engine)) { World::clear(); setName("World"); physics_engine_->setParent(this); if (physics_engine) physics_engine_->clear(); } //override updatable interface so we can synchronize physics engine //*** Start: UpdatableState implementation ***// virtual void resetImplementation() override { UpdatableContainer::resetImplementation(); if (physics_engine_) physics_engine_->reset(); } virtual void update() override { ClockFactory::get()->step(); //first update our objects UpdatableContainer::update(); //now update kinematics state if (physics_engine_) physics_engine_->update(); } virtual void reportState(StateReporter& reporter) override { reporter.writeValue("Sleep", 1.0f / executor_.getSleepTimeAvg()); if (physics_engine_) physics_engine_->reportState(reporter); //call base UpdatableContainer::reportState(reporter); } //*** End: UpdatableState implementation ***// //override membership modification methods so we can synchronize physics engine virtual void clear() override { if (physics_engine_) physics_engine_->clear(); UpdatableContainer::clear(); } virtual void insert(UpdatableObject* member) override { if (physics_engine_ && member->getPhysicsBody() != nullptr) physics_engine_->insert(static_cast<PhysicsBody*>(member->getPhysicsBody())); UpdatableContainer::insert(member); } virtual void erase_remove(UpdatableObject* member) override { if (physics_engine_ && member->getPhysicsBody() != nullptr) physics_engine_->erase_remove(static_cast<PhysicsBody*>( member->getPhysicsBody())); UpdatableContainer::erase_remove(member); } //async updater thread void startAsyncUpdator(uint64_t period) { //TODO: probably we shouldn't be passing around fixed period executor_.initialize(std::bind(&World::worldUpdatorAsync, this, std::placeholders::_1), period); executor_.start(); } void stopAsyncUpdator() { executor_.stop(); } void lock() { executor_.lock(); } void unlock() { executor_.unlock(); } virtual ~World() { executor_.stop(); } void pause(bool is_paused) { executor_.pause(is_paused); } bool isPaused() const { return executor_.isPaused(); } void pauseForTime(double seconds) { executor_.pauseForTime(seconds); } void continueForTime(double seconds) { executor_.continueForTime(seconds); } void continueForFrames(uint32_t frames) { executor_.continueForFrames(frames); } void setFrameNumber(uint32_t frameNumber) { executor_.setFrameNumber(frameNumber); } private: bool worldUpdatorAsync(uint64_t dt_nanos) { unused(dt_nanos); try { update(); } catch (const std::exception& ex) { //Utils::DebugBreak(); Utils::log(Utils::stringf("Exception occurred while updating world: %s", ex.what()), Utils::kLogLevelError); } catch (...) { //Utils::DebugBreak(); Utils::log("Exception occurred while updating world", Utils::kLogLevelError); } return true; } private: std::unique_ptr<PhysicsEngineBase> physics_engine_ = nullptr; common_utils::ScheduledExecutor executor_; }; } } //namespace #endif
AirSim/AirLib/include/physics/World.hpp/0
{ "file_path": "AirSim/AirLib/include/physics/World.hpp", "repo_id": "AirSim", "token_count": 2264 }
11
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_Gps_hpp #define msr_airlib_Gps_hpp #include <random> #include "common/Common.hpp" #include "GpsSimpleParams.hpp" #include "GpsBase.hpp" #include "common/FirstOrderFilter.hpp" #include "common/FrequencyLimiter.hpp" #include "common/DelayLine.hpp" namespace msr { namespace airlib { class GpsSimple : public GpsBase { public: //methods GpsSimple(const AirSimSettings::GpsSetting& setting = AirSimSettings::GpsSetting()) : GpsBase(setting.sensor_name) { // initialize params params_.initializeFromSettings(setting); //initialize frequency limiter freq_limiter_.initialize(params_.update_frequency, params_.startup_delay); delay_line_.initialize(params_.update_latency); //initialize filters eph_filter.initialize(params_.eph_time_constant, params_.eph_final, params_.eph_initial); //starting dilution set to 100 which we will reduce over time to targeted 0.3f, with 45% accuracy within 100 updates, each update occurring at 0.2s interval epv_filter.initialize(params_.epv_time_constant, params_.epv_final, params_.epv_initial); } //*** Start: UpdatableState implementation ***// virtual void resetImplementation() override { freq_limiter_.reset(); delay_line_.reset(); eph_filter.reset(); epv_filter.reset(); addOutputToDelayLine(eph_filter.getOutput(), epv_filter.getOutput()); } virtual void update() override { GpsBase::update(); freq_limiter_.update(); eph_filter.update(); epv_filter.update(); if (freq_limiter_.isWaitComplete()) { //update output addOutputToDelayLine(eph_filter.getOutput(), epv_filter.getOutput()); } delay_line_.update(); if (freq_limiter_.isWaitComplete()) setOutput(delay_line_.getOutput()); } //*** End: UpdatableState implementation ***// virtual ~GpsSimple() = default; private: void addOutputToDelayLine(real_T eph, real_T epv) { Output output; const GroundTruth& ground_truth = getGroundTruth(); //GNSS output.gnss.time_utc = static_cast<uint64_t>(clock()->nowNanos() / 1.0E3); output.gnss.geo_point = ground_truth.environment->getState().geo_point; output.gnss.eph = eph; output.gnss.epv = epv; output.gnss.velocity = ground_truth.kinematics->twist.linear; output.is_valid = true; output.gnss.fix_type = output.gnss.eph <= params_.eph_min_3d ? GnssFixType::GNSS_FIX_3D_FIX : output.gnss.eph <= params_.eph_min_2d ? GnssFixType::GNSS_FIX_2D_FIX : GnssFixType::GNSS_FIX_NO_FIX; output.time_stamp = clock()->nowNanos(); delay_line_.push_back(output); } private: typedef std::normal_distribution<> NormalDistribution; GpsSimpleParams params_; FirstOrderFilter<real_T> eph_filter, epv_filter; FrequencyLimiter freq_limiter_; DelayLine<Output> delay_line_; }; } } //namespace #endif
AirSim/AirLib/include/sensors/gps/GpsSimple.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/gps/GpsSimple.hpp", "repo_id": "AirSim", "token_count": 1594 }
12
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_ArduRoverCarController_hpp #define msr_airlib_ArduRoverCarController_hpp #include "vehicles/car/api/CarApiBase.hpp" #include "sensors/SensorCollection.hpp" #include "common/Common.hpp" #include "common/AirSimSettings.hpp" // Sensors #include "sensors/imu/ImuBase.hpp" #include "sensors/gps/GpsBase.hpp" #include "sensors/magnetometer/MagnetometerBase.hpp" #include "sensors/barometer/BarometerBase.hpp" #include "sensors/distance/DistanceSimple.hpp" #include "sensors/lidar/LidarSimple.hpp" #include "UdpSocket.hpp" #include <sstream> namespace msr { namespace airlib { class ArduRoverApi : public CarApiBase { public: ArduRoverApi(const AirSimSettings::VehicleSetting* vehicle_setting, std::shared_ptr<SensorFactory> sensor_factory, const Kinematics::State& state, const Environment& environment) : CarApiBase(vehicle_setting, sensor_factory, state, environment), home_geopoint_(environment.getHomeGeoPoint()) { connection_info_ = static_cast<const AirSimSettings::MavLinkVehicleSetting*>(vehicle_setting)->connection_info; sensors_ = &getSensors(); connect(); } ~ArduRoverApi() { closeConnections(); } protected: virtual void resetImplementation() override { CarApiBase::resetImplementation(); } public: // Update sensor data & send to Ardupilot virtual void update() override { CarApiBase::update(); sendSensors(); recvRoverControl(); } virtual const SensorCollection& getSensors() const override { return CarApiBase::getSensors(); } // TODO: VehicleApiBase implementation virtual bool isApiControlEnabled() const override { // Return true so that CarPawnSim gets control message from external firmware and not keyboard return true; } virtual void enableApiControl(bool is_enabled) override { Utils::log("enableApiControl() - Not Implemented", Utils::kLogLevelInfo); unused(is_enabled); } virtual bool armDisarm(bool arm) override { Utils::log("armDisarm() - Not Implemented", Utils::kLogLevelInfo); unused(arm); return false; } virtual GeoPoint getHomeGeoPoint() const override { return home_geopoint_; } virtual void getStatusMessages(std::vector<std::string>& messages) override { unused(messages); } public: virtual void setCarControls(const CarControls& controls) override { // Currently ArduPilot vehicles don't implement AirSim movement APIs unused(controls); } virtual void updateCarState(const CarState& car_state) override { last_car_state_ = car_state; } virtual const CarState& getCarState() const override { return last_car_state_; } virtual const CarControls& getCarControls() const override { return last_controls_; } protected: void closeConnections() { if (udp_socket_ != nullptr) udp_socket_->close(); } void connect() { port_ = static_cast<uint16_t>(connection_info_.udp_port); ip_ = connection_info_.udp_address; closeConnections(); if (ip_ == "") { throw std::invalid_argument("UdpIp setting is invalid."); } if (port_ == 0) { throw std::invalid_argument("UdpPort setting has an invalid value."); } Utils::log(Utils::stringf("Using UDP port %d, local IP %s, remote IP %s for sending sensor data", port_, connection_info_.local_host_ip.c_str(), ip_.c_str()), Utils::kLogLevelInfo); Utils::log(Utils::stringf("Using UDP port %d for receiving rotor power", connection_info_.control_port_local, connection_info_.local_host_ip.c_str(), ip_.c_str()), Utils::kLogLevelInfo); udp_socket_ = std::make_unique<mavlinkcom::UdpSocket>(); udp_socket_->bind(connection_info_.local_host_ip, connection_info_.control_port_local); } private: void recvRoverControl() { // Receive motor data RoverControlMessage pkt; int recv_ret = udp_socket_->recv(&pkt, sizeof(pkt), 100); while (recv_ret != sizeof(pkt)) { if (recv_ret <= 0) { Utils::log(Utils::stringf("Error while receiving rotor control data - ErrorNo: %d", recv_ret), Utils::kLogLevelInfo); } else { Utils::log(Utils::stringf("Received %d bytes instead of %zu bytes", recv_ret, sizeof(pkt)), Utils::kLogLevelInfo); } recv_ret = udp_socket_->recv(&pkt, sizeof(pkt), 100); } last_controls_.throttle = pkt.throttle; last_controls_.steering = pkt.steering; if (pkt.throttle > 0) { last_controls_.is_manual_gear = false; last_controls_.manual_gear = 0; } else { last_controls_.is_manual_gear = true; last_controls_.manual_gear = -1; } } void sendSensors() { if (sensors_ == nullptr || udp_socket_ == nullptr) return; std::ostringstream buf; // Start of JSON element buf << "{"; buf << "\"timestamp\": " << ClockFactory::get()->nowNanos() / 1000 << ","; const auto& imu_output = getImuData(""); buf << "\"imu\": {" << std::fixed << std::setprecision(7) << "\"angular_velocity\": [" << imu_output.angular_velocity[0] << "," << imu_output.angular_velocity[1] << "," << imu_output.angular_velocity[2] << "]" << "," << "\"linear_acceleration\": [" << imu_output.linear_acceleration[0] << "," << imu_output.linear_acceleration[1] << "," << imu_output.linear_acceleration[2] << "]" << "}"; float pitch, roll, yaw; VectorMath::toEulerianAngle(imu_output.orientation, pitch, roll, yaw); buf << "," << "\"pose\": {" << "\"pitch\": " << pitch << "," << "\"roll\": " << roll << "," << "\"yaw\": " << yaw << "}"; const uint count_gps_sensors = sensors_->size(SensorBase::SensorType::Gps); if (count_gps_sensors != 0) { const auto& gps_output = getGpsData(""); buf << "," "\"gps\": {" << std::fixed << std::setprecision(7) << "\"lat\": " << gps_output.gnss.geo_point.latitude << "," << "\"lon\": " << gps_output.gnss.geo_point.longitude << "," << std::setprecision(3) << "\"alt\": " << gps_output.gnss.geo_point.altitude << "}," << "\"velocity\": {" << "\"world_linear_velocity\": [" << gps_output.gnss.velocity[0] << "," << gps_output.gnss.velocity[1] << "," << gps_output.gnss.velocity[2] << "]" "}"; } // Send Distance Sensors data if present const uint count_distance_sensors = sensors_->size(SensorBase::SensorType::Distance); if (count_distance_sensors != 0) { // Start JSON element buf << "," "\"rng\": {" "\"distances\": ["; // More than mm level accuracy isn't needed or used buf << std::fixed << std::setprecision(3); // Used to avoid trailing comma std::string sep = ""; // Add sensor outputs in the array for (uint i = 0; i < count_distance_sensors; ++i) { const auto* distance_sensor = static_cast<const DistanceSimple*>( sensors_->getByType(SensorBase::SensorType::Distance, i)); // Don't send the data if sending to external controller is disabled in settings if (distance_sensor && distance_sensor->getParams().external_controller) { const auto& distance_output = distance_sensor->getOutput(); // AP uses meters so no need to convert here buf << sep << distance_output.distance; sep = ","; } } // Close JSON array & element buf << "]}"; } const uint count_lidars = sensors_->size(SensorBase::SensorType::Lidar); if (count_lidars != 0) { buf << "," "\"lidar\": {" "\"point_cloud\": ["; // More than mm level accuracy isn't needed or used buf << std::fixed << std::setprecision(3); // Add sensor outputs in the array for (uint i = 0; i < count_lidars; ++i) { const auto* lidar = static_cast<const LidarSimple*>(sensors_->getByType(SensorBase::SensorType::Lidar, i)); if (lidar && lidar->getParams().external_controller) { const auto& lidar_output = lidar->getOutput(); std::copy(lidar_output.point_cloud.begin(), lidar_output.point_cloud.end(), std::ostream_iterator<real_T>(buf, ",")); // AP backend only takes in a single Lidar sensor data currently break; } } // Close JSON array & element buf << "]}"; } // End of JSON, AP Parser needs newline buf << "}\n"; // str copy is made since if later on something like - // const char* ptr = buf.str().c_str() // is written, ptr is invalid since buf.str() is a temporary copy // Currently there's no way to get pointer to underlying buffer const std::string sensor_data = buf.str(); udp_socket_->sendto(sensor_data.c_str(), sensor_data.length(), ip_, port_); } private: struct RoverControlMessage { float throttle; float steering; }; AirSimSettings::MavLinkConnectionInfo connection_info_; std::unique_ptr<mavlinkcom::UdpSocket> udp_socket_; uint16_t port_; std::string ip_; const SensorCollection* sensors_; CarControls last_controls_; GeoPoint home_geopoint_; CarState last_car_state_; }; } } // namespace #endif
AirSim/AirLib/include/vehicles/car/firmwares/ardurover/ArduRoverApi.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/car/firmwares/ardurover/ArduRoverApi.hpp", "repo_id": "AirSim", "token_count": 5715 }
13
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_MavLinkDroneController_hpp #define msr_airlib_MavLinkDroneController_hpp #include "MavLinkConnection.hpp" #include "MavLinkMessages.hpp" #include "MavLinkNode.hpp" #include "MavLinkVehicle.hpp" #include "MavLinkVideoStream.hpp" #include <exception> #include <memory> #include <mutex> #include <queue> #include <string> #include <thread> #include <tuple> #include <vector> #include "common/AirSimSettings.hpp" #include "common/Common.hpp" #include "common/CommonStructs.hpp" #include "common/PidController.hpp" #include "common/VectorMath.hpp" #include "common/common_utils/FileSystem.hpp" #include "common/common_utils/SmoothingFilter.hpp" #include "common/common_utils/Timer.hpp" #include "physics/World.hpp" #include "sensors/SensorCollection.hpp" #include "vehicles/multirotor/api/MultirotorApiBase.hpp" //sensors #include "sensors/barometer/BarometerBase.hpp" #include "sensors/distance/DistanceSimple.hpp" #include "sensors/gps/GpsBase.hpp" #include "sensors/imu/ImuBase.hpp" #include "sensors/magnetometer/MagnetometerBase.hpp" namespace msr { namespace airlib { class MavLinkMultirotorApi : public MultirotorApiBase { public: //methods virtual ~MavLinkMultirotorApi() { closeAllConnection(); if (this->connect_thread_.joinable()) { this->connect_thread_.join(); } if (this->telemetry_thread_.joinable()) { this->telemetry_thread_.join(); } } //non-base interface specific to MavLinKDroneController void initialize(const AirSimSettings::MavLinkConnectionInfo& connection_info, const SensorCollection* sensors, bool is_simulation) { connection_info_ = connection_info; sensors_ = sensors; is_simulation_mode_ = is_simulation; lock_step_enabled_ = connection_info.lock_step; try { openAllConnections(); is_ready_ = true; } catch (std::exception& ex) { is_ready_ = false; is_ready_message_ = Utils::stringf("Failed to connect: %s", ex.what()); } } Pose getMocapPose() { std::lock_guard<std::mutex> guard(mocap_pose_mutex_); return mocap_pose_; } virtual const SensorCollection& getSensors() const override { return *sensors_; } //reset PX4 stack virtual void resetImplementation() override { // note this is called AFTER "initialize" when we've connected to the drone // so this method cannot reset any of that connection state. world_ = nullptr; for (UpdatableObject* container = this->getParent(); container != nullptr; container = container->getParent()) { if (container->getName() == "World") { // cool beans! // note: cannot use dynamic_cast because Unreal builds with /GR- for some unknown reason... world_ = static_cast<World*>(container); } } MultirotorApiBase::resetImplementation(); was_reset_ = true; } unsigned long long getSimTime() { // This ensures HIL_SENSOR and HIL_GPS have matching clocks. if (lock_step_active_) { if (sim_time_us_ == 0) { sim_time_us_ = clock()->nowNanos() / 1000; } return sim_time_us_; } else { return clock()->nowNanos() / 1000; } } void advanceTime() { sim_time_us_ = clock()->nowNanos() / 1000; } //update sensors in PX4 stack virtual void update() override { try { auto now = clock()->nowNanos() / 1000; MultirotorApiBase::update(); if (sensors_ == nullptr || !connected_ || connection_ == nullptr || !connection_->isOpen() || !got_first_heartbeat_) return; { std::lock_guard<std::mutex> guard(telemetry_mutex_); update_count_++; } if (lock_step_active_) { if (last_update_time_ + 1000000 < now) { // if 1 second passes then something is terribly wrong, reset lockstep mode lock_step_active_ = false; { std::lock_guard<std::mutex> guard(telemetry_mutex_); lock_step_resets_++; } addStatusMessage("timeout on HilActuatorControlsMessage, resetting lock step mode"); } else if (!received_actuator_controls_) { // drop this one since we are in LOCKSTEP mode and we have not yet received the HilActuatorControlsMessage. return; } } last_update_time_ = now; { std::lock_guard<std::mutex> guard(telemetry_mutex_); hil_sensor_count_++; } advanceTime(); //send sensor updates const auto& imu_output = getImuData(""); const auto& mag_output = getMagnetometerData(""); const auto& baro_output = getBarometerData(""); sendHILSensor(imu_output.linear_acceleration, imu_output.angular_velocity, mag_output.magnetic_field_body, baro_output.pressure * 0.01f /*Pa to Millibar */, baro_output.altitude); sendSystemTime(); const uint count_distance_sensors = getSensors().size(SensorBase::SensorType::Distance); if (count_distance_sensors != 0) { const auto* distance_sensor = static_cast<const DistanceSimple*>( sensors_->getByType(SensorBase::SensorType::Distance)); // Don't send the data if sending to external controller is disabled in settings if (distance_sensor && distance_sensor->getParams().external_controller) { const auto& distance_output = distance_sensor->getOutput(); sendDistanceSensor(distance_output.min_distance * 100, //m -> cm distance_output.max_distance * 100, //m -> cm distance_output.distance * 100, //m-> cm 0, //sensor type: //TODO: allow changing in settings? 77, //sensor id, //TODO: should this be something real? distance_output.relative_pose.orientation); //TODO: convert from radians to degrees? } } const uint count_gps_sensors = getSensors().size(SensorBase::SensorType::Gps); if (count_gps_sensors != 0) { const auto& gps_output = getGpsData(""); //send GPS if (gps_output.is_valid && gps_output.gnss.time_utc > last_gps_time_) { last_gps_time_ = gps_output.gnss.time_utc; Vector3r gps_velocity = gps_output.gnss.velocity; Vector3r gps_velocity_xy = gps_velocity; gps_velocity_xy.z() = 0; float gps_cog; if (Utils::isApproximatelyZero(gps_velocity.y(), 1E-2f) && Utils::isApproximatelyZero(gps_velocity.x(), 1E-2f)) gps_cog = 0; else gps_cog = Utils::radiansToDegrees(atan2(gps_velocity.y(), gps_velocity.x())); if (gps_cog < 0) gps_cog += 360; sendHILGps(gps_output.gnss.geo_point, gps_velocity, gps_velocity_xy.norm(), gps_cog, gps_output.gnss.eph, gps_output.gnss.epv, gps_output.gnss.fix_type, 10); } } auto end = clock()->nowNanos() / 1000; { std::lock_guard<std::mutex> guard(telemetry_mutex_); update_time_ += (end - now); } } catch (std::exception& e) { addStatusMessage("Exception sending messages to vehicle"); addStatusMessage(e.what()); disconnect(); connect(); // re-start a new connection so PX4 can be restarted and AirSim will happily continue on. } //must be done at the end if (was_reset_) was_reset_ = false; } virtual bool isReady(std::string& message) const override { if (!is_ready_ && is_ready_message_.size() > 0) { message = is_ready_message_; } return is_ready_; } virtual bool canArm() const override { return is_ready_ && has_gps_lock_; } //TODO: this method can't be const yet because it clears previous messages virtual void getStatusMessages(std::vector<std::string>& messages) override { updateState(); //clear param messages.clear(); //move messages from private vars to param std::lock_guard<std::mutex> guard(status_text_mutex_); while (!status_messages_.empty()) { messages.push_back(status_messages_.front()); status_messages_.pop(); } } virtual Kinematics::State getKinematicsEstimated() const override { updateState(); Kinematics::State state; //TODO: reduce code duplication in getPosition() etc methods? state.pose.position = Vector3r(current_state_.local_est.pos.x, current_state_.local_est.pos.y, current_state_.local_est.pos.z); state.pose.orientation = VectorMath::toQuaternion(current_state_.attitude.pitch, current_state_.attitude.roll, current_state_.attitude.yaw); state.twist.linear = Vector3r(current_state_.local_est.lin_vel.x, current_state_.local_est.lin_vel.y, current_state_.local_est.lin_vel.z); state.twist.angular = Vector3r(current_state_.attitude.roll_rate, current_state_.attitude.pitch_rate, current_state_.attitude.yaw_rate); state.accelerations.linear = Vector3r(current_state_.local_est.acc.x, current_state_.local_est.acc.y, current_state_.local_est.acc.z); //TODO: how do we get angular acceleration? return state; } virtual bool isApiControlEnabled() const override { return is_api_control_enabled_; } virtual void enableApiControl(bool is_enabled) override { checkValidVehicle(); if (is_enabled) { mav_vehicle_->requestControl(); is_api_control_enabled_ = true; } else { mav_vehicle_->releaseControl(); is_api_control_enabled_ = false; } } virtual Vector3r getPosition() const override { updateState(); return Vector3r(current_state_.local_est.pos.x, current_state_.local_est.pos.y, current_state_.local_est.pos.z); } virtual Vector3r getVelocity() const override { updateState(); return Vector3r(current_state_.local_est.lin_vel.x, current_state_.local_est.lin_vel.y, current_state_.local_est.lin_vel.z); } virtual Quaternionr getOrientation() const override { updateState(); return VectorMath::toQuaternion(current_state_.attitude.pitch, current_state_.attitude.roll, current_state_.attitude.yaw); } virtual LandedState getLandedState() const override { updateState(); return current_state_.controls.landed ? LandedState::Landed : LandedState::Flying; } virtual real_T getActuation(unsigned int rotor_index) const override { if (!is_simulation_mode_) throw std::logic_error("Attempt to read motor controls while not in simulation mode"); std::lock_guard<std::mutex> guard(hil_controls_mutex_); return rotor_controls_[rotor_index]; } virtual size_t getActuatorCount() const override { return RotorControlsCount; } virtual bool armDisarm(bool arm) override { SingleCall lock(this); checkValidVehicle(); bool rc = false; if (arm) { float timeout_sec = 10; waitForHomeLocation(timeout_sec); waitForStableGroundPosition(timeout_sec); } mav_vehicle_->armDisarm(arm).wait(10000, &rc); return rc; } void onArmed() { if (connection_info_.logs.size() > 0 && mav_vehicle_ != nullptr) { auto con = mav_vehicle_->getConnection(); if (con != nullptr) { if (log_ != nullptr) { log_->close(); log_ = nullptr; } try { std::time_t t = std::time(0); // get time now std::tm* now = std::localtime(&t); auto folder = Utils::stringf("%04d-%02d-%02d", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday); auto path = common_utils::FileSystem::ensureFolder(connection_info_.logs, folder); auto filename = Utils::stringf("%02d-%02d-%02d.mavlink", now->tm_hour, now->tm_min, now->tm_sec); auto fullpath = common_utils::FileSystem::combine(path, filename); addStatusMessage(Utils::stringf("Opening log file: %s", fullpath.c_str())); log_file_name_ = fullpath; log_ = std::make_shared<mavlinkcom::MavLinkFileLog>(); log_->openForWriting(fullpath, false); con->startLoggingSendMessage(log_); con->startLoggingReceiveMessage(log_); if (con != connection_) { // log the SITL channel also connection_->startLoggingSendMessage(log_); connection_->startLoggingReceiveMessage(log_); } start_telemtry_thread(); } catch (std::exception& ex) { addStatusMessage(std::string("Opening log file failed: ") + ex.what()); } } } } void onDisarmed() { if (connection_info_.logs.size() > 0 && mav_vehicle_ != nullptr) { auto con = mav_vehicle_->getConnection(); if (con != nullptr) { con->stopLoggingSendMessage(); con->stopLoggingReceiveMessage(); } if (connection_ != nullptr) { connection_->stopLoggingSendMessage(); connection_->stopLoggingReceiveMessage(); } } if (log_ != nullptr) { addStatusMessage(Utils::stringf("Closing log file: %s", log_file_name_.c_str())); log_->close(); log_ = nullptr; } } void waitForHomeLocation(float timeout_sec) { if (!current_state_.home.is_set) { addStatusMessage("Waiting for valid GPS home location..."); if (!waitForFunction([&]() { return current_state_.home.is_set; }, timeout_sec) .isComplete()) { throw VehicleMoveException("Vehicle does not have a valid GPS home location"); } } } void waitForStableGroundPosition(float timeout_sec) { // wait for ground stabilization if (ground_variance_ > GroundTolerance) { addStatusMessage("Waiting for z-position to stabilize..."); if (!waitForFunction([&]() { return ground_variance_ <= GroundTolerance; }, timeout_sec) .isComplete()) { auto msg = Utils::stringf("Ground is not stable, variance is %f", ground_variance_); throw VehicleMoveException(msg); } } } virtual bool takeoff(float timeout_sec) override { SingleCall lock(this); checkValidVehicle(); waitForHomeLocation(timeout_sec); waitForStableGroundPosition(timeout_sec); bool rc = false; auto vec = getPosition(); auto yaw = current_state_.attitude.yaw; float z = vec.z() + getTakeoffZ(); if (!mav_vehicle_->takeoff(z, 0.0f /* pitch */, yaw).wait(static_cast<int>(timeout_sec * 1000), &rc)) { throw VehicleMoveException("TakeOff command - timeout waiting for response"); } if (!rc) { throw VehicleMoveException("TakeOff command rejected by drone"); } if (timeout_sec <= 0) return true; // client doesn't want to wait. return waitForZ(timeout_sec, z, getDistanceAccuracy()); } virtual bool land(float timeout_sec) override { SingleCall lock(this); //TODO: bugbug: really need a downward pointing distance to ground sensor to do this properly, for now //we assume the ground is relatively flat an we are landing roughly at the home altitude. updateState(); checkValidVehicle(); if (current_state_.home.is_set) { bool rc = false; if (!mav_vehicle_->land(current_state_.global_est.pos.lat, current_state_.global_est.pos.lon, current_state_.home.global_pos.alt).wait(10000, &rc)) { throw VehicleMoveException("Landing command - timeout waiting for response from drone"); } else if (!rc) { throw VehicleMoveException("Landing command rejected by drone"); } } else { throw VehicleMoveException("Cannot land safely with out a home position that tells us the home altitude. Could fix this if we hook up a distance to ground sensor..."); } const auto& waiter = waitForFunction([&]() { updateState(); return current_state_.controls.landed; }, timeout_sec); // Wait for landed state (or user cancellation) if (!waiter.isComplete()) { throw VehicleMoveException("Drone hasn't reported a landing state"); } return waiter.isComplete(); } virtual bool goHome(float timeout_sec) override { SingleCall lock(this); checkValidVehicle(); bool rc = false; if (mav_vehicle_ != nullptr && !mav_vehicle_->returnToHome().wait( static_cast<int>(timeout_sec) * 1000, &rc)) { throw VehicleMoveException("goHome - timeout waiting for response from drone"); } return rc; } virtual bool moveToPosition(float x, float y, float z, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead) override { SingleTaskCall lock(this); unused(adaptive_lookahead); unused(lookahead); unused(drivetrain); checkValidVehicle(); // save current manual, cruise, and max velocity parameters bool result = false; mavlinkcom::MavLinkParameter manual_velocity_parameter, cruise_velocity_parameter, max_velocity_parameter; result = mav_vehicle_->getParameter("MPC_VEL_MANUAL").wait(1000, &manual_velocity_parameter); result = result && mav_vehicle_->getParameter("MPC_XY_CRUISE").wait(1000, &cruise_velocity_parameter); result = result && mav_vehicle_->getParameter("MPC_XY_VEL_MAX").wait(1000, &max_velocity_parameter); if (result) { // set max velocity parameter mavlinkcom::MavLinkParameter p; p.name = "MPC_XY_VEL_MAX"; p.value = velocity; mav_vehicle_->setParameter(p).wait(1000, &result); if (result) { const Vector3r& goal_pos = Vector3r(x, y, z); Vector3r goal_dist_vect; float goal_dist; Waiter waiter(getCommandPeriod(), timeout_sec, getCancelToken()); while (!waiter.isComplete()) { goal_dist_vect = getPosition() - goal_pos; const Vector3r& goal_normalized = goal_dist_vect.normalized(); goal_dist = goal_dist_vect.dot(goal_normalized); if (goal_dist > getDistanceAccuracy()) { moveToPositionInternal(goal_pos, yaw_mode); //sleep for rest of the cycle if (!waiter.sleep()) return false; } else { waiter.complete(); } } // reset manual, cruise, and max velocity parameters bool result_temp = false; mav_vehicle_->setParameter(manual_velocity_parameter).wait(1000, &result); mav_vehicle_->setParameter(cruise_velocity_parameter).wait(1000, &result_temp); result = result && result_temp; mav_vehicle_->setParameter(max_velocity_parameter).wait(1000, &result_temp); result = result && result_temp; return result && waiter.isComplete(); } } return result; } virtual bool hover() override { SingleCall lock(this); bool rc = false; checkValidVehicle(); mavlinkcom::AsyncResult<bool> result = mav_vehicle_->loiter(); //auto start_time = std::chrono::system_clock::now(); while (!getCancelToken().isCancelled()) { if (result.wait(100, &rc)) { break; } } return rc; } virtual GeoPoint getHomeGeoPoint() const override { updateState(); if (current_state_.home.is_set) return GeoPoint(current_state_.home.global_pos.lat, current_state_.home.global_pos.lon, current_state_.home.global_pos.alt); else return GeoPoint(Utils::nan<double>(), Utils::nan<double>(), Utils::nan<float>()); } virtual GeoPoint getGpsLocation() const override { updateState(); return GeoPoint(current_state_.global_est.pos.lat, current_state_.global_est.pos.lon, current_state_.global_est.pos.alt); } virtual void sendTelemetry(float last_interval = -1) override { if (connection_ == nullptr || mav_vehicle_ == nullptr) { return; } // This method is called at high frequence from MultirotorPawnSimApi::updateRendering. mavlinkcom::MavLinkTelemetry data; connection_->getTelemetry(data); if (data.messages_received == 0) { if (!hil_message_timer_.started()) { hil_message_timer_.start(); } else if (hil_message_timer_.seconds() > messageReceivedTimeout) { addStatusMessage("not receiving any messages from HIL, please restart your HIL node and try again"); hil_message_timer_.stop(); } } else { hil_message_timer_.stop(); } } void writeTelemetry(float last_interval = -1) { auto proxy = logviewer_proxy_; auto log = log_; if ((logviewer_proxy_ == nullptr && log_ == nullptr)) { return; } mavlinkcom::MavLinkTelemetry data; connection_->getTelemetry(data); // listen to the other mavlink connection also auto mavcon = mav_vehicle_->getConnection(); if (mavcon != connection_) { mavlinkcom::MavLinkTelemetry gcs; mavcon->getTelemetry(gcs); data.handler_microseconds += gcs.handler_microseconds; data.messages_handled += gcs.messages_handled; data.messages_received += gcs.messages_received; data.messages_sent += gcs.messages_sent; if (gcs.messages_received == 0) { if (!gcs_message_timer_.started()) { gcs_message_timer_.start(); } else if (gcs_message_timer_.seconds() > messageReceivedTimeout) { addStatusMessage("not receiving any messages from GCS port, please restart your SITL node and try again"); } } else { gcs_message_timer_.stop(); } } data.render_time = static_cast<int64_t>(last_interval * 1000000); // microseconds { std::lock_guard<std::mutex> guard(telemetry_mutex_); uint32_t average_delay = 0; uint32_t average_update = 0; if (hil_sensor_count_ != 0) { average_delay = actuator_delay_ / hil_sensor_count_; average_update = static_cast<uint32_t>(update_time_ / hil_sensor_count_); } data.update_rate = update_count_; data.sensor_rate = hil_sensor_count_; data.actuation_delay = average_delay; data.lock_step_resets = lock_step_resets_; data.update_time = average_update; // reset the counters we just captured. update_count_ = 0; hil_sensor_count_ = 0; actuator_delay_ = 0; update_time_ = 0; } if (proxy != nullptr) { proxy->sendMessage(data); } if (log != nullptr) { mavlinkcom::MavLinkMessage msg; msg.magic = MAVLINK_STX_MAVLINK1; data.encode(msg); msg.update_checksum(); // disk I/O is unpredictable, so we have to get it out of the update loop // which is why this thread exists. log->write(msg); } } void start_telemtry_thread() { if (this->telemetry_thread_.joinable()) { this->telemetry_thread_.join(); } // reset the counters we use for telemetry. update_count_ = 0; hil_sensor_count_ = 0; actuator_delay_ = 0; this->telemetry_thread_ = std::thread(&MavLinkMultirotorApi::telemtry_thread, this); } void telemtry_thread() { while (log_ != nullptr) { std::this_thread::sleep_for(std::chrono::seconds(1)); writeTelemetry(1); } } virtual float getCommandPeriod() const override { return 1.0f / 50; //1 period of 50hz } virtual float getTakeoffZ() const override { // pick a number, PX4 doesn't have a fixed limit here, but 3 meters is probably safe // enough to get out of the backwash turbulence. Negative due to NED coordinate system. return -3.0f; } virtual float getDistanceAccuracy() const override { return 0.5f; //measured in simulator by firing commands "MoveToLocation -x 0 -y 0" multiple times and looking at distance traveled } protected: //methods virtual void setControllerGains(uint8_t controllerType, const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) override { unused(controllerType); unused(kp); unused(ki); unused(kd); Utils::log("Not Implemented: setControllerGains", Utils::kLogLevelInfo); } virtual void commandMotorPWMs(float front_right_pwm, float front_left_pwm, float rear_right_pwm, float rear_left_pwm) override { unused(front_right_pwm); unused(front_left_pwm); unused(rear_right_pwm); unused(rear_left_pwm); Utils::log("Not Implemented: commandMotorPWMs", Utils::kLogLevelInfo); } virtual void commandRollPitchYawZ(float roll, float pitch, float yaw, float z) override { if (target_height_ != -z) { // these PID values were calculated experimentally using AltHoldCommand n MavLinkTest, this provides the best // control over thrust to achieve minimal over/under shoot in a reasonable amount of time, but it has not // been tested on a real drone outside jMavSim, so it may need recalibrating... thrust_controller_.setPoint(-z, .05f, .005f, 0.09f); target_height_ = -z; } checkValidVehicle(); auto state = mav_vehicle_->getVehicleState(); float thrust = 0.21f + thrust_controller_.control(-state.local_est.pos.z); mav_vehicle_->moveByAttitude(roll, pitch, yaw, 0, 0, 0, thrust); } virtual void commandRollPitchYawrateZ(float roll, float pitch, float yaw_rate, float z) override { if (target_height_ != -z) { thrust_controller_.setPoint(-z, .05f, .005f, 0.09f); target_height_ = -z; } checkValidVehicle(); auto state = mav_vehicle_->getVehicleState(); float thrust = 0.21f + thrust_controller_.control(-state.local_est.pos.z); mav_vehicle_->moveByAttitude(roll, pitch, 0, 0, 0, yaw_rate, thrust); } virtual void commandRollPitchYawThrottle(float roll, float pitch, float yaw, float throttle) override { checkValidVehicle(); mav_vehicle_->moveByAttitude(roll, pitch, yaw, 0, 0, 0, throttle); } virtual void commandRollPitchYawrateThrottle(float roll, float pitch, float yaw_rate, float throttle) override { checkValidVehicle(); mav_vehicle_->moveByAttitude(roll, pitch, 0, 0, 0, yaw_rate, throttle); } virtual void commandAngleRatesZ(float roll_rate, float pitch_rate, float yaw_rate, float z) override { if (target_height_ != -z) { thrust_controller_.setPoint(-z, .05f, .005f, 0.09f); target_height_ = -z; } checkValidVehicle(); auto state = mav_vehicle_->getVehicleState(); float thrust = 0.21f + thrust_controller_.control(-state.local_est.pos.z); mav_vehicle_->moveByAttitude(0, 0, 0, roll_rate, pitch_rate, yaw_rate, thrust); } virtual void commandAngleRatesThrottle(float roll_rate, float pitch_rate, float yaw_rate, float throttle) override { checkValidVehicle(); mav_vehicle_->moveByAttitude(0, 0, 0, roll_rate, pitch_rate, yaw_rate, throttle); } virtual void commandVelocity(float vx, float vy, float vz, const YawMode& yaw_mode) override { checkValidVehicle(); float yaw = yaw_mode.yaw_or_rate * M_PIf / 180; mav_vehicle_->moveByLocalVelocity(vx, vy, vz, !yaw_mode.is_rate, yaw); } virtual void commandVelocityZ(float vx, float vy, float z, const YawMode& yaw_mode) override { checkValidVehicle(); float yaw = yaw_mode.yaw_or_rate * M_PIf / 180; mav_vehicle_->moveByLocalVelocityWithAltHold(vx, vy, z, !yaw_mode.is_rate, yaw); } virtual void commandPosition(float x, float y, float z, const YawMode& yaw_mode) override { checkValidVehicle(); float yaw = yaw_mode.yaw_or_rate * M_PIf / 180; mav_vehicle_->moveToLocalPosition(x, y, z, !yaw_mode.is_rate, yaw); } //TODO: decouple MultirotorApiBase, VehicalParams and SafetyEval virtual const MultirotorApiParams& getMultirotorApiParams() const override { //defaults are good for PX4 generic quadcopter. static const MultirotorApiParams vehicle_params_; return vehicle_params_; } virtual void beforeTask() override { startOffboardMode(); } virtual void afterTask() override { endOffboardMode(); } public: class MavLinkLogViewerLog : public mavlinkcom::MavLinkLog { public: MavLinkLogViewerLog(std::shared_ptr<mavlinkcom::MavLinkNode> proxy) { proxy_ = proxy; } ~MavLinkLogViewerLog() { proxy_ = nullptr; } void write(const mavlinkcom::MavLinkMessage& msg, uint64_t timestamp = 0) override { if (proxy_ != nullptr) { unused(timestamp); mavlinkcom::MavLinkMessage copy; ::memcpy(&copy, &msg, sizeof(mavlinkcom::MavLinkMessage)); try { proxy_->sendMessage(copy); } catch (std::exception&) { failures++; if (failures == 100) { // hmmm, doesn't like the proxy, bad socket perhaps, so stop trying... proxy_ = nullptr; } } } } private: std::shared_ptr<mavlinkcom::MavLinkNode> proxy_; int failures = 0; }; protected: //methods virtual void connect() { if (!connecting_) { connecting_ = true; if (this->connect_thread_.joinable()) { this->connect_thread_.join(); } this->connect_thread_ = std::thread(&MavLinkMultirotorApi::connect_thread, this); } } virtual void disconnect() { addStatusMessage("Disconnecting mavlink vehicle"); connected_ = false; connecting_ = false; if (is_armed_) { // close the telemetry log. is_armed_ = false; onDisarmed(); } if (connection_ != nullptr) { if (is_hil_mode_set_ && mav_vehicle_ != nullptr) { setNormalMode(); } connection_->stopLoggingSendMessage(); connection_->stopLoggingReceiveMessage(); connection_->close(); } if (hil_node_ != nullptr) { hil_node_->close(); } if (mav_vehicle_ != nullptr) { auto c = mav_vehicle_->getConnection(); if (c != nullptr) { c->stopLoggingSendMessage(); c->stopLoggingReceiveMessage(); } mav_vehicle_->close(); mav_vehicle_ = nullptr; } if (video_server_ != nullptr) video_server_->close(); if (logviewer_proxy_ != nullptr) { logviewer_proxy_->close(); logviewer_proxy_ = nullptr; } if (logviewer_out_proxy_ != nullptr) { logviewer_out_proxy_->close(); logviewer_out_proxy_ = nullptr; } if (qgc_proxy_ != nullptr) { qgc_proxy_->close(); qgc_proxy_ = nullptr; } resetState(); } void connect_thread() { addStatusMessage("Waiting for mavlink vehicle..."); connecting_ = true; createMavConnection(connection_info_); if (mav_vehicle_ != nullptr) { connectToLogViewer(); connectToQGC(); } if (connecting_) { // only set connected if we haven't already been told to disconnect. connecting_ = false; connected_ = true; } } virtual void close() { disconnect(); } void closeAllConnection() { close(); } private: //methods void openAllConnections() { Utils::log("Opening mavlink connection"); close(); //just in case if connections were open resetState(); //reset all variables we might have changed during last session connect(); } void getMocapPose(Vector3r& position, Quaternionr& orientation) const { position.x() = MocapPoseMessage.x; position.y() = MocapPoseMessage.y; position.z() = MocapPoseMessage.z; orientation.w() = MocapPoseMessage.q[0]; orientation.x() = MocapPoseMessage.q[1]; orientation.y() = MocapPoseMessage.q[2]; orientation.z() = MocapPoseMessage.q[3]; } //TODO: this method used to send collision to external sim. Do we still need this? void sendCollision(float normalX, float normalY, float normalZ) { checkValidVehicle(); mavlinkcom::MavLinkCollision collision{}; collision.src = 1; //provider of data is MavLink system in id field collision.id = mav_vehicle_->getLocalSystemId(); collision.action = static_cast<uint8_t>(mavlinkcom::MAV_COLLISION_ACTION::MAV_COLLISION_ACTION_REPORT); collision.threat_level = static_cast<uint8_t>(mavlinkcom::MAV_COLLISION_THREAT_LEVEL::MAV_COLLISION_THREAT_LEVEL_NONE); // we are abusing these fields, passing the angle of the object we hit, so that jMAVSim knows how to bounce off. collision.time_to_minimum_delta = normalX; collision.altitude_minimum_delta = normalY; collision.horizontal_minimum_delta = normalZ; mav_vehicle_->sendMessage(collision); } //TODO: do we still need this method? bool hasVideoRequest() { mavlinkcom::MavLinkVideoServer::MavLinkVideoRequest image_req; return video_server_->hasVideoRequest(image_req); } //TODO: do we still need this method? void sendImage(unsigned char data[], uint32_t length, uint16_t width, uint16_t height) { const int MAVLINK_DATA_STREAM_IMG_PNG = 6; video_server_->sendFrame(data, length, width, height, MAVLINK_DATA_STREAM_IMG_PNG, 0); } //put PX4 in normal mode (i.e. non-simulation mode) void setNormalMode() { if (is_hil_mode_set_ && connection_ != nullptr && mav_vehicle_ != nullptr) { // remove MAV_MODE_FLAG_HIL_ENABLED flag from current mode std::lock_guard<std::mutex> guard(set_mode_mutex_); int mode = mav_vehicle_->getVehicleState().mode; mode &= ~static_cast<int>(mavlinkcom::MAV_MODE_FLAG::MAV_MODE_FLAG_HIL_ENABLED); mavlinkcom::MavCmdDoSetMode cmd; cmd.command = static_cast<uint16_t>(mavlinkcom::MAV_CMD::MAV_CMD_DO_SET_MODE); cmd.Mode = static_cast<float>(mode); mav_vehicle_->sendCommand(cmd); is_hil_mode_set_ = false; } } //put PX4 in simulation mode void setHILMode() { if (!is_simulation_mode_) throw std::logic_error("Attempt to set device in HIL mode while not in simulation mode"); checkValidVehicle(); // add MAV_MODE_FLAG_HIL_ENABLED flag to current mode std::lock_guard<std::mutex> guard(set_mode_mutex_); int mode = mav_vehicle_->getVehicleState().mode; mode |= static_cast<int>(mavlinkcom::MAV_MODE_FLAG::MAV_MODE_FLAG_HIL_ENABLED); mavlinkcom::MavCmdDoSetMode cmd; cmd.command = static_cast<uint16_t>(mavlinkcom::MAV_CMD::MAV_CMD_DO_SET_MODE); cmd.Mode = static_cast<float>(mode); mav_vehicle_->sendCommand(cmd); is_hil_mode_set_ = true; } bool startOffboardMode() { checkValidVehicle(); try { mav_vehicle_->requestControl(); } catch (std::exception& ex) { ensureSafeMode(); addStatusMessage(std::string("Request control failed: ") + ex.what()); return false; } return true; } void endOffboardMode() { // bugbug: I removed this releaseControl because it makes back-to-back move operations less smooth. // The side effect of this is that with some drones (e.g. PX4 based) the drone itself will timeout // when you stop sending move commands and the behavior on timeout is then determined by the drone itself. // mav_vehicle_->releaseControl(); ensureSafeMode(); } void ensureSafeMode() { if (mav_vehicle_ != nullptr) { const mavlinkcom::VehicleState& state = mav_vehicle_->getVehicleState(); if (state.controls.landed || !state.controls.armed) { return; } } } void checkValidVehicle() { if (mav_vehicle_ == nullptr || connection_ == nullptr || !connection_->isOpen() || !connected_) { throw std::logic_error("Cannot perform operation when no vehicle is connected or vehicle is not responding"); } } //status update methods should call this first! void updateState() const { StatusLock lock(this); if (mav_vehicle_ != nullptr) { int version = mav_vehicle_->getVehicleStateVersion(); if (version != state_version_) { current_state_ = mav_vehicle_->getVehicleState(); state_version_ = version; } } } virtual void normalizeRotorControls() { //if rotor controls are in not in 0-1 range then they are in -1 to 1 range in which case //we normalize them to 0 to 1 for PX4 if (!is_controls_0_1_) { // change -1 to 1 to 0 to 1. for (size_t i = 0; i < Utils::length(rotor_controls_); ++i) { rotor_controls_[i] = (rotor_controls_[i] + 1.0f) / 2.0f; } } else { //this applies to PX4 and may work differently on other firmwares. //We use 0.2 as idle rotors which leaves out range of 0.8 for (size_t i = 0; i < Utils::length(rotor_controls_); ++i) { rotor_controls_[i] = Utils::clip(0.8f * rotor_controls_[i] + 0.20f, 0.0f, 1.0f); } } } bool sendTestMessage(std::shared_ptr<mavlinkcom::MavLinkNode> node) { try { // try and send a test message. mavlinkcom::MavLinkHeartbeat test; test.autopilot = static_cast<int>(mavlinkcom::MAV_AUTOPILOT::MAV_AUTOPILOT_PX4); test.type = static_cast<uint8_t>(mavlinkcom::MAV_TYPE::MAV_TYPE_GCS); test.base_mode = 0; test.custom_mode = 0; test.mavlink_version = 3; node->sendMessage(test); test.system_status = 0; return true; } catch (std::exception&) { return false; } } bool connectToLogViewer() { //set up logviewer proxy if (connection_info_.logviewer_ip_address.size() > 0) { std::shared_ptr<mavlinkcom::MavLinkConnection> connection; createProxy("LogViewer", connection_info_.logviewer_ip_address, connection_info_.logviewer_ip_port, connection_info_.local_host_ip, logviewer_proxy_, connection); if (!sendTestMessage(logviewer_proxy_)) { // error talking to log viewer, so don't keep trying, and close the connection also. logviewer_proxy_->getConnection()->close(); logviewer_proxy_ = nullptr; } std::shared_ptr<mavlinkcom::MavLinkConnection> out_connection; createProxy("LogViewerOut", connection_info_.logviewer_ip_address, connection_info_.logviewer_ip_sport, connection_info_.local_host_ip, logviewer_out_proxy_, out_connection); if (!sendTestMessage(logviewer_out_proxy_)) { // error talking to log viewer, so don't keep trying, and close the connection also. logviewer_out_proxy_->getConnection()->close(); logviewer_out_proxy_ = nullptr; } else if (mav_vehicle_ != nullptr) { auto proxylog = std::make_shared<MavLinkLogViewerLog>(logviewer_out_proxy_); mav_vehicle_->getConnection()->startLoggingSendMessage(proxylog); mav_vehicle_->getConnection()->startLoggingReceiveMessage(proxylog); if (connection_ != nullptr) { connection_->startLoggingSendMessage(proxylog); connection_->startLoggingReceiveMessage(proxylog); } } } return logviewer_proxy_ != nullptr; } bool connectToQGC() { if (connection_info_.qgc_ip_address.size() > 0) { std::shared_ptr<mavlinkcom::MavLinkConnection> connection; createProxy("QGC", connection_info_.qgc_ip_address, connection_info_.qgc_ip_port, connection_info_.local_host_ip, qgc_proxy_, connection); if (!sendTestMessage(qgc_proxy_)) { // error talking to QGC, so don't keep trying, and close the connection also. qgc_proxy_->getConnection()->close(); qgc_proxy_ = nullptr; } else { connection->subscribe([=](std::shared_ptr<mavlinkcom::MavLinkConnection> connection_val, const mavlinkcom::MavLinkMessage& msg) { unused(connection_val); processQgcMessages(msg); }); } } return qgc_proxy_ != nullptr; } void createProxy(std::string name, std::string ip, int port, string local_host_ip, std::shared_ptr<mavlinkcom::MavLinkNode>& node, std::shared_ptr<mavlinkcom::MavLinkConnection>& connection) { if (connection_ == nullptr) throw std::domain_error("MavLinkMultirotorApi requires connection object to be set before createProxy call"); connection = mavlinkcom::MavLinkConnection::connectRemoteUdp("Proxy to: " + name + " at " + ip + ":" + std::to_string(port), local_host_ip, ip, port); // it is ok to reuse the simulator sysid and compid here because this node is only used to send a few messages directly to this endpoint // and all other messages are funneled through from PX4 via the Join method below. node = std::make_shared<mavlinkcom::MavLinkNode>(connection_info_.sim_sysid, connection_info_.sim_compid); node->connect(connection); // now join the main connection to this one, this causes all PX4 messages to be sent to the proxy and all messages from the proxy will be // send directly to the PX4 (using whatever sysid/compid comes from that remote node). connection_->join(connection); auto mavcon = mav_vehicle_->getConnection(); if (mavcon != connection_) { mavcon->join(connection); } } static std::string findPX4() { auto result = mavlinkcom::MavLinkConnection::findSerialPorts(0, 0); for (auto iter = result.begin(); iter != result.end(); iter++) { mavlinkcom::SerialPortInfo info = *iter; if (( (info.vid == pixhawkVendorId) && (info.pid == pixhawkFMUV4ProductId || info.pid == pixhawkFMUV2ProductId || info.pid == pixhawkFMUV2OldBootloaderProductId || info.pid == pixhawkFMUV5ProductId)) || ((info.displayName.find(L"PX4_") != std::string::npos))) { // printf("Auto Selecting COM port: %S\n", info.displayName.c_str()); std::string portName_str; for (wchar_t ch : info.portName) { portName_str.push_back(static_cast<char>(ch)); } return portName_str; } } return ""; } void createMavConnection(const AirSimSettings::MavLinkConnectionInfo& connection_info) { if (connection_info.use_serial) { createMavSerialConnection(connection_info.serial_port, connection_info.baud_rate); } else { createMavEthernetConnection(connection_info); } //Uncomment below for sending images over MavLink //connectToVideoServer(); } void createMavEthernetConnection(const AirSimSettings::MavLinkConnectionInfo& connection_info) { close(); connecting_ = true; is_controls_0_1_ = true; std::string remoteIpAddr; Utils::setValue(rotor_controls_, 0.0f); if (connection_info.use_tcp) { if (connection_info.tcp_port == 0) { throw std::invalid_argument("TcpPort setting has an invalid value."); } auto msg = Utils::stringf("Waiting for TCP connection on port %d, local IP %s", connection_info.tcp_port, connection_info_.local_host_ip.c_str()); addStatusMessage(msg); try { connection_ = std::make_shared<mavlinkcom::MavLinkConnection>(); remoteIpAddr = connection_->acceptTcp("hil", connection_info_.local_host_ip, connection_info.tcp_port); } catch (std::exception& e) { addStatusMessage("Accepting TCP socket failed, is another instance running?"); addStatusMessage(e.what()); return; } } else if (connection_info.udp_address.size() > 0) { if (connection_info.udp_port == 0) { throw std::invalid_argument("UdpPort setting has an invalid value."); } connection_ = mavlinkcom::MavLinkConnection::connectRemoteUdp("hil", connection_info_.local_host_ip, connection_info.udp_address, connection_info.udp_port); } else { throw std::invalid_argument("Please provide valid connection info for your drone."); } // start listening to the SITL connection. connection_->subscribe([=](std::shared_ptr<mavlinkcom::MavLinkConnection> connection, const mavlinkcom::MavLinkMessage& msg) { unused(connection); processMavMessages(msg); }); hil_node_ = std::make_shared<mavlinkcom::MavLinkNode>(connection_info_.sim_sysid, connection_info_.sim_compid); hil_node_->connect(connection_); if (connection_info.use_tcp) { addStatusMessage(std::string("Connected to SITL over TCP.")); } else { addStatusMessage(std::string("Connected to SITL over UDP.")); } mav_vehicle_ = std::make_shared<mavlinkcom::MavLinkVehicle>(connection_info_.vehicle_sysid, connection_info_.vehicle_compid); if (connection_info_.control_ip_address != "") { if (connection_info_.control_port_local == 0) { throw std::invalid_argument("LocalControlPort setting has an invalid value."); } if (!connection_info.use_tcp || connection_info_.control_ip_address != "remote") { remoteIpAddr = connection_info_.control_ip_address; } if (remoteIpAddr == "local" || remoteIpAddr == "localhost") { remoteIpAddr = "127.0.0.1"; } // The PX4 SITL mode app cannot receive commands to control the drone over the same HIL mavlink connection. // The HIL mavlink connection can only handle HIL_SENSOR messages. This separate channel is needed for // everything else. addStatusMessage(Utils::stringf("Connecting to PX4 Control UDP port %d, local IP %s, remote IP %s ...", connection_info_.control_port_local, connection_info_.local_host_ip.c_str(), remoteIpAddr.c_str())); // if we try and connect the UDP port too quickly it doesn't work, bug in PX4 ? for (int retries = 60; retries >= 0 && connecting_; retries--) { try { std::shared_ptr<mavlinkcom::MavLinkConnection> gcsConnection; if (remoteIpAddr == "127.0.0.1") { gcsConnection = mavlinkcom::MavLinkConnection::connectLocalUdp("gcs", connection_info_.local_host_ip, connection_info_.control_port_local); } else { gcsConnection = mavlinkcom::MavLinkConnection::connectRemoteUdp("gcs", connection_info_.local_host_ip, remoteIpAddr, connection_info_.control_port_remote); } mav_vehicle_->connect(gcsConnection); // need to try and send something to make sure the connection is good. mav_vehicle_->setMessageInterval(mavlinkcom::MavLinkHomePosition::kMessageId, 1); break; } catch (std::exception&) { std::this_thread::sleep_for(std::chrono::seconds(1)); } } if (mav_vehicle_ == nullptr) { // play was stopped! return; } if (mav_vehicle_->getConnection() != nullptr) { addStatusMessage(std::string("Ground control connected over UDP.")); } else { addStatusMessage(std::string("Timeout trying to connect ground control over UDP.")); return; } } try { connectVehicle(); } catch (std::exception& e) { addStatusMessage("Error connecting vehicle:"); addStatusMessage(e.what()); } } void processControlMessages(const mavlinkcom::MavLinkMessage& msg) { // Utils::log(Utils::stringf("Control msg %d", msg.msgid)); // PX4 usually sends the following on the control channel. // If nothing is arriving here it means our control channel UDP connection isn't working. // MAVLINK_MSG_ID_HIGHRES_IMU // MAVLINK_MSG_ID_ACTUATOR_CONTROL_TARGET // MAVLINK_MSG_ID_SERVO_OUTPUT_RAW // MAVLINK_MSG_ID_GPS_RAW_INT // MAVLINK_MSG_ID_TIMESYNC // MAVLINK_MSG_ID_ALTITUDE // MAVLINK_MSG_ID_VFR_HUD // MAVLINK_MSG_ID_ESTIMATOR_STATUS // MAVLINK_MSG_ID_EXTENDED_SYS_STATE // MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN // MAVLINK_MSG_ID_PING // MAVLINK_MSG_ID_SYS_STATUS // MAVLINK_MSG_ID_SYSTEM_TIME // MAVLINK_MSG_ID_LINK_NODE_STATUS // MAVLINK_MSG_ID_AUTOPILOT_VERSION // MAVLINK_MSG_ID_COMMAND_ACK // MAVLINK_MSG_ID_STATUSTEXT // MAVLINK_MSG_ID_PARAM_VALUE processMavMessages(msg); } void connectVehicle() { // listen to this UDP mavlink connection also auto mavcon = mav_vehicle_->getConnection(); if (mavcon != nullptr && mavcon != connection_) { mavcon->subscribe([=](std::shared_ptr<mavlinkcom::MavLinkConnection> connection, const mavlinkcom::MavLinkMessage& msg) { unused(connection); processControlMessages(msg); }); } else { mav_vehicle_->connect(connection_); } connected_ = true; // Also request home position messages mav_vehicle_->setMessageInterval(mavlinkcom::MavLinkHomePosition::kMessageId, 1); // now we can start our heartbeats. mav_vehicle_->startHeartbeat(); // wait for px4 to connect so we can safely send any configured parameters while (!send_params_ && connected_) { std::this_thread::sleep_for(std::chrono::seconds(1)); } if (connected_) { sendParams(); send_params_ = false; } } void createMavSerialConnection(const std::string& port_name, int baud_rate) { close(); connecting_ = true; bool reported = false; std::string port_name_auto = port_name; while (port_name_auto == "" || port_name_auto == "*") { port_name_auto = findPX4(); if (port_name_auto == "") { if (!reported) { reported = true; addStatusMessage("Could not detect a connected PX4 flight controller on any USB ports."); addStatusMessage("You can specify USB port in settings.json."); } std::this_thread::sleep_for(std::chrono::seconds(1)); } } if (port_name_auto == "") { addStatusMessage("USB port for PX4 flight controller is empty. Please set it in settings.json."); return; } if (baud_rate == 0) { addStatusMessage("Baud rate specified in settings.json is 0 which is invalid"); return; } addStatusMessage(Utils::stringf("Connecting to PX4 over serial port: %s, baud rate %d ....", port_name_auto.c_str(), baud_rate)); reported = false; while (connecting_) { try { connection_ = mavlinkcom::MavLinkConnection::connectSerial("hil", port_name_auto, baud_rate); connection_->ignoreMessage(mavlinkcom::MavLinkAttPosMocap::kMessageId); //TODO: find better way to communicate debug pose instead of using fake Mo-cap messages hil_node_ = std::make_shared<mavlinkcom::MavLinkNode>(connection_info_.sim_sysid, connection_info_.sim_compid); hil_node_->connect(connection_); addStatusMessage(Utils::stringf("Connected to PX4 over serial port: %s", port_name_auto.c_str())); // start listening to the HITL connection. connection_->subscribe([=](std::shared_ptr<mavlinkcom::MavLinkConnection> connection, const mavlinkcom::MavLinkMessage& msg) { unused(connection); processMavMessages(msg); }); mav_vehicle_ = std::make_shared<mavlinkcom::MavLinkVehicle>(connection_info_.vehicle_sysid, connection_info_.vehicle_compid); connectVehicle(); return; } catch (std::exception& e) { if (!reported) { reported = true; addStatusMessage("Error connecting to mavlink vehicle."); addStatusMessage(e.what()); addStatusMessage("Please check your USB port in settings.json."); } std::this_thread::sleep_for(std::chrono::seconds(1)); } } } mavlinkcom::MavLinkHilSensor getLastSensorMessage() { std::lock_guard<std::mutex> guard(last_message_mutex_); return last_sensor_message_; } mavlinkcom::MavLinkDistanceSensor getLastDistanceMessage() { std::lock_guard<std::mutex> guard(last_message_mutex_); return last_distance_message_; } mavlinkcom::MavLinkHilGps getLastGpsMessage() { std::lock_guard<std::mutex> guard(last_message_mutex_); return last_gps_message_; } void sendParams() { // send any mavlink parameters from settings.json through to the connected vehicle. if (mav_vehicle_ != nullptr && connection_info_.params.size() > 0) { try { for (auto iter : connection_info_.params) { auto key = iter.first; auto value = iter.second; mavlinkcom::MavLinkParameter p; p.name = key; p.value = value; bool result = false; mav_vehicle_->setParameter(p).wait(1000, &result); if (!result) { Utils::log(Utils::stringf("Failed to set mavlink parameter '%s'", key.c_str())); } } } catch (std::exception& ex) { addStatusMessage("Exception sending parameters to vehicle"); addStatusMessage(ex.what()); } } } void setArmed(bool armed) { if (is_armed_) { if (!armed) { onDisarmed(); } } else { if (armed) { onArmed(); } } is_armed_ = armed; if (!armed) { //reset motor controls for (size_t i = 0; i < Utils::length(rotor_controls_); ++i) { rotor_controls_[i] = 0; } } } void processQgcMessages(const mavlinkcom::MavLinkMessage& msg) { if (msg.msgid == MocapPoseMessage.msgid) { std::lock_guard<std::mutex> guard(mocap_pose_mutex_); MocapPoseMessage.decode(msg); getMocapPose(mocap_pose_.position, mocap_pose_.orientation); } //else ignore message } void addStatusMessage(const std::string& message) { if (message.size() != 0) { Utils::log(message); std::lock_guard<std::mutex> guard_status(status_text_mutex_); //if queue became too large, clear it first if (status_messages_.size() > status_messages_MaxSize) Utils::clear(status_messages_, status_messages_MaxSize - status_messages_.size()); status_messages_.push(message); } } void handleLockStep() { received_actuator_controls_ = true; // if the timestamps match then it means we are in lockstep mode. if (!lock_step_active_ && lock_step_enabled_) { // && (HilActuatorControlsMessage.flags & 0x1)) // todo: enable this check when this flag is widely available... if (last_hil_sensor_time_ == HilActuatorControlsMessage.time_usec) { addStatusMessage("Enabling lockstep mode"); lock_step_active_ = true; } } else { auto now = clock()->nowNanos() / 1000; auto delay = static_cast<uint32_t>(now - last_update_time_); std::lock_guard<std::mutex> guard(telemetry_mutex_); actuator_delay_ += delay; } if (world_ != nullptr) { world_->pause(false); } } void processMavMessages(const mavlinkcom::MavLinkMessage& msg) { if (msg.msgid == HeartbeatMessage.msgid) { std::lock_guard<std::mutex> guard_heartbeat(heartbeat_mutex_); HeartbeatMessage.decode(msg); bool armed = (HeartbeatMessage.base_mode & static_cast<uint8_t>(mavlinkcom::MAV_MODE_FLAG::MAV_MODE_FLAG_SAFETY_ARMED)) > 0; setArmed(armed); if (!got_first_heartbeat_) { Utils::log("received first heartbeat"); got_first_heartbeat_ = true; if (HeartbeatMessage.autopilot == static_cast<uint8_t>(mavlinkcom::MAV_AUTOPILOT::MAV_AUTOPILOT_PX4) && HeartbeatMessage.type == static_cast<uint8_t>(mavlinkcom::MAV_TYPE::MAV_TYPE_FIXED_WING)) { // PX4 will scale fixed wing servo outputs to -1 to 1 // and it scales multi rotor servo output to 0 to 1. is_controls_0_1_ = false; } } else if (is_simulation_mode_ && !is_hil_mode_set_) { setHILMode(); } } else if (msg.msgid == StatusTextMessage.msgid) { StatusTextMessage.decode(msg); //lock is established by below method addStatusMessage(std::string(StatusTextMessage.text)); } else if (msg.msgid == CommandLongMessage.msgid) { CommandLongMessage.decode(msg); if (CommandLongMessage.command == static_cast<int>(mavlinkcom::MAV_CMD::MAV_CMD_SET_MESSAGE_INTERVAL)) { int msg_id = static_cast<int>(CommandLongMessage.param1 + 0.5); if (msg_id == 115) { //HIL_STATE_QUATERNION hil_state_freq_ = static_cast<int>(CommandLongMessage.param2 + 0.5); } } } else if (msg.msgid == HilControlsMessage.msgid) { if (!actuators_message_supported_) { std::lock_guard<std::mutex> guard_controls(hil_controls_mutex_); HilControlsMessage.decode(msg); rotor_controls_[0] = HilControlsMessage.roll_ailerons; rotor_controls_[1] = HilControlsMessage.pitch_elevator; rotor_controls_[2] = HilControlsMessage.yaw_rudder; rotor_controls_[3] = HilControlsMessage.throttle; rotor_controls_[4] = HilControlsMessage.aux1; rotor_controls_[5] = HilControlsMessage.aux2; rotor_controls_[6] = HilControlsMessage.aux3; rotor_controls_[7] = HilControlsMessage.aux4; normalizeRotorControls(); handleLockStep(); } } else if (msg.msgid == HilActuatorControlsMessage.msgid) { actuators_message_supported_ = true; std::lock_guard<std::mutex> guard_actuator(hil_controls_mutex_); //use same mutex as HIL_CONTROl HilActuatorControlsMessage.decode(msg); bool isarmed = (HilActuatorControlsMessage.mode & 128) != 0; for (auto i = 0; i < 8; ++i) { if (isarmed) { rotor_controls_[i] = HilActuatorControlsMessage.controls[i]; } else { rotor_controls_[i] = 0; } } if (isarmed) { normalizeRotorControls(); } handleLockStep(); } else if (msg.msgid == MavLinkGpsRawInt.msgid) { MavLinkGpsRawInt.decode(msg); auto fix_type = static_cast<mavlinkcom::GPS_FIX_TYPE>(MavLinkGpsRawInt.fix_type); auto locked = (fix_type != mavlinkcom::GPS_FIX_TYPE::GPS_FIX_TYPE_NO_GPS && fix_type != mavlinkcom::GPS_FIX_TYPE::GPS_FIX_TYPE_NO_FIX); if (locked && !has_gps_lock_) { addStatusMessage("Got GPS lock"); has_gps_lock_ = true; } if (!has_home_ && current_state_.home.is_set) { addStatusMessage("Got GPS Home Location"); has_home_ = true; } send_params_ = true; } else if (msg.msgid == mavlinkcom::MavLinkLocalPositionNed::kMessageId) { // we are getting position information... so we can use this to check the stability of the z coordinate before takeoff. if (current_state_.controls.landed) { monitorGroundAltitude(); } } else if (msg.msgid == mavlinkcom::MavLinkExtendedSysState::kMessageId) { // check landed state. getLandedState(); send_params_ = true; } else if (msg.msgid == mavlinkcom::MavLinkHomePosition::kMessageId) { mavlinkcom::MavLinkHomePosition home; home.decode(msg); // this is a good time to send the params send_params_ = true; } else if (msg.msgid == mavlinkcom::MavLinkSysStatus::kMessageId) { // this is a good time to send the params send_params_ = true; } else if (msg.msgid == mavlinkcom::MavLinkAutopilotVersion::kMessageId) { // this is a good time to send the params send_params_ = true; } else { // creates too much log output, only do this when debugging this issue specifically. // Utils::log(Utils::stringf("Ignoring msg %d from %d,%d ", msg.msgid, msg.compid, msg.sysid)); } } void sendHILSensor(const Vector3r& acceleration, const Vector3r& gyro, const Vector3r& mag, float abs_pressure, float pressure_alt) { if (!is_simulation_mode_) throw std::logic_error("Attempt to send simulated sensor messages while not in simulation mode"); mavlinkcom::MavLinkHilSensor hil_sensor; hil_sensor.time_usec = last_hil_sensor_time_ = getSimTime(); hil_sensor.xacc = acceleration.x(); hil_sensor.yacc = acceleration.y(); hil_sensor.zacc = acceleration.z(); hil_sensor.fields_updated = 0b111; // Set accel bit fields hil_sensor.xgyro = gyro.x(); hil_sensor.ygyro = gyro.y(); hil_sensor.zgyro = gyro.z(); hil_sensor.fields_updated |= 0b111000; // Set gyro bit fields hil_sensor.xmag = mag.x(); hil_sensor.ymag = mag.y(); hil_sensor.zmag = mag.z(); hil_sensor.fields_updated |= 0b111000000; // Set mag bit fields hil_sensor.abs_pressure = abs_pressure; hil_sensor.pressure_alt = pressure_alt; hil_sensor.fields_updated |= 0b1101000000000; // Set baro bit fields //TODO: enable temperature? diff_pressure if (was_reset_) { hil_sensor.fields_updated = static_cast<uint32_t>(1 << 31); } if (hil_node_ != nullptr) { hil_node_->sendMessage(hil_sensor); received_actuator_controls_ = false; if (lock_step_active_ && world_ != nullptr) { world_->pauseForTime(1); // 1 second delay max waiting for actuator controls. } } std::lock_guard<std::mutex> guard(last_message_mutex_); last_sensor_message_ = hil_sensor; } void sendSystemTime() { // SYSTEM TIME from host auto tu = getSimTime(); uint32_t ms = (uint32_t)(tu / 1000); if (ms != last_sys_time_) { last_sys_time_ = ms; mavlinkcom::MavLinkSystemTime msg_system_time; msg_system_time.time_unix_usec = tu; msg_system_time.time_boot_ms = last_sys_time_; if (hil_node_ != nullptr) { hil_node_->sendMessage(msg_system_time); } } } void sendDistanceSensor(float min_distance, float max_distance, float current_distance, uint8_t sensor_type, uint8_t sensor_id, const Quaternionr& orientation) { if (!is_simulation_mode_) throw std::logic_error("Attempt to send simulated distance sensor messages while not in simulation mode"); mavlinkcom::MavLinkDistanceSensor distance_sensor; distance_sensor.time_boot_ms = static_cast<uint32_t>(getSimTime() / 1000); distance_sensor.min_distance = static_cast<uint16_t>(min_distance); distance_sensor.max_distance = static_cast<uint16_t>(max_distance); distance_sensor.current_distance = static_cast<uint16_t>(current_distance); distance_sensor.type = sensor_type; distance_sensor.id = sensor_id; // Use custom orientation distance_sensor.orientation = 100; // MAV_SENSOR_ROTATION_CUSTOM distance_sensor.quaternion[0] = orientation.w(); distance_sensor.quaternion[1] = orientation.x(); distance_sensor.quaternion[2] = orientation.y(); distance_sensor.quaternion[3] = orientation.z(); //TODO: use covariance parameter? // PX4 doesn't support receiving simulated distance sensor messages this way. // It results in lots of error messages from PX4. This code is still useful in that // it sets last_distance_message_ and that is returned via Python API. // // if (hil_node_ != nullptr) { // hil_node_->sendMessage(distance_sensor); // } std::lock_guard<std::mutex> guard(last_message_mutex_); last_distance_message_ = distance_sensor; } void sendHILGps(const GeoPoint& geo_point, const Vector3r& velocity, float velocity_xy, float cog, float eph, float epv, int fix_type, unsigned int satellites_visible) { unused(satellites_visible); if (!is_simulation_mode_) throw std::logic_error("Attempt to send simulated GPS messages while not in simulation mode"); mavlinkcom::MavLinkHilGps hil_gps; hil_gps.time_usec = getSimTime(); hil_gps.lat = static_cast<int32_t>(geo_point.latitude * 1E7); hil_gps.lon = static_cast<int32_t>(geo_point.longitude * 1E7); hil_gps.alt = static_cast<int32_t>(geo_point.altitude * 1000); hil_gps.vn = static_cast<int16_t>(velocity.x() * 100); hil_gps.ve = static_cast<int16_t>(velocity.y() * 100); hil_gps.vd = static_cast<int16_t>(velocity.z() * 100); hil_gps.eph = static_cast<uint16_t>(eph * 100); hil_gps.epv = static_cast<uint16_t>(epv * 100); hil_gps.fix_type = static_cast<uint8_t>(fix_type); hil_gps.vel = static_cast<uint16_t>(velocity_xy * 100); hil_gps.cog = static_cast<uint16_t>(cog * 100); hil_gps.satellites_visible = static_cast<uint8_t>(15); if (hil_node_ != nullptr) { hil_node_->sendMessage(hil_gps); } if (hil_gps.lat < 0.1f && hil_gps.lat > -0.1f) { //Utils::DebugBreak(); Utils::log("hil_gps.lat was too close to 0", Utils::kLogLevelError); } std::lock_guard<std::mutex> guard(last_message_mutex_); last_gps_message_ = hil_gps; } void resetState() { //reset state is_hil_mode_set_ = false; is_controls_0_1_ = true; hil_state_freq_ = -1; actuators_message_supported_ = false; state_version_ = 0; current_state_ = mavlinkcom::VehicleState(); target_height_ = 0; got_first_heartbeat_ = false; is_armed_ = false; has_home_ = false; sim_time_us_ = 0; last_sys_time_ = 0; last_gps_time_ = 0; last_update_time_ = 0; last_hil_sensor_time_ = 0; update_count_ = 0; hil_sensor_count_ = 0; lock_step_resets_ = 0; actuator_delay_ = 0; is_api_control_enabled_ = false; thrust_controller_ = PidController(); Utils::setValue(rotor_controls_, 0.0f); was_reset_ = false; received_actuator_controls_ = false; lock_step_active_ = false; lock_step_enabled_ = false; has_gps_lock_ = false; send_params_ = false; mocap_pose_ = Pose::nanPose(); ground_variance_ = 1; ground_filter_.initialize(25, 0.1f); cancelLastTask(); } void monitorGroundAltitude() { // used to ensure stable altitude before takeoff. auto position = getPosition(); auto result = ground_filter_.filter(position.z()); auto variance = std::get<1>(result); if (variance >= 0) { // filter returns -1 if we don't have enough data yet. ground_variance_ = variance; } } protected: //variables //TODO: below was made protected from private to support Ardupilot //implementation but we need to review this and avoid having protected variables static const int RotorControlsCount = 8; const SensorCollection* sensors_; mutable std::mutex hil_controls_mutex_; AirSimSettings::MavLinkConnectionInfo connection_info_; float rotor_controls_[RotorControlsCount]; bool is_simulation_mode_; private: //variables static const int pixhawkVendorId = 9900; ///< Vendor ID for Pixhawk board (V2 and V1) and PX4 Flow static const int pixhawkFMUV4ProductId = 18; ///< Product ID for Pixhawk V2 board static const int pixhawkFMUV2ProductId = 17; ///< Product ID for Pixhawk V2 board static const int pixhawkFMUV5ProductId = 50; ///< Product ID for Pixhawk V5 board static const int pixhawkFMUV2OldBootloaderProductId = 22; ///< Product ID for Bootloader on older Pixhawk V2 boards static const int pixhawkFMUV1ProductId = 16; ///< Product ID for PX4 FMU V1 board static const int messageReceivedTimeout = 10; ///< Seconds std::shared_ptr<mavlinkcom::MavLinkNode> logviewer_proxy_, logviewer_out_proxy_, qgc_proxy_; size_t status_messages_MaxSize = 5000; std::shared_ptr<mavlinkcom::MavLinkNode> hil_node_; std::shared_ptr<mavlinkcom::MavLinkConnection> connection_; std::shared_ptr<mavlinkcom::MavLinkVideoServer> video_server_; std::shared_ptr<MultirotorApiBase> mav_vehicle_control_; mavlinkcom::MavLinkAttPosMocap MocapPoseMessage; mavlinkcom::MavLinkHeartbeat HeartbeatMessage; mavlinkcom::MavLinkSetMode SetModeMessage; mavlinkcom::MavLinkStatustext StatusTextMessage; mavlinkcom::MavLinkHilControls HilControlsMessage; mavlinkcom::MavLinkHilActuatorControls HilActuatorControlsMessage; mavlinkcom::MavLinkGpsRawInt MavLinkGpsRawInt; mavlinkcom::MavLinkCommandLong CommandLongMessage; mavlinkcom::MavLinkLocalPositionNed MavLinkLocalPositionNed; mavlinkcom::MavLinkHilSensor last_sensor_message_; mavlinkcom::MavLinkDistanceSensor last_distance_message_; mavlinkcom::MavLinkHilGps last_gps_message_; std::mutex mocap_pose_mutex_, heartbeat_mutex_, set_mode_mutex_, status_text_mutex_, last_message_mutex_, telemetry_mutex_; //variables required for VehicleApiBase implementation bool got_first_heartbeat_ = false, is_hil_mode_set_ = false, is_armed_ = false; bool is_controls_0_1_; //Are motor controls specified in 0..1 or -1..1? bool send_params_ = false; std::queue<std::string> status_messages_; int hil_state_freq_; bool actuators_message_supported_ = false; bool was_reset_ = false; bool has_home_ = false; bool is_ready_ = false; bool has_gps_lock_ = false; bool lock_step_active_ = false; bool lock_step_enabled_ = false; bool received_actuator_controls_ = false; std::string is_ready_message_; Pose mocap_pose_; std::thread connect_thread_; bool connecting_ = false; bool connected_ = false; common_utils::SmoothingFilter<float> ground_filter_; double ground_variance_ = 1; const double GroundTolerance = 0.1; // variables for throttling HIL_SENSOR and SYSTEM_TIME messages uint32_t last_sys_time_ = 0; unsigned long long sim_time_us_ = 0; uint64_t last_gps_time_ = 0; uint64_t last_update_time_ = 0; uint64_t last_hil_sensor_time_ = 0; // variables accumulated for MavLinkTelemetry messages. uint64_t update_time_ = 0; uint32_t update_count_ = 0; uint32_t hil_sensor_count_ = 0; uint32_t lock_step_resets_ = 0; uint32_t actuator_delay_ = 0; std::thread telemetry_thread_; //additional variables required for MultirotorApiBase implementation //this is optional for methods that might not use vehicle commands std::shared_ptr<mavlinkcom::MavLinkVehicle> mav_vehicle_; float target_height_; bool is_api_control_enabled_; PidController thrust_controller_; common_utils::Timer hil_message_timer_; common_utils::Timer gcs_message_timer_; std::shared_ptr<mavlinkcom::MavLinkFileLog> log_; std::string log_file_name_; World* world_; //every time we return status update, we need to check if we have new data //this is why below two variables are marked as mutable mutable int state_version_; mutable mavlinkcom::VehicleState current_state_; }; } } //namespace #endif
AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/MavLinkMultirotorApi.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/MavLinkMultirotorApi.hpp", "repo_id": "AirSim", "token_count": 44249 }
14
#pragma once #include "interfaces/CommonStructs.hpp" namespace simple_flight { struct Params { public: static float min_armed_throttle() { static float val = 0.1f; return val; } //this should match up with target board //simulation board should respect possible values struct Motor { uint16_t motor_count = 4; float min_motor_output = 0; float max_motor_output = 1; //if min_armed_output too low then noise in pitch/roll can destabilize quad copter when throttle is zero float min_angling_throttle = Params::min_armed_throttle() / 2; } motor; struct Rc { uint16_t channel_count = 12; uint16_t read_interval_ms = 10; int16_t rate_level_mode_channel = 4; //corresponds to switch 0 in rc_data int16_t allow_api_control_channel = 5; //corresponds to switch 1 in rc_data //When actions such as arming/unarming, how much tolerance can be allowed in stick positions from 0 to 1? float action_request_tolerance = 0.1f; //milliseconds while sticks should stay in position uint64_t arm_duration = 100; uint64_t disarm_duration = 100; uint64_t neutral_duration = 100; Axis4<int16_t> channels = Axis4<int16_t>(0, 3, 1, 2); TReal max_angle_level_switch = 0.3f; //should be >= motor.min_angling_throttle float min_angling_throttle = Params::min_armed_throttle() / 1.5f; bool allow_api_when_disconnected = false; bool allow_api_always = false; } rc; struct AngleRatePid { //max_xxx_rate > 5 would introduce wobble/oscillations const float kMaxLimit = 2.5f; const float kP = 0.25f; const float kI = 0.0f; const float kD = 0.0f; Axis3r max_limit = Axis3r(kMaxLimit, kMaxLimit, kMaxLimit); //roll, pitch, yaw - in radians/sec //p_xxx_rate params are sensitive to gyro noise. Values higher than 0.5 would require //noise filtration Axis4r p = Axis4r(kP, kP, kP, 1.0f); Axis4r i = Axis4r(kI, kI, kI, 0.0f); Axis4r d = Axis4r(kD, kD, kD, 0.0f); } angle_rate_pid; struct AngleLevelPid { const float pi = 3.14159265359f; //180-degrees const float kP = 2.5f; const float kI = 0.0f; const float kD = 0.0f; //max_pitch/roll_angle > 5.5 would produce verticle thrust that is not enough to keep vehicle in air at extremities of controls Axis4r max_limit = Axis4r(pi / 5.5f, pi / 5.5f, pi, 1.0f); //roll, pitch, yaw - in radians/sec Axis4r p = Axis4r(kP, kP, kP, 1.0f); Axis4r i = Axis4r(kI, kI, kI, 0.0f); Axis4r d = Axis4r(kD, kD, kD, 0.0f); } angle_level_pid; struct PositionPid { const float kMaxLimit = 8.8E26f; //some big number like size of known universe const float kP = 0.25f; const float kI = 0.0f; const float kD = 0.0f; Axis4r max_limit = Axis4r(kMaxLimit, kMaxLimit, kMaxLimit, 1.0f); //x, y, z in meters Axis4r p = Axis4r(kP, kP, 0, kP); Axis4r i = Axis4r(kI, kI, kI, kI); Axis4r d = Axis4r(kD, kD, kD, kD); } position_pid; struct VelocityPid { const float kMinThrottle = std::min(1.0f, Params::min_armed_throttle() * 3.0f); const float kMaxLimit = 6.0f; // m/s const float kP = 0.2f; const float kI = 2.0f; const float kD = 0.0f; Axis4r max_limit = Axis4r(kMaxLimit, kMaxLimit, 0, kMaxLimit); //x, y, yaw, z in meters Axis4r p = Axis4r(kP, kP, 0.0f, 2.0f); // todo why 2.0f hardcoded Axis4r i = Axis4r(0.0f, 0.0f, 0.0f, kI); Axis4r d = Axis4r(kD, kD, kD, kD); Axis4r iterm_discount = Axis4r(1, 1, 1, 0.9999f); Axis4r output_bias = Axis4r(0, 0, 0, 0); //we keep min throttle higher so that if we are angling a lot, its still supported float min_throttle = kMinThrottle; } velocity_pid; struct Takeoff { float takeoff_z = -2.0f; //float velocity = -1.0f; } takeoff; enum class ControllerType { Cascade, Adaptive }; GoalMode default_goal_mode = GoalMode::getStandardAngleMode(); VehicleStateType default_vehicle_state = VehicleStateType::Inactive; uint64_t api_goal_timeout = 60; //milliseconds ControllerType controller_type = ControllerType::Cascade; bool gains_changed; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Params.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Params.hpp", "repo_id": "AirSim", "token_count": 2059 }
15
#pragma once #include <cstdint> #include "IUpdatable.hpp" #include "IGoal.hpp" #include "IStateEstimator.hpp" #include "IBoardClock.hpp" namespace simple_flight { class IController : public IUpdatable { public: virtual void initialize(const IGoal* goal, const IStateEstimator* state_estimator) = 0; virtual const Axis4r& getOutput() = 0; virtual bool isLastGoalModeAllPassthrough() = 0; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IController.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IController.hpp", "repo_id": "AirSim", "token_count": 159 }
16
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //in header only mode, control library is not available #ifndef AIRLIB_HEADER_ONLY //RPC code requires C++14. If build system like Unreal doesn't support it then use compiled binaries #ifndef AIRLIB_NO_RPC //if using Unreal Build system then include pre-compiled header file first #include "vehicles/multirotor/api/MultirotorRpcLibServer.hpp" #include "common/Common.hpp" STRICT_MODE_OFF #ifndef RPCLIB_MSGPACK #define RPCLIB_MSGPACK clmdep_msgpack #endif // !RPCLIB_MSGPACK #include "common/common_utils/MinWinDefines.hpp" #undef NOUSER #include "common/common_utils/WindowsApisCommonPre.hpp" #undef FLOAT #undef check #include "rpc/server.h" //TODO: HACK: UE4 defines macro with stupid names like "check" that conflicts with msgpack library #ifndef check #define check(expr) (static_cast<void>((expr))) #endif #include "common/common_utils/WindowsApisCommonPost.hpp" #include "vehicles/multirotor/api/MultirotorRpcLibAdaptors.hpp" STRICT_MODE_ON namespace msr { namespace airlib { typedef msr::airlib_rpclib::MultirotorRpcLibAdaptors MultirotorRpcLibAdaptors; MultirotorRpcLibServer::MultirotorRpcLibServer(ApiProvider* api_provider, string server_address, uint16_t port) : RpcLibServerBase(api_provider, server_address, port) { (static_cast<rpc::server*>(getServer()))->bind("takeoff", [&](float timeout_sec, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->takeoff(timeout_sec); }); (static_cast<rpc::server*>(getServer()))->bind("land", [&](float timeout_sec, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->land(timeout_sec); }); (static_cast<rpc::server*>(getServer()))->bind("goHome", [&](float timeout_sec, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->goHome(timeout_sec); }); (static_cast<rpc::server*>(getServer()))->bind("moveByVelocityBodyFrame", [&](float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByVelocityBodyFrame(vx, vy, vz, duration, drivetrain, yaw_mode.to()); }); (static_cast<rpc::server*>(getServer()))->bind("moveByVelocityZBodyFrame", [&](float vx, float vy, float z, float duration, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByVelocityZBodyFrame(vx, vy, z, duration, drivetrain, yaw_mode.to()); }); (static_cast<rpc::server*>(getServer()))->bind("moveByMotorPWMs", [&](float front_right_pwm, float rear_left_pwm, float front_left_pwm, float rear_right_pwm, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByMotorPWMs(front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByRollPitchYawZ", [&](float roll, float pitch, float yaw, float z, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByRollPitchYawZ(roll, pitch, yaw, z, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByRollPitchYawThrottle", [&](float roll, float pitch, float yaw, float throttle, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByRollPitchYawThrottle(roll, pitch, yaw, throttle, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByRollPitchYawrateThrottle", [&](float roll, float pitch, float yaw_rate, float throttle, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByRollPitchYawrateThrottle(roll, pitch, yaw_rate, throttle, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByRollPitchYawrateZ", [&](float roll, float pitch, float yaw_rate, float z, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByRollPitchYawrateZ(roll, pitch, yaw_rate, z, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByAngleRatesZ", [&](float roll_rate, float pitch_rate, float yaw_rate, float z, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByAngleRatesZ(roll_rate, pitch_rate, yaw_rate, z, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByAngleRatesThrottle", [&](float roll_rate, float pitch_rate, float yaw_rate, float throttle, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByAngleRatesThrottle(roll_rate, pitch_rate, yaw_rate, throttle, duration); }); (static_cast<rpc::server*>(getServer()))->bind("moveByVelocity", [&](float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByVelocity(vx, vy, vz, duration, drivetrain, yaw_mode.to()); }); (static_cast<rpc::server*>(getServer()))->bind("moveByVelocityZ", [&](float vx, float vy, float z, float duration, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByVelocityZ(vx, vy, z, duration, drivetrain, yaw_mode.to()); }); (static_cast<rpc::server*>(getServer()))->bind("moveOnPath", [&](const vector<MultirotorRpcLibAdaptors::Vector3r>& path, float velocity, float timeout_sec, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) -> bool { vector<Vector3r> conv_path; MultirotorRpcLibAdaptors::to(path, conv_path); return getVehicleApi(vehicle_name)->moveOnPath(conv_path, velocity, timeout_sec, drivetrain, yaw_mode.to(), lookahead, adaptive_lookahead); }); (static_cast<rpc::server*>(getServer()))->bind("moveToGPS", [&](float latitude, float longitude, float altitude, float velocity, float timeout_sec, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveToGPS(latitude, longitude, altitude, velocity, timeout_sec, drivetrain, yaw_mode.to(), lookahead, adaptive_lookahead); }); (static_cast<rpc::server*>(getServer()))->bind("moveToPosition", [&](float x, float y, float z, float velocity, float timeout_sec, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveToPosition(x, y, z, velocity, timeout_sec, drivetrain, yaw_mode.to(), lookahead, adaptive_lookahead); }); (static_cast<rpc::server*>(getServer()))->bind("moveToZ", [&](float z, float velocity, float timeout_sec, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, float lookahead, float adaptive_lookahead, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveToZ(z, velocity, timeout_sec, yaw_mode.to(), lookahead, adaptive_lookahead); }); (static_cast<rpc::server*>(getServer()))->bind("moveByManual", [&](float vx_max, float vy_max, float z_min, float duration, DrivetrainType drivetrain, const MultirotorRpcLibAdaptors::YawMode& yaw_mode, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->moveByManual(vx_max, vy_max, z_min, duration, drivetrain, yaw_mode.to()); }); (static_cast<rpc::server*>(getServer()))->bind("rotateToYaw", [&](float yaw, float timeout_sec, float margin, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->rotateToYaw(yaw, timeout_sec, margin); }); (static_cast<rpc::server*>(getServer()))->bind("rotateByYawRate", [&](float yaw_rate, float duration, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->rotateByYawRate(yaw_rate, duration); }); (static_cast<rpc::server*>(getServer()))->bind("hover", [&](const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->hover(); }); (static_cast<rpc::server*>(getServer()))->bind("setAngleLevelControllerGains", [&](const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) -> void { getVehicleApi(vehicle_name)->setAngleLevelControllerGains(kp, ki, kd); }); (static_cast<rpc::server*>(getServer()))->bind("setAngleRateControllerGains", [&](const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) -> void { getVehicleApi(vehicle_name)->setAngleRateControllerGains(kp, ki, kd); }); (static_cast<rpc::server*>(getServer()))->bind("setVelocityControllerGains", [&](const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) -> void { getVehicleApi(vehicle_name)->setVelocityControllerGains(kp, ki, kd); }); (static_cast<rpc::server*>(getServer()))->bind("setPositionControllerGains", [&](const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name) -> void { getVehicleApi(vehicle_name)->setPositionControllerGains(kp, ki, kd); }); (static_cast<rpc::server*>(getServer()))->bind("moveByRC", [&](const MultirotorRpcLibAdaptors::RCData& data, const std::string& vehicle_name) -> void { getVehicleApi(vehicle_name)->moveByRC(data.to()); }); (static_cast<rpc::server*>(getServer()))->bind("setSafety", [&](uint enable_reasons, float obs_clearance, const SafetyEval::ObsAvoidanceStrategy& obs_startegy, float obs_avoidance_vel, const MultirotorRpcLibAdaptors::Vector3r& origin, float xy_length, float max_z, float min_z, const std::string& vehicle_name) -> bool { return getVehicleApi(vehicle_name)->setSafety(SafetyEval::SafetyViolationType(enable_reasons), obs_clearance, obs_startegy, obs_avoidance_vel, origin.to(), xy_length, max_z, min_z); }); //getters // Rotor state (static_cast<rpc::server*>(getServer()))->bind("getRotorStates", [&](const std::string& vehicle_name) -> MultirotorRpcLibAdaptors::RotorStates { return MultirotorRpcLibAdaptors::RotorStates(getVehicleApi(vehicle_name)->getRotorStates()); }); // Multirotor state (static_cast<rpc::server*>(getServer()))->bind("getMultirotorState", [&](const std::string& vehicle_name) -> MultirotorRpcLibAdaptors::MultirotorState { return MultirotorRpcLibAdaptors::MultirotorState(getVehicleApi(vehicle_name)->getMultirotorState()); }); } //required for pimpl MultirotorRpcLibServer::~MultirotorRpcLibServer() { } } } //namespace #endif #endif
AirSim/AirLib/src/vehicles/multirotor/api/MultirotorRpcLibServer.cpp/0
{ "file_path": "AirSim/AirLib/src/vehicles/multirotor/api/MultirotorRpcLibServer.cpp", "repo_id": "AirSim", "token_count": 4484 }
17
# Changelog This page has moved [here](https://github.com/microsoft/AirSim/blob/main/docs/CHANGELOG.md).
AirSim/CHANGELOG.md/0
{ "file_path": "AirSim/CHANGELOG.md", "repo_id": "AirSim", "token_count": 38 }
18
ECHO OFF SET NUM=1000 SET AIRSIMPATH=E:\AirSimBinaries SET DATAPATH=D:\Data\AirSim SET EXE=DataCollectorSGM.exe mkdir %DATAPATH% START /I %AIRSIMPATH%\Africa\Africa_001.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\AA TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM Africa_001.exe START /I %AIRSIMPATH%\AirSimNH\AirSimNH.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\NH TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM AirSimNH.exe START /I %AIRSIMPATH%\CityEnviron\CityEnviron.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\CE TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM CityEnviron.exe START /I %AIRSIMPATH%\Coastline\Coastline.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\CL TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM Coastline.exe START /I %AIRSIMPATH%\Forest\Forest.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\FT TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM Forest.exe START /I %AIRSIMPATH%\LandscapeMountains\LandscapeMountains.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\LM TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM LandscapeMountains.exe START /I %AIRSIMPATH%\SimpleMaze\Car_Maze.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\SM TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM Car_Maze.exe START /I %AIRSIMPATH%\Warehouse\Factory.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\WH TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM Factory.exe START /I %AIRSIMPATH%\ZhangJiaJie\ZhangJiaJie.exe -windowed TIMEOUT 30 & REM Waits 30 seconds START /B /wait %EXE% %NUM% %DATAPATH%\ZJ TIMEOUT 10 & REM Waits 10 seconds TASKKILL /F /IM ZhangJiaJie.exe
AirSim/Examples/DataCollection/exe/getData.bat/0
{ "file_path": "AirSim/Examples/DataCollection/exe/getData.bat", "repo_id": "AirSim", "token_count": 778 }
19
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="16.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), AirSim.props))\AirSim.props" /> <PropertyGroup> <ShowAllFiles>true</ShowAllFiles> </PropertyGroup> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="RelWithDebInfo|Win32"> <Configuration>RelWithDebInfo</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="RelWithDebInfo|x64"> <Configuration>RelWithDebInfo</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ClCompile Include="main.cpp" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\AirLib\AirLib.vcxproj"> <Project>{4bfb7231-077a-4671-bd21-d3ade3ea36e7}</Project> </ProjectReference> <ProjectReference Include="..\MavLinkCom\MavLinkCom.vcxproj"> <Project>{8510c7a4-bf63-41d2-94f6-d8731d137a5a}</Project> </ProjectReference> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{4358ED90-CCA1-47A8-8D68-A260F212931E}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>HelloCar</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v143</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="Shared"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(ProjectDir)temp\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir> <OutDir>$(ProjectDir)build\$(Platform)\$(Configuration)\</OutDir> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <LanguageStandard>stdcpp17</LanguageStandard> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level4</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>_SCL_SECURE_NO_WARNINGS;_CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <DisableSpecificWarnings>4100;4505;4820;4464;4514;4710;4571;%(DisableSpecificWarnings)</DisableSpecificWarnings> <LanguageStandard>stdcpp17</LanguageStandard> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <LanguageStandard>stdcpp17</LanguageStandard> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>Disabled</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <LanguageStandard>stdcpp17</LanguageStandard> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <LanguageStandard>stdcpp17</LanguageStandard> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>Disabled</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include</AdditionalIncludeDirectories> <TreatWarningAsError>true</TreatWarningAsError> <AdditionalOptions>/w34263 /w34266 %(AdditionalOptions)</AdditionalOptions> <LanguageStandard>stdcpp17</LanguageStandard> <WholeProgramOptimization>false</WholeProgramOptimization> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>rpc.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
AirSim/HelloCar/HelloCar.vcxproj/0
{ "file_path": "AirSim/HelloCar/HelloCar.vcxproj", "repo_id": "AirSim", "token_count": 5887 }
20
using LogViewer.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace LogViewer.Controls { /// <summary> /// Interaction logic for AppSettings.xaml /// </summary> public partial class AppSettings : UserControl { public AppSettings() { InitializeComponent(); List<AppTheme> items = new List<AppTheme>(); items.Add(AppTheme.Light); items.Add(AppTheme.Dark); ThemeSelection.ItemsSource = items; ThemeSelection.SelectedItem = Settings.Instance.Theme; ThemeSelection.SelectionChanged += ThemeSelection_SelectionChanged; } private void OnCloseClicked(object sender, RoutedEventArgs e) { this.Visibility = Visibility.Collapsed; } private void ThemeSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems != null && e.AddedItems.Count > 0) { Settings.Instance.Theme = (AppTheme)e.AddedItems[0]; } } } }
AirSim/LogViewer/LogViewer/Controls/AppSettings.xaml.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/AppSettings.xaml.cs", "repo_id": "AirSim", "token_count": 578 }
21
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using LogViewer.Utilities; using System.Windows; using System.Windows.Input; namespace LogViewer.Controls { class ScrollViewerLite : ScrollViewer { Border scrollerBorder = null; protected override void OnScrollChanged(ScrollChangedEventArgs e) { ShowScroller(); base.OnScrollChanged(e); } private void ShowScroller() { if (scrollerBorder == null) { scrollerBorder = (from border in this.FindDescendantsOfType<Border>() where border.Name == "PART_ScrollBorder" select border).FirstOrDefault(); } if (scrollerBorder != null) { bool rc = VisualStateManager.GoToElementState(scrollerBorder, "Scrolling", true); delayedActions.StartDelayedAction("HideScroller", () => { HideScroller(); }, TimeSpan.FromSeconds(2)); } } private void HideScroller() { if (Mouse.Captured != null) { // try again after mouse capture is cleared (user might be dragging the scrollbar thumb!) delayedActions.StartDelayedAction("HideScroller", () => { HideScroller(); }, TimeSpan.FromSeconds(2)); } else { VisualStateManager.GoToElementState(scrollerBorder, "NotScrolling", true); } } DelayedActions delayedActions = new DelayedActions(); } }
AirSim/LogViewer/LogViewer/Controls/ScrollViewerLite.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/ScrollViewerLite.cs", "repo_id": "AirSim", "token_count": 890 }
22
using System.Collections.Generic; using System.Linq; namespace LogViewer.Model { /// <summary> /// This class is used to provide schema information about the IDataLog, notice it is hierarchical, so it can /// be bound to a Tree control so user can drill into log item data at any level, the selected items can then /// be queried via IDataLog.GetDataValues. /// </summary> public class LogItemSchema { public LogItemSchema Parent { get; set; } public string Name { get; set; } public string Type { get; set; } // in case the Name is not unique (as is the case with multi_id formats in px4 logs) // the IDataLog implementor can use this field instead. public int Id { get; set; } private List<LogItemSchema> childItems; public LogItemSchema() { } public string GetFullName() { if (Parent != null) { return Parent.GetFullName() + "." + Name; } return Name; } public List<LogItemSchema> CopyChildren() { var list = this.childItems; if (list == null) { return new List<LogItemSchema>(); } lock (list) { return new List<LogItemSchema>(list); } } public bool HasChildren { get { return childItems != null && childItems.Count > 0; } } public bool IsNumeric { get { return Type == "sbyte" || Type == "byte" || Type == "SByte" || Type == "Byte" || Type == "UInt8" || Type == "Int8" || Type == "Int16" || Type == "UInt16" || Type == "Int32" || Type == "UInt32" || Type == "Int64" || Type == "UInt64" || Type == "Float" || Type == "Single" || Type == "Double"; } } public LogItemSchema Root { get { if (this.Parent == null) return this; return this.Parent.Root; } } public bool IsArray { get; internal set; } internal void Combine(LogItemSchema s) { Dictionary<string, LogItemSchema> index = new Dictionary<string, Model.LogItemSchema>(); if (this.HasChildren) { lock (this.childItems) { foreach (var i in this.childItems) { index[i.Name] = i; } } } if (s.HasChildren) { lock (s.childItems) { foreach (var child in s.childItems) { LogItemSchema found = null; if (index.TryGetValue(child.Name, out found)) { found.Combine(child); } else { LogItemSchema copy = child.Clone(); copy.Parent = this; this.AddChild(child); } } } } } private LogItemSchema Clone() { LogItemSchema copy = new LogItemSchema() { Id = this.Id, Name = this.Name, Type = this.Type }; if (this.HasChildren) { lock (this.childItems) { foreach (var child in this.childItems) { var childClone = child.Clone(); copy.AddChild(childClone); } } } return copy; } internal bool HasChild(string name) { if (this.childItems == null) { return false; } lock (this.childItems) { return (from c in this.childItems where c.Name == name select c).Any(); } } internal void AddChild(LogItemSchema item) { if (this.childItems == null) { this.childItems = new List<LogItemSchema>(); } item.Parent = this; lock (this.childItems) { this.childItems.Add(item); } } } }
AirSim/LogViewer/LogViewer/Model/LogItemSchema.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Model/LogItemSchema.cs", "repo_id": "AirSim", "token_count": 2678 }
23
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; namespace LogViewer.Utilities { public static class MathHelpers { /// <summary> /// Return the Mean of the given numbers. /// </summary> public static double Mean(IEnumerable<double> values) { double sum = 0; double count = 0; foreach (double d in values) { sum += d; count++; } if (count == 0) return 0; return sum / count; } public static double StandardDeviation(IEnumerable<double> values) { double mean = Mean(values); double totalSquares = 0; int count = 0; foreach (double v in values) { count++; double diff = mean - v; totalSquares += diff * diff; } if (count == 0) { return 0; } return Math.Sqrt((double)(totalSquares / (double)count)); } /// <summary> /// Return the variance, sum of the difference between each value and the mean, squared. /// </summary> public static double Variance(IEnumerable<double> values) { double mean = Mean(values); double variance = 0; double count = 0; foreach (double d in values) { double diff = (d - mean); variance += (diff * diff); count++; } return variance / count; } /// <summary> /// Return the covariance in the given x,y values. /// The sum of the difference between x and its mean times the difference between y and its mean. /// </summary> public static double Covariance(IEnumerable<Point> pts) { double xsum = 0; double ysum = 0; double count = 0; foreach (Point d in pts) { xsum += d.X; ysum += d.Y; count++; } if (count == 0) return 0; double xMean = xsum / count; double yMean = ysum / count; double covariance = 0; foreach (Point d in pts) { covariance += (d.X - xMean) * (d.Y - yMean); } return covariance; } /// <summary> /// Compute the trend line through the given points, and return the line in the form: /// y = a + b.x /// </summary> /// <param name="pts">The data to analyze</param> /// <param name="a">The y-coordinate of the line at x = 0</param> /// <param name="b">The slope of the line</param> public static void LinearRegression(IEnumerable<Point> pts, out double a, out double b) { double xMean = Mean(from p in pts select p.X); double yMean = Mean(from p in pts select p.Y); double xVariance = Variance(from p in pts select p.X); double yVariance = Variance(from p in pts select p.Y); double covariance = Covariance(pts); if (xVariance == 0) { a = yMean; b = 1; } else { b = covariance / xVariance; a = yMean - (b * xMean); } } } }
AirSim/LogViewer/LogViewer/Utilities/MathHelpers.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Utilities/MathHelpers.cs", "repo_id": "AirSim", "token_count": 1859 }
24
using Microsoft.Networking.Mavlink; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Networking { public class UdpPort : IPort { System.Net.Sockets.UdpClient udp; IPEndPoint remoteEndPoint; AutoResetEvent received = new AutoResetEvent(false); bool receivingPending; IPEndPoint localEndPoint; public IPEndPoint LocalEndPoint { get { return this.localEndPoint; } } /// <summary> /// Connect to any remote machine that wants to send to the given local port. /// </summary> public void Connect(IPEndPoint localEndPoint) { this.localEndPoint = localEndPoint; udp = new System.Net.Sockets.UdpClient(localEndPoint); udp.Client.ReceiveBufferSize = 1000000; receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); } public static IEnumerable<NetworkInterface> GetLocalAddresses() { foreach (var network in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { if (network.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback && network.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) { var ipProps = network.GetIPProperties(); if (ipProps != null) { yield return network; } } } } /// <summary> /// Connect to specific remote end point and only send and receive from that endpoint. /// </summary> /// <param name="endPoint"></param> public void Connect(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { this.remoteEndPoint = remoteEndPoint; udp = new UdpClient(localEndPoint); receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); } public IPEndPoint WaitForOneMessage(TimeSpan delay) { received.WaitOne(delay); return remoteEndPoint; } private void OnPacketReceived(IAsyncResult ar) { if (udp != null) { lock (udp) { receivingPending = false; IPEndPoint remoteEP = null; try { byte[] bytes = udp.EndReceive(ar, ref remoteEP); if (bytes != null && bytes.Length > 0) { remoteEndPoint = remoteEP; lock (packets) { bool first = packets.Count == 0; packets.Add(bytes); if (first) { received.Set(); } } // begin another. if (udp != null) { receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); } } } catch (SocketException ex) { // receive is forceably closed on send, so ignore that if (ex.SocketErrorCode != SocketError.ConnectionReset) { //throw; } } catch (Exception) { // perhaps it was closed... } } } } public void Write(byte[] buffer, int count) { if (udp == null) { throw new Exception("UdpPort is not connected"); } lock (udp) { if (this.remoteEndPoint != null) { udp.Send(buffer, count, remoteEndPoint); } } if (!receivingPending) { // then previous receive would be cancelled by this send, so start receiving again. receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); } } public void Write(string msg) { byte[] buffer = Encoding.UTF8.GetBytes(msg); Write(buffer, buffer.Length); } private void OnSent(IAsyncResult ar) { if (udp != null) { int bytesSent = udp.EndSend(ar); } } public int Read(byte[] buffer, int bytesToRead) { if (packets.Count == 0) { received.WaitOne(); } int pos = 0; while (pos < bytesToRead) { if (current == null) { lock (packets) { current = packets[0]; packets.RemoveAt(0); currentPos = 0; } } int available = current.Length - currentPos; if (available > bytesToRead - pos) { // partial int toCopy = bytesToRead - pos; Array.Copy(current, currentPos, buffer, pos, toCopy); pos = bytesToRead; currentPos += toCopy; } else { // consume all. Array.Copy(current, currentPos, buffer, pos, available); pos += available; current = null; currentPos = 0; } } return pos; } public void Close() { if (udp != null) { udp.Close(); udp = null; } } byte[] current; int currentPos; List<byte[]> packets = new List<byte[]>(); } }
AirSim/LogViewer/Networking/UdpPort.cs/0
{ "file_path": "AirSim/LogViewer/Networking/UdpPort.cs", "repo_id": "AirSim", "token_count": 3905 }
25
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <Text Include="ReadMe.txt" /> </ItemGroup> <ItemGroup> <ClInclude Include="stdafx.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="targetver.h"> <Filter>Header Files</Filter> </ClInclude> </ItemGroup> <ItemGroup> <ClCompile Include="stdafx.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="MavlinkMoCap.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> </Project>
AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.vcxproj.filters/0
{ "file_path": "AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.vcxproj.filters", "repo_id": "AirSim", "token_count": 590 }
26
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // PX4.cpp : Defines the entry point for the console application. #include "Utils.hpp" #include "FileSystem.hpp" #include "MavLinkTcpServer.hpp" #include "MavLinkConnection.hpp" #include "MavLinkVehicle.hpp" #include "MavLinkMessages.hpp" #include "MavLinkLog.hpp" #include "Commands.h" #include <iostream> #include <vector> #include <string.h> #include <functional> #include <mutex> #include <map> #include <ctime> STRICT_MODE_OFF #include "json.hpp" STRICT_MODE_ON #include "UnitTests.h" #include <filesystem> using namespace std::filesystem; /* enable math defines on Windows */ #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 // pi/2 #endif static const int pixhawkVendorId = 9900; ///< Vendor ID for Pixhawk board (V2 and V1) and PX4 Flow static const int pixhawkFMUV4ProductId = 18; ///< Product ID for Pixhawk V2 board static const int pixhawkFMUV2ProductId = 17; ///< Product ID for Pixhawk V2 board static const int pixhawkFMUV5ProductId = 50; ///< Product ID for Pixhawk V5 board static const int pixhawkFMUV2OldBootloaderProductId = 22; ///< Product ID for Bootloader on older Pixhawk V2 boards //static const int pixhawkFMUV1ProductId = 16; ///< Product ID for PX4 FMU V1 board #define MAV_AUTOPILOT_ENUM_END (static_cast<uint8_t>(MAV_AUTOPILOT::MAV_AUTOPILOT_ASLUAV) + 1) #define MAV_TYPE_ENUM_END (static_cast<uint8_t>(MAV_TYPE::MAV_TYPE_ADSB) + 1) #define MAV_STATE_ENUM_END (static_cast<uint8_t>(MAV_STATE::MAV_STATE_POWEROFF) + 1) typedef mavlink_utils::Utils Utils; typedef mavlink_utils::FileSystem FileSystem; typedef unsigned int uint; using namespace mavlinkcom; struct FlagName { public: int Flag; const char* Name; }; class PortAddress { public: std::string addr; int port; }; #ifdef _WIN32 #include <Windows.h> void DebugOutput(const char* message, ...) { va_list args; va_start(args, message); std::unique_ptr<char[]> buffer(new char[8000]); vsprintf(buffer.get(), message, args); OutputDebugStringA(buffer.get()); OutputDebugStringA("\n"); fflush(stdout); va_end(args); } #else // how do you write to the debug output windows on Unix ? __attribute__((__format__(__printf__, 1, 0))) void DebugOutput(const char* message, ...) { va_list args; va_start(args, message); std::unique_ptr<char[]> buffer(new char[8000]); IGNORE_FORMAT_STRING_ON vsprintf(buffer.get(), message, args); IGNORE_FORMAT_STRING_OFF fflush(stdout); va_end(args); } #endif const int LocalSystemId = 166; const int LocalLogViewerSystemId = 167; const int LocalComponentId = 1; #define DEFAULT_BUFLEN 512 std::string defaultLocalAddress{ "127.0.0.1" }; // The remote app is connected to Pixhawk, and is also "serving" UDP packets, this tells us what remote // connection to create to talke to that server. bool offboard = false; bool udp = false; bool tcp = false; PortAddress offboardEndPoint; #define DEFAULT_OFFBOARD_UDP_PORT 14560 #define DEFAULT_OFFBOARD_TCP_PORT 4560 // SITL setup info const uint8_t sim_sysid = 142; const int sim_compid = 42; #define DEFAULT_SITL_PORT 14580 bool sitl = false; PortAddress sitlEndPoint; // The local ethernet interface to use (default localhost). PortAddress localEndPoint; // this is used if you want to connect MavLinkTest to the serial port of the Pixhawk directly bool serial = false; std::string comPort; int baudRate = 115200; // server mode on UDP is when you want another app to connect to Pixhawk and publish data back to this process. // this server will be listening for UDP packets, this is mutually exclusive with 'offboard' as this // server will become the primary "droneConnection". For example, jMAVSim can talk to this server // using their the -qgc option. Server mode on TCP means mavlinktest will do an "accept" socket which is // what PX4 is waiting for when it is running in TCP mode. Here the serverEndPoint is different from the // offboardEndPoint. The serverEndPoint specifies which local address to use in case your computer has // multiple network interfaces. bool server = false; bool connectLogViewer = false; PortAddress logViewerEndPoint; #define DEFAULT_LOGVIEWER_PORT 14388 // These are used to echo the mavlink messages to other 3rd party apps like QGC or LogViewer. std::vector<PortAddress> proxyEndPoints; #define DEFAULT_PROXY_PORT 14580 // this switch controls whether we turn off the RC remote active link loss detection // if you do not have radio connected this is needed to stop "failsafe" override in pixhawk // from kicking in when you try and fly. bool noRadio = false; bool unitTest = false; bool verbose = false; bool nsh = false; bool noparams = false; std::string logDirectory; std::string ifaceName; bool jsonLogFormat = false; bool csvLogFormat = false; bool convertExisting = false; std::vector<int> filterTypes; std::shared_ptr<MavLinkFileLog> inLogFile; std::shared_ptr<MavLinkFileLog> outLogFile; std::thread telemetry_thread; bool telemetry = false; std::mutex logLock; std::stringstream initScript; std::shared_ptr<MavLinkConnection> droneConnection; std::shared_ptr<MavLinkConnection> logConnection; std::shared_ptr<MavLinkVehicle> mavLinkVehicle; std::shared_ptr<MavLinkNode> hilNode; // for simulation. std::vector<PortAddress> usedPorts; void ConvertLogFileToJson(std::string logFile) { std::string fullPath = FileSystem::getFullPath(logFile); printf("Converting logfile to json: %s...", fullPath.c_str()); try { MavLinkMessage msg; MavLinkFileLog log; log.openForReading(fullPath); path jsonPath(logFile); jsonPath.replace_extension(".json"); MavLinkFileLog jsonLog; jsonLog.openForWriting(jsonPath.generic_string(), true); uint64_t timestamp; while (log.read(msg, timestamp)) { jsonLog.write(msg, timestamp); } jsonLog.close(); printf("done\n"); } catch (std::exception& ex) { printf("error: %s\n", ex.what()); } } class CsvWriter { std::ofstream csvFile; bool begin; std::string delimiter; public: CsvWriter(std::string fileName, std::string tabDelimiter) { csvFile.open(fileName.c_str()); this->delimiter = tabDelimiter; } ~CsvWriter() { csvFile.close(); } void BeginRow() { begin = true; } void WriteValue(const std::string& value) { if (begin) { begin = false; } else { csvFile << delimiter; } csvFile << value; } void WriteValue(double value) { if (begin) { begin = false; } else { csvFile << delimiter; } csvFile << value; } void EndRow() { csvFile << std::endl; } }; void ConvertLogFileToCsv(std::string logFile, int filter) { std::string fullPath = FileSystem::getFullPath(logFile); printf("Converting logfile to csv: %s...", fullPath.c_str()); try { MavLinkMessage msg; MavLinkFileLog log; log.openForReading(fullPath); path jsonPath(logFile); jsonPath.replace_extension(".csv"); CsvWriter csv(jsonPath.generic_string(), "\t"); bool headers = true; uint64_t timestamp; while (log.read(msg, timestamp)) { if (msg.msgid == filter) { MavLinkMessageBase* strongTypedMsg = MavLinkMessageBase::lookup(msg); if (strongTypedMsg != nullptr) { strongTypedMsg->timestamp = timestamp; std::string line = strongTypedMsg->toJSon(); line = line.substr(0, line.size() - 1); // remove trailing comma. // parse the json nlohmann::json doc; std::stringstream ss; ss << line; ss >> doc; auto name = doc["name"].get<std::string>(); if (headers) { headers = false; csv.BeginRow(); for (auto it = doc.begin(); it != doc.end(); ++it) { auto v = it.value(); if (v.is_object()) { // flatten inner mavlink object for (auto itm = v.begin(); itm != v.end(); ++itm) { csv.WriteValue(itm.key()); } } else { csv.WriteValue(it.key()); } } csv.EndRow(); } csv.BeginRow(); for (auto it = doc.begin(); it != doc.end(); ++it) { auto v = it.value(); if (v.is_object()) { // flatten inner mavlink object for (auto itm = v.begin(); itm != v.end(); ++itm) { auto vm = itm.value(); if (vm.is_number()) { csv.WriteValue(vm.get<double>()); } else if (vm.is_string()) { csv.WriteValue(vm.get<std::string>()); } else { // todo csv.WriteValue(""); } } } else { auto m = it.value(); if (m.is_number()) { csv.WriteValue(m.get<double>()); } else if (m.is_string()) { csv.WriteValue(m.get<std::string>()); } else { // todo csv.WriteValue(""); } } } csv.EndRow(); delete strongTypedMsg; } } }; printf("done\n"); } catch (std::exception& ex) { printf("error: %s\n", ex.what()); } } void LoadInitScript(std::string fileName) { std::ifstream fs; std::string line; FileSystem::openTextFile(fileName, fs); while (!fs.eof()) { std::getline(fs, line); if (line.size() > 0) { initScript << line << std::endl; } } } void ConvertLogFilesToJson(std::string directory) { if (directory == "") { printf("Please provide the -logdir option\n"); return; } printf("converting log files in: %s\n", directory.c_str()); auto fullPath = FileSystem::getFullPath(directory); if (!FileSystem::isDirectory(fullPath)) { printf("-logdir:%s, does not exist\n", fullPath.c_str()); } path dirPath(fullPath); for (directory_iterator next(dirPath), end; next != end; ++next) { auto path = next->path(); auto ext = path.extension(); if (ext == ".mavlink") { ConvertLogFileToJson(path.generic_string()); } } } void ConvertLogFilesToCsv(std::string directory) { if (filterTypes.size() != 1) { printf("When converting to csv, you must provide a single -filter value\n"); return; } if (directory == "") { printf("Please provide the -logdir option\n"); return; } int filter = filterTypes[0]; printf("extracting csv data for %d from log files in: %s\n", filter, directory.c_str()); auto fullPath = FileSystem::getFullPath(directory); if (!FileSystem::isDirectory(fullPath)) { printf("-logdir:%s, does not exist\n", fullPath.c_str()); } path dirPath(fullPath); for (directory_iterator next(dirPath), end; next != end; ++next) { auto path = next->path(); auto ext = path.extension(); if (ext == ".mavlink") { ConvertLogFileToCsv(path.generic_string(), filter); } } } void OpenLogFiles() { if (logDirectory.size() > 0) { std::time_t result = std::time(nullptr); auto local = std::localtime(&result); auto path = FileSystem::getFullPath(logDirectory); FileSystem::ensureFolder(path); path = FileSystem::combine(path, "logs"); FileSystem::ensureFolder(path); std::string today = Utils::stringf("%04d-%02d-%02d", local->tm_year + 1900, local->tm_mon + 1, local->tm_mday); path = FileSystem::combine(path, today); FileSystem::ensureFolder(path); const char* ext = jsonLogFormat ? "json" : "mavlink"; std::string input = Utils::stringf("%02d-%02d-%02d-input.%s", local->tm_hour, local->tm_min, local->tm_sec, ext); auto infile = FileSystem::combine(path, input); inLogFile = std::make_shared<MavLinkFileLog>(); inLogFile->openForWriting(infile, jsonLogFormat); std::string output = Utils::stringf("%02d-%02d-%02d-output.%s", local->tm_hour, local->tm_min, local->tm_sec, ext); auto outfile = FileSystem::combine(path, output); outLogFile = std::make_shared<MavLinkFileLog>(); outLogFile->openForWriting(outfile, jsonLogFormat); } } void CloseLogFiles() { if (inLogFile != nullptr) { inLogFile->close(); inLogFile = nullptr; } if (outLogFile != nullptr) { outLogFile->close(); outLogFile = nullptr; } } const static FlagName MavSysSensorFlags[] = { { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_GYRO), "MAV_SYS_STATUS_SENSOR_3D_GYRO - 0x01 3D gyro" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_ACCEL), "MAV_SYS_STATUS_SENSOR_3D_ACCEL - 0x02 3D accelerometer" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_MAG), "MAV_SYS_STATUS_SENSOR_3D_MAG - 0x04 3D magnetometer" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE), "MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE - 0x08 absolute pressure" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE), "MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE - 0x10 differential pressure" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_GPS), "MAV_SYS_STATUS_SENSOR_GPS - 0x20 GPS" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW), "MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW - 0x40 optical flow" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_VISION_POSITION), "MAV_SYS_STATUS_SENSOR_VISION_POSITION - 0x80 computer vision position" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_LASER_POSITION), "MAV_SYS_STATUS_SENSOR_LASER_POSITION - 0x100 laser based position" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH), "MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH - 0x200 external ground truth (Vicon or Leica)" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL), "MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL - 0x400 3D angular rate control" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION), "MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION - 0x800 attitude stabilization" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_YAW_POSITION), "MAV_SYS_STATUS_SENSOR_YAW_POSITION - 0x1000 yaw position" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL), "MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL - 0x2000 z/altitude control" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL), "MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL - 0x4000 x/y position control" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS), "MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS - 0x8000 motor outputs / control" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_RC_RECEIVER), "MAV_SYS_STATUS_SENSOR_RC_RECEIVER - 0x10000 rc receiver" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_GYRO2), "MAV_SYS_STATUS_SENSOR_3D_GYRO2 - 0x20000 2nd 3D gyro" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_ACCEL2), "MAV_SYS_STATUS_SENSOR_3D_ACCEL2 - 0x40000 2nd 3D accelerometer" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_SENSOR_3D_MAG2), "MAV_SYS_STATUS_SENSOR_3D_MAG2 - 0x80000 2nd 3D magnetometer" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_GEOFENCE), "MAV_SYS_STATUS_GEOFENCE - 0x100000 geofence" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_AHRS), "MAV_SYS_STATUS_AHRS - 0x200000 AHRS subsystem health" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_TERRAIN), "MAV_SYS_STATUS_TERRAIN - 0x400000 Terrain subsystem health" }, { static_cast<int>(MAV_SYS_STATUS_SENSOR::MAV_SYS_STATUS_REVERSE_MOTOR), "MAV_SYS_STATUS_REVERSE_MOTOR - 0x800000 Motors are reversed" }, { 0, NULL } }; const static char* AutoPilotNames[]{ "MAV_AUTOPILOT_GENERIC, Generic autopilot, full support for everything", "MAV_AUTOPILOT_RESERVED, Reserved for future use.", "MAV_AUTOPILOT_SLUGS, SLUGS autopilot, http://slugsuav.soe.ucsc.edu", "MAV_AUTOPILOT_ARDUPILOTMEGA, ArduPilotMega / ArduCopter, http://diydrones.com", "MAV_AUTOPILOT_OPENPILOT, OpenPilot, http://openpilot.org", "MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY, Generic autopilot only supporting simple waypoints", "MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY, Generic autopilot supporting waypoints and other simple navigation commands", "MAV_AUTOPILOT_GENERIC_MISSION_FULL, Generic autopilot supporting the full mission command set", "MAV_AUTOPILOT_INVALID, No valid autopilot, e.g. a GCS or other MAVLink component", "MAV_AUTOPILOT_PPZ, PPZ UAV - http://nongnu.org/paparazzi", "MAV_AUTOPILOT_UDB, UAV Dev Board", "MAV_AUTOPILOT_FP, FlexiPilot", "MAV_AUTOPILOT_PX4, PX4 Autopilot - http://pixhawk.ethz.ch/px4/", "MAV_AUTOPILOT_SMACCMPILOT, SMACCMPilot - http://smaccmpilot.org", "MAV_AUTOPILOT_AUTOQUAD, AutoQuad -- http://autoquad.org", "MAV_AUTOPILOT_ARMAZILA, Armazila -- http://armazila.com", "MAV_AUTOPILOT_AEROB, Aerob -- http://aerob.ru", "MAV_AUTOPILOT_ASLUAV, ASLUAV autopilot -- http://www.asl.ethz.ch" }; const static char* MavTypeNames[]{ "MAV_TYPE_GENERIC- Generic micro air vehicle.", "MAV_TYPE_FIXED_WING- Fixed wing aircraft.", "MAV_TYPE_QUADROTOR- Quadrotor", "MAV_TYPE_COAXIAL- Coaxial helicopter", "MAV_TYPE_HELICOPTER- Normal helicopter with tail rotor.", "MAV_TYPE_ANTENNA_TRACKER- Ground installation", "MAV_TYPE_GCS- Operator control unit / ground control station", "MAV_TYPE_AIRSHIP- Airship, controlled", "MAV_TYPE_FREE_BALLOON- Free balloon, uncontrolled", "MAV_TYPE_ROCKET- Rocket", "MAV_TYPE_GROUND_ROVER- Ground rover", "MAV_TYPE_SURFACE_BOAT- Surface vessel, boat, ship", "MAV_TYPE_SUBMARINE- Submarine", "MAV_TYPE_HEXAROTOR- Hexarotor", "MAV_TYPE_OCTOROTOR- Octorotor", "MAV_TYPE_TRICOPTER- Octorotor", "MAV_TYPE_FLAPPING_WING- Flapping wing", "MAV_TYPE_KITE- Flapping wing", "MAV_TYPE_ONBOARD_CONTROLLER- Onboard companion controller", "MAV_TYPE_VTOL_DUOROTOR- Two-rotor VTOL using control surfaces in vertical operation in addition. Tailsitter.", "MAV_TYPE_VTOL_QUADROTOR- Quad-rotor VTOL using a V-shaped quad config in vertical operation. Tailsitter.", "MAV_TYPE_VTOL_TILTROTOR- Tiltrotor VTOL", "MAV_TYPE_VTOL_RESERVED2- VTOL reserved 2", "MAV_TYPE_VTOL_RESERVED3- VTOL reserved 3", "MAV_TYPE_VTOL_RESERVED4- VTOL reserved 4", "MAV_TYPE_VTOL_RESERVED5- VTOL reserved 5", "MAV_TYPE_GIMBAL- Onboard gimbal", "MAV_TYPE_ADSB- Onboard ADSB peripheral" }; const static FlagName ModeFlagNames[]{ { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_TEST_ENABLED), "MAV_MODE_FLAG_TEST_ENABLED - system has a test mode enabled. This flag is intended for temporary system tests and should not be used for stable implementations." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_AUTO_ENABLED), "MAV_MODE_FLAG_AUTO_ENABLED - autonomous mode enabled, system finds its own goal positions. Guided flag can be set or not, depends on the actual implementation." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_GUIDED_ENABLED), "MAV_MODE_FLAG_GUIDED_ENABLED - guided mode enabled, system flies MISSIONs / mission items." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_STABILIZE_ENABLED), "MAV_MODE_FLAG_STABILIZE_ENABLED - system stabilizes electronically its attitude (and optionally position). It needs however further control inputs to move around." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_HIL_ENABLED), "MAV_MODE_FLAG_HIL_ENABLED - hardware in the loop simulation. All motors / actuators are blocked, but internal software is full operational." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_MANUAL_INPUT_ENABLED), "MAV_MODE_FLAG_MANUAL_INPUT_ENABLED - remote control input is enabled." }, { static_cast<int>(MAV_MODE_FLAG::MAV_MODE_FLAG_SAFETY_ARMED), "MAV_MODE_FLAG_SAFETY_ARMED - MAV safety set to armed. Motors are enabled / running / can start. Ready to fly." }, { 0, NULL } }; const static char* MavStateNames[]{ "MAV_STATE_UNINIT - Uninitialized system, state is unknown.", "MAV_STATE_BOOT - System is booting up.", "MAV_STATE_CALIBRATING - System is calibrating and not flight-ready.", "MAV_STATE_STANDBY - System is grounded and on standby. It can be launched any time.", "MAV_STATE_ACTIVE - System is active and might be already airborne. Motors are engaged.", "MAV_STATE_CRITICAL - System is in a non-normal flight mode. It can however still navigate.", "MAV_STATE_EMERGENCY - System is in a non-normal flight mode. It lost control over parts or over the whole airframe. It is in mayday and going down.", "MAV_STATE_POWEROFF - System just initialized its power-down sequence, will shut down now.", "MAV_STATE_ENUM_END - ", }; enum PX4_CUSTOM_MAIN_MODE { PX4_CUSTOM_MAIN_MODE_MANUAL = 1, PX4_CUSTOM_MAIN_MODE_ALTCTL, PX4_CUSTOM_MAIN_MODE_POSCTL, PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_MAIN_MODE_ACRO, PX4_CUSTOM_MAIN_MODE_OFFBOARD, PX4_CUSTOM_MAIN_MODE_STABILIZED, PX4_CUSTOM_MAIN_MODE_RATTITUDE }; enum PX4_CUSTOM_SUB_MODE_AUTO { PX4_CUSTOM_SUB_MODE_AUTO_READY = 1, PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF, PX4_CUSTOM_SUB_MODE_AUTO_LOITER, PX4_CUSTOM_SUB_MODE_AUTO_MISSION, PX4_CUSTOM_SUB_MODE_AUTO_RTL, PX4_CUSTOM_SUB_MODE_AUTO_LAND, PX4_CUSTOM_SUB_MODE_AUTO_RTGS, PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET }; const static FlagName CustomModeNames[]{ { PX4_CUSTOM_MAIN_MODE_MANUAL, "PX4_CUSTOM_MAIN_MODE_MANUAL" }, { PX4_CUSTOM_MAIN_MODE_ALTCTL, "PX4_CUSTOM_MAIN_MODE_ALTCTL" }, { PX4_CUSTOM_MAIN_MODE_POSCTL, "PX4_CUSTOM_MAIN_MODE_POSCTL" }, { PX4_CUSTOM_MAIN_MODE_AUTO, "PX4_CUSTOM_MAIN_MODE_AUTO" }, { PX4_CUSTOM_MAIN_MODE_ACRO, "PX4_CUSTOM_MAIN_MODE_ACRO" }, { PX4_CUSTOM_MAIN_MODE_OFFBOARD, "PX4_CUSTOM_MAIN_MODE_OFFBOARD" }, { PX4_CUSTOM_MAIN_MODE_STABILIZED, "PX4_CUSTOM_MAIN_MODE_STABILIZED" }, { PX4_CUSTOM_MAIN_MODE_RATTITUDE, "PX4_CUSTOM_MAIN_MODE_RATTITUDE" }, { 0, nullptr } }; const static FlagName CustomSubModeNames[]{ { PX4_CUSTOM_SUB_MODE_AUTO_READY, "PX4_CUSTOM_SUB_MODE_AUTO_READY" }, { PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF, "PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF" }, { PX4_CUSTOM_SUB_MODE_AUTO_LOITER, "PX4_CUSTOM_SUB_MODE_AUTO_LOITER" }, { PX4_CUSTOM_SUB_MODE_AUTO_MISSION, "PX4_CUSTOM_SUB_MODE_AUTO_MISSION" }, { PX4_CUSTOM_SUB_MODE_AUTO_RTL, "PX4_CUSTOM_SUB_MODE_AUTO_RTL" }, { PX4_CUSTOM_SUB_MODE_AUTO_LAND, "PX4_CUSTOM_SUB_MODE_AUTO_LAND" }, { PX4_CUSTOM_SUB_MODE_AUTO_RTGS, "PX4_CUSTOM_SUB_MODE_AUTO_RTGS" }, { PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET, "PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET" }, { 0, nullptr } }; void PrintFlags(const FlagName* flagNames, int value) { for (int i = 0;; i++) { if (flagNames[i].Name == NULL) break; if ((value & flagNames[i].Flag) != 0) { printf(" %s\n", flagNames[i].Name); } } } void PrintEnum(const FlagName* enumNames, int value) { for (int i = 0;; i++) { if (enumNames[i].Name == NULL) break; if (value == enumNames[i].Flag) { printf(" %s\n", enumNames[i].Name); } } } void PrintSystemStatus(MavLinkSysStatus& status) { printf("System status:\n"); printf(" onboard sensors present:\n"); PrintFlags(MavSysSensorFlags, status.onboard_control_sensors_present); printf(" onboard sensors enabled:\n"); PrintFlags(MavSysSensorFlags, status.onboard_control_sensors_enabled); printf(" CPU load %d\n", static_cast<int>(status.load)); printf(" battery voltage %d millivolts\n", static_cast<int>(status.voltage_battery)); printf(" battery current %d milliamps\n", static_cast<int>(status.current_battery)); printf(" drop_rate_comm = %d\n", static_cast<int>(status.drop_rate_comm)); printf(" errors_comm = %d\n", static_cast<int>(status.errors_comm)); printf(" battery_remaining = %d\n", static_cast<int>(status.battery_remaining)); } void PrintCustomMode(const MavLinkHeartbeat& heartbeat) { if (heartbeat.autopilot == static_cast<uint8_t>(MAV_AUTOPILOT::MAV_AUTOPILOT_PX4)) { int custom = (heartbeat.custom_mode >> 16); int mode = (custom & 0xff); int submode = (custom >> 8); PrintEnum(CustomModeNames, mode); PrintEnum(CustomSubModeNames, submode); } else { Utils::log(Utils::stringf(" Custom mode=%x", heartbeat.custom_mode)); } } void PrintHeartbeat(const MavLinkMessage& msg) { MavLinkHeartbeat heartbeat; heartbeat.decode(msg); Utils::log("Connected:\n"); Utils::log(Utils::stringf(" Version=%d\n", static_cast<int>(heartbeat.mavlink_version))); if (heartbeat.type < MAV_TYPE_ENUM_END) { Utils::log(Utils::stringf(" Type=%s\n", MavTypeNames[heartbeat.type])); } if (heartbeat.autopilot < MAV_AUTOPILOT_ENUM_END) { Utils::log(Utils::stringf(" Autopilot=%s\n", AutoPilotNames[heartbeat.autopilot])); } if (heartbeat.system_status < MAV_STATE_ENUM_END) { Utils::log(Utils::stringf(" State=%s\n", MavStateNames[heartbeat.system_status])); } Utils::log(" Base mode:\n"); PrintFlags(ModeFlagNames, heartbeat.base_mode); PrintCustomMode(heartbeat); Utils::log(Utils::stringf(" VEHICLE SYSTEM ID: %i\n", msg.sysid)); Utils::log(Utils::stringf(" VEHICLE COMPONENT ID: %i\n", msg.compid)); } uint32_t gCustom = 0; void CheckHeartbeat(const MavLinkMessage& msg) { MavLinkHeartbeat heartbeat; heartbeat.decode(msg); if (gCustom != heartbeat.custom_mode) { gCustom = heartbeat.custom_mode; PrintCustomMode(heartbeat); } } void mavlink_quaternion_to_dcm(const float quaternion[4], float dcm[3][3]) { double a = quaternion[0]; double b = quaternion[1]; double c = quaternion[2]; double d = quaternion[3]; double aSq = a * a; double bSq = b * b; double cSq = c * c; double dSq = d * d; dcm[0][0] = static_cast<float>(aSq + bSq - cSq - dSq); dcm[0][1] = static_cast<float>(2 * (b * c - a * d)); dcm[0][2] = static_cast<float>(2 * (a * c + b * d)); dcm[1][0] = static_cast<float>(2 * (b * c + a * d)); dcm[1][1] = static_cast<float>(aSq - bSq + cSq - dSq); dcm[1][2] = static_cast<float>(2 * (c * d - a * b)); dcm[2][0] = static_cast<float>(2 * (b * d - a * c)); dcm[2][1] = static_cast<float>(2 * (a * b + c * d)); dcm[2][2] = static_cast<float>(aSq - bSq - cSq + dSq); } void mavlink_dcm_to_euler(const float dcm[3][3], float* roll, float* pitch, float* yaw) { float phi, theta, psi; theta = asin(-dcm[2][0]); if (fabsf(theta - static_cast<float>(M_PI_2)) < 1.0e-3f) { phi = 0.0f; psi = (atan2f(dcm[1][2] - dcm[0][1], dcm[0][2] + dcm[1][1]) + phi); } else if (fabsf(theta + static_cast<float>(M_PI_2)) < 1.0e-3f) { phi = 0.0f; psi = atan2f(dcm[1][2] - dcm[0][1], dcm[0][2] + dcm[1][1] - phi); } else { phi = atan2f(dcm[2][1], dcm[2][2]); psi = atan2f(dcm[1][0], dcm[0][0]); } *roll = phi; *pitch = theta; *yaw = psi; } void mavlink_quaternion_to_euler(const float quaternion[4], float* roll, float* pitch, float* yaw) { float dcm[3][3]; mavlink_quaternion_to_dcm(quaternion, dcm); mavlink_dcm_to_euler(dcm, roll, pitch, yaw); } extern void mavlink_euler_to_quaternion(float roll, float pitch, float yaw, float quaternion[4]); void PrintUsage() { printf("Usage: PX4 options\n"); printf("Connects to PX4 either over udp or serial COM port\n"); printf("Options: \n"); printf(" -udp[:ipaddr[:port]] - connect to remote drone at this udp address (default port localhost:14550)\n"); printf(" -tcp[:ipaddr[:port]] - connect to remote drone at this tcp address (default port localhost:4560)\n"); printf(" -local[:ipaddr] - connect to remote drone via this local address (default localhost)\n"); printf(" -server - start mavlink server on specified -udp or -tcp local address\n"); printf(" -serial[:comPortName][, baudrate]] - open serial port\n"); printf(" -sitl[:ipaddr[:port]] - when talking to a SITL PX4 provide socket port number here for control channel (default localhost:14580)\n"); printf(" -logviewer:ipaddr[:port] - for sending mavlink information to Log Viewer\n"); printf(" -proxy:ipaddr[:port] - send all mavlink messages to and from remote node\n"); printf(" -local:ipaddr - specify local NIC address (default 127.0.0.1)\n"); printf(" -logdir:filename - specify local directory where mavlink logs are stored (default is no log files)\n"); printf(" -logformat:json - the default is binary .mavlink, if you specify this option you will get mavlink logs in json\n"); printf(" -convert:[json,csv] - convert all existing .mavlink log files in the logdir to the specified -logformat\n"); printf(" -filter:msid,msgid,... - while converting .mavlink log extract only the given mavlink message ids\n"); printf(" -noradio - disables RC link loss failsafe\n"); printf(" -nsh - enter NuttX shell immediately on connecting with PX4\n"); printf(" -telemetry - generate telemetry mavlink messages for logviewer\n"); printf(" -wifi:iface - add wifi rssi to the telemetry using given wifi interface name (e.g. wplsp0)\n"); printf("If no arguments it will find a COM port matching the name 'PX4'\n"); printf("You can specify -proxy multiple times with different port numbers to proxy drone messages out to multiple listeners\n"); } bool ParseCommandLine(int argc, const char* argv[]) { const char* logDirOption = "logdir"; const char* logformatOption = "logformat"; //const char* outLogFileOption = "outlogfile"; const char* wifiOption = "wifi"; const char* initOption = "init"; const char* filterOption = "filter"; const char* convertOption = "convert"; // parse command line for (int i = 1; i < argc; i++) { const char* arg = argv[i]; if (arg[0] == '-' || arg[0] == '/') { std::string option(arg + 1); std::vector<std::string> parts = Utils::split(option, ":,", 2); std::string lower = Utils::toLower(parts[0]); if (lower == "udp") { udp = true; offboard = true; offboardEndPoint.port = DEFAULT_OFFBOARD_UDP_PORT; if (parts.size() > 1) { offboardEndPoint.addr = parts[1]; if (parts.size() > 2) { offboardEndPoint.port = atoi(parts[2].c_str()); } } } else if (lower == "tcp") { tcp = true; offboard = true; offboardEndPoint.port = DEFAULT_OFFBOARD_TCP_PORT; if (parts.size() > 1) { offboardEndPoint.addr = parts[1]; if (parts.size() > 2) { offboardEndPoint.port = atoi(parts[2].c_str()); } } } else if (lower == "local") { localEndPoint.port = 0; // any port. if (parts.size() > 1) { localEndPoint.addr = parts[1]; if (parts.size() > 2) { localEndPoint.port = atoi(parts[2].c_str()); } } } else if (lower == "server") { server = true; } else if (lower == "sitl") { sitl = true; sitlEndPoint.port = 0; // any port. if (parts.size() > 1) { sitlEndPoint.addr = parts[1]; if (parts.size() > 2) { sitlEndPoint.port = atoi(parts[2].c_str()); } } } else if (lower == "proxy") { PortAddress ep; ep.port = DEFAULT_PROXY_PORT; if (parts.size() > 1) { ep.addr = parts[1]; if (parts.size() > 2) { ep.port = atoi(parts[2].c_str()); } } proxyEndPoints.push_back(ep); } else if (lower == "logviewer") { connectLogViewer = true; logViewerEndPoint.port = DEFAULT_LOGVIEWER_PORT; if (parts.size() > 1) { logViewerEndPoint.addr = parts[1]; if (parts.size() > 2) { logViewerEndPoint.port = atoi(parts[2].c_str()); } } } else if (lower == logDirOption) { if (parts.size() > 1) { std::string fileName(arg + 1 + strlen(logDirOption) + 1); logDirectory = fileName; } } else if (lower == logformatOption) { if (parts.size() > 1) { std::string format(arg + 1 + strlen(logformatOption) + 1); format = Utils::toLower(format); if (format == "json") { jsonLogFormat = true; } else { printf("### Error: invalid logformat '%s', expecting 'json'\n", format.c_str()); return false; } } } else if (lower == convertOption) { convertExisting = true; if (parts.size() > 1) { std::string format(arg + 1 + strlen(convertOption) + 1); format = Utils::toLower(format); if (format == "json") { jsonLogFormat = true; } else if (format == "csv") { csvLogFormat = true; } else { printf("### Error: invalid format '%s', expecting 'json'\n", format.c_str()); return false; } } } else if (lower == filterOption) { if (parts.size() > 1) { std::string filters(arg + 1 + strlen(filterOption) + 1); std::vector<std::string> fparts = Utils::split(filters, ",", 1); for (auto ptr = fparts.begin(), end = fparts.end(); ptr != end; ptr++) { std::string f = *ptr; try { long ft = std::stol(f); filterTypes.push_back(ft); } catch (std::exception&) { printf("expecting integer filter messagid, but found %s\n", f.c_str()); return false; } } } } #if defined(USE_CPP_FILESYSTEM) else if (lower == initOption) { if (parts.size() > 1) { std::string fileName(arg + 1 + strlen(initOption) + 1); LoadInitScript(fileName); } } #endif else if (lower == "local") { if (parts.size() > 1) { defaultLocalAddress = parts[1]; } } else if (lower == "serial") { serial = true; if (parts.size() > 1) { comPort = parts[1]; if (parts.size() > 2) { baudRate = atoi(parts[2].c_str()); if (baudRate == 0) { printf("### Error: invalid baud rate in -serial argument\n"); return false; } } } } else if (lower == "h" || lower == "?" || lower == "help" || lower == "-help") { return false; } else if (lower == "noradio") { noRadio = true; } else if (lower == "test") { unitTest = true; } else if (lower == "verbose") { verbose = true; } else if (lower == "nsh") { nsh = true; } else if (lower == "noparams") { noparams = true; } else if (lower == "telemetry") { telemetry = true; } else if (lower == wifiOption) { if (parts.size() > 1) { std::string name(arg + 1 + strlen(wifiOption) + 1); ifaceName = name; } } else { printf("### Error: unexpected argument: %s\n", arg); return false; } } else { printf("### Error: unexpected argument: %s\n", arg); return false; } } return true; } void HexDump(uint8_t* buffer, uint len) { for (uint i = 0; i < len; i += 16) { uint j = 0; for (j = i; j < i + 16 && j < len; j++) { uint8_t b = buffer[i + j]; printf("%02x ", b); } while (j < 16) { printf(" "); } for (j = i; j < i + 16 && j < len; j++) { uint8_t b = buffer[j]; if (b < 0x20 || b == 0x7f || b == 0xfe) { b = '.'; } printf("%c", b); } while (j < 16) { printf(" "); } printf("\n"); } } std::shared_ptr<MavLinkConnection> connectProxy(const PortAddress& endPoint, std::string name) { printf("Connecting to UDP Proxy address %s:%d\n", endPoint.addr.c_str(), endPoint.port); std::shared_ptr<MavLinkConnection> proxyConnection = MavLinkConnection::connectRemoteUdp(name, localEndPoint.addr, endPoint.addr, endPoint.port); // forward all PX4 messages to the remote proxy and all messages from remote proxy to PX4. droneConnection->join(proxyConnection); return proxyConnection; } std::string findPixhawk() { auto result = MavLinkConnection::findSerialPorts(0, 0); for (auto iter = result.begin(); iter != result.end(); iter++) { SerialPortInfo info = *iter; if (info.vid == pixhawkVendorId) { if (info.pid == pixhawkFMUV4ProductId || info.pid == pixhawkFMUV2ProductId || info.pid == pixhawkFMUV2OldBootloaderProductId || info.pid == pixhawkFMUV5ProductId) { printf("Auto Selecting COM port: %S\n", info.displayName.c_str()); std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::string portName_str = converter.to_bytes(info.portName); return portName_str; } } } return ""; } std::shared_ptr<MavLinkConnection> connectSerial() { std::string name = comPort; printf("Connecting to serial port %s, baudrate=%d\n", name.c_str(), baudRate); return MavLinkConnection::connectSerial("drone", name, baudRate, "sh /etc/init.d/rc.usb\n"); } std::shared_ptr<MavLinkConnection> connectOffboard() { printf("Connecting to offboard drone at address %s:%d\n", offboardEndPoint.addr.c_str(), offboardEndPoint.port); return MavLinkConnection::connectRemoteUdp("drone", defaultLocalAddress, offboardEndPoint.addr, offboardEndPoint.port); } std::shared_ptr<MavLinkConnection> connectServer(std::string name) { if (localEndPoint.addr == "") { localEndPoint.addr = defaultLocalAddress; } if (localEndPoint.port == 0) { localEndPoint.port = offboardEndPoint.port; } std::shared_ptr<MavLinkConnection> serverConnection; if (tcp) { if (localEndPoint.port == 0) { localEndPoint.port = DEFAULT_OFFBOARD_TCP_PORT; } printf("Waiting for drone to connect to server at address %s:%d...\n", localEndPoint.addr.c_str(), localEndPoint.port); MavLinkTcpServer server(localEndPoint.addr, localEndPoint.port); serverConnection = server.acceptTcp(name); } else { if (localEndPoint.port == 0) { localEndPoint.port = DEFAULT_OFFBOARD_UDP_PORT; } printf("Starting UDP Server on address %s:%d\n", localEndPoint.addr.c_str(), localEndPoint.port); serverConnection = MavLinkConnection::connectLocalUdp(name, localEndPoint.addr, localEndPoint.port); } if (droneConnection != nullptr) { // then we have a serial connection as the primary droneConnection, so publish all PX4 messages out to the server droneConnection->join(serverConnection); } else { // no local serial connection, so this is the primary droneConnection. droneConnection = serverConnection; } return serverConnection; } void runTelemetry() { while (telemetry) { std::this_thread::sleep_for(std::chrono::seconds(1)); if (droneConnection != nullptr) { MavLinkTelemetry tel; tel.wifiInterfaceName = ifaceName.c_str(); droneConnection->getTelemetry(tel); tel.compid = LocalComponentId; tel.sysid = LocalSystemId; if (logConnection != nullptr) { logConnection->sendMessage(tel); } } } } void startTelemetry() { Utils::cleanupThread(telemetry_thread); telemetry_thread = std::thread(&runTelemetry); } void stopTelemetry() { telemetry = false; if (telemetry_thread.joinable()) { telemetry_thread.join(); } } bool connect() { if (offboard && serial) { printf("Cannot connect to local -serial pixhawk and -udp drone at the same time \n"); return false; } if (!offboard && !serial) { printf("Must specify one of -serial, -udp or -tcp otherwise we don't have a drone connection\n"); return false; } if (offboardEndPoint.addr == "") { offboardEndPoint.addr = defaultLocalAddress; } if (localEndPoint.addr == "") { localEndPoint.addr = defaultLocalAddress; } if (serial) { droneConnection = connectSerial(); } else if (!server) { droneConnection = connectOffboard(); usedPorts.push_back(offboardEndPoint); } if (server) { std::shared_ptr<MavLinkConnection> serverConnection = connectServer("server"); usedPorts.push_back(localEndPoint); } return true; } void connectSitl(std::shared_ptr<MavLinkVehicle> mavLinkVehicle) { if (sitlEndPoint.port != 0) { sitlEndPoint.port = DEFAULT_SITL_PORT; } // need a retry loop here because we don't know how quickly px4 will start accepting these connections... for (int retries = 60; retries >= 0; retries--) { try { auto gcsConnection = mavlinkcom::MavLinkConnection::connectRemoteUdp("gcs", localEndPoint.addr, sitlEndPoint.addr, sitlEndPoint.port); mavLinkVehicle->connect(gcsConnection); } catch (std::exception&) { std::this_thread::sleep_for(std::chrono::seconds(1)); } } } bool setupDrone() { if (droneConnection == nullptr) { // failed to connect return false; } if (verbose) { droneConnection->subscribe([=](std::shared_ptr<MavLinkConnection> con, const MavLinkMessage& msg) { printf("Received msg %d from drone\n", static_cast<int>(msg.msgid)); }); } if (outLogFile != nullptr) { droneConnection->startLoggingSendMessage(outLogFile); } if (sitl) { // then we need 2 mavlink channels, one for sending/receiving HIL_* messages and the other // for controlling the drone. hilNode = std::make_shared<mavlinkcom::MavLinkNode>(sim_sysid, sim_compid); hilNode->connect(droneConnection); hilNode->startHeartbeat(); printf("TODO: for SITL to work, mavlinktest needs to simulate HIL_SENSOR messages...\n"); // this is the control channel. mavLinkVehicle = std::make_shared<MavLinkVehicle>(LocalSystemId, LocalComponentId); connectSitl(mavLinkVehicle); } else { mavLinkVehicle = std::make_shared<MavLinkVehicle>(LocalSystemId, LocalComponentId); mavLinkVehicle->connect(droneConnection); } mavLinkVehicle->startHeartbeat(); if (connectLogViewer) { if (logViewerEndPoint.addr == "") { logViewerEndPoint.addr = defaultLocalAddress; } logConnection = connectProxy(logViewerEndPoint, "log"); usedPorts.push_back(logViewerEndPoint); if (serial && telemetry) { startTelemetry(); } } else { logConnection = nullptr; } for (auto ptr = proxyEndPoints.begin(), end = proxyEndPoints.end(); ptr != end; ptr++) { bool ok = true; PortAddress proxyEndPoint = *ptr; for (auto ep = usedPorts.begin(), endep = usedPorts.end(); ep != endep; ep++) { PortAddress used = *ep; if (used.addr == proxyEndPoint.addr && used.port == proxyEndPoint.port) { printf("Cannot proxy to address that is already used: %s:%d\n", used.addr.c_str(), used.port); ok = false; } } if (ok) { usedPorts.push_back(proxyEndPoint); connectProxy(proxyEndPoint, "proxy"); } } return true; } void checkPulse() { MavLinkHeartbeat heartbeat; if (!mavLinkVehicle->waitForHeartbeat().wait(100000, &heartbeat)) { throw std::runtime_error("Received no heartbeat from PX4 after 100 seconds"); } } const char* IgnoreStateTable[] = { "Baro #0 fail: STALE!", nullptr }; void handleStatus(const MavLinkStatustext& statustext) { std::string msg = statustext.text; for (size_t i = 0; IgnoreStateTable[i] != nullptr; i++) { if (msg == IgnoreStateTable[i]) { return; } } std::string safeText(statustext.text, 50); Utils::log(Utils::stringf("STATUS: sev=%d, '%s'\n", static_cast<int>(statustext.severity), safeText.c_str())); } int console(std::stringstream& script) { std::string line; std::shared_ptr<MavLinkNode> logViewer = nullptr; Command* currentCommand = nullptr; OrbitCommand* orbit = new OrbitCommand(); SendImageCommand* sendImage = nullptr; NshCommand* nshCommand = new NshCommand(); std::vector<Command*> cmdTable; Command::setAllCommand(&cmdTable); cmdTable.push_back(new ArmDisarmCommand()); cmdTable.push_back(new TakeOffCommand()); cmdTable.push_back(new LandCommand()); cmdTable.push_back(new MissionCommand()); cmdTable.push_back(new LoiterCommand()); cmdTable.push_back(new CapabilitiesCommand()); cmdTable.push_back(new RtlCommand()); cmdTable.push_back(new GetParamsCommand()); cmdTable.push_back(new GetSetParamCommand()); cmdTable.push_back(new StatusCommand()); cmdTable.push_back(new PositionCommand()); cmdTable.push_back(new HilCommand()); cmdTable.push_back(new FakeGpsCommand()); cmdTable.push_back(new RequestImageCommand()); cmdTable.push_back(new FtpCommand()); cmdTable.push_back(new PlayLogCommand()); cmdTable.push_back(new DumpLogCommandsCommand()); cmdTable.push_back(nshCommand); // this is advanced command that can get us into trouble on real drone, so remove it for now. //cmdTable.push_back(new AltHoldCommand()); cmdTable.push_back(sendImage = new SendImageCommand()); cmdTable.push_back(new SetMessageIntervalCommand()); cmdTable.push_back(new BatteryCommand()); cmdTable.push_back(new WaitForAltitudeCommand()); droneConnection->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { MavLinkStatustext statustext; if (inLogFile != nullptr && inLogFile->isOpen()) { std::lock_guard<std::mutex> lock(logLock); inLogFile->write(message); } switch (message.msgid) { case MavLinkHeartbeat::kMessageId: CheckHeartbeat(message); break; case MavLinkAttitudeTarget::kMessageId: /* MavLinkAttitudeTarget target; target.decode(message); float pitch, roll, yaw; mavlink_quaternion_to_euler(target.q, &roll, &pitch, &yaw); float q2[4]; mavlink_euler_to_quaternion(roll, pitch, yaw, q2);*/ //DebugOutput("q1 : %f\t%f\t%f\t%g", target.q[0], target.q[1], target.q[2], target.q[3]); //DebugOutput("q2 : %f\t%f\t%f\t%g", q2[0], q2[1], q2[2], q2[3]); //DebugOutput("target roll: %f\tpitch: %f\tyaw:%f\tthrust: %f", roll, pitch, yaw, target.thrust); break; case MavLinkStatustext::kMessageId: // MAVLINK_MSG_ID_STATUSTEXT: statustext.decode(message); handleStatus(statustext); break; default: break; } }); if (logConnection != nullptr) { logViewer = std::make_shared<MavLinkNode>(LocalLogViewerSystemId, LocalComponentId); logViewer->connect(logConnection); orbit->setLogViewer(logViewer); sendImage->setLogViewer(logViewer); } // this stops us from being able to connect to SITL mode PX4. //checkPulse(); int retries = 0; while (retries++ < 5) { try { if (mavLinkVehicle->isLocalControlSupported()) { cmdTable.push_back(new GotoCommand()); cmdTable.push_back(new RotateCommand()); cmdTable.push_back(orbit); cmdTable.push_back(new SquareCommand()); cmdTable.push_back(new WiggleCommand()); } break; } catch (std::exception& e) { printf("isLocalControlSupported failed: %s\n", e.what()); } } if (noRadio) { MavLinkParameter p = mavLinkVehicle->getCachedParameter("NAV_RCL_ACT"); if (p.value != 0) { p.value = 0; mavLinkVehicle->setParameter(p); } } if (nsh) { currentCommand = nshCommand; currentCommand->Execute(mavLinkVehicle); } else { if (!noparams) { printf("Downloading drone parameters so we know how to control it properly...\n"); try { mavLinkVehicle->getParamList(); } catch (std::exception& e) { printf("%s\n", e.what()); } } mavLinkVehicle->setStabilizedFlightMode(); } printf("Ready...\n"); script << "status\n"; while (!std::cin.eof()) { if (!script.eof()) { std::getline(script, line); } else { printf("mavlink> "); std::getline(std::cin, line); } line = mavlink_utils::Utils::trim(line, ' '); if (line.length() > 0) { if (line.length() == 0) { continue; } std::vector<std::string> args = Command::parseArgs(line); std::string cmd = args[0]; if (cmd == "x") { break; } else if (cmd == "disconnect") { mavLinkVehicle->close(); } else if (cmd == "connect") { connect(); } else if (cmd == "?" || cmd == "help") { for (size_t i = 0; i < cmdTable.size(); i++) { Command* command = cmdTable[i]; if (args.size() > 1 && args[1] == command->Name) { command->PrintHelp(); break; } else { printf("%s\n", command->Name.c_str()); } } } else { Command* selected = Command::create(args); //add command text in log if (selected != nullptr && inLogFile != nullptr && inLogFile->isOpen()) { auto str = std::string(Command::kCommandLogPrefix) + line; MavLinkStatustext st; strncpy(st.text, str.c_str(), 50); MavLinkMessage m; st.encode(m); droneConnection->prepareForSending(m); std::lock_guard<std::mutex> lock(logLock); inLogFile->write(m); } if (currentCommand != nullptr && currentCommand != selected) { // close previous command. currentCommand->Close(); } currentCommand = selected; if (currentCommand != NULL) { try { currentCommand->Execute(mavLinkVehicle); } catch (const std::exception& e) { const char* reason = e.what(); if (reason == nullptr) { reason = "(unknown)"; } printf("Error: %s\n", reason); } } else { printf("Unknown command. Type '?' to get list of commands\n"); } } } } stopTelemetry(); logViewer = nullptr; droneConnection = nullptr; logConnection = nullptr; mavLinkVehicle = nullptr; CloseLogFiles(); return 0; } void completion(int state) { } int main(int argc, const char* argv[]) { if (!ParseCommandLine(argc, argv)) { PrintUsage(); return 1; } #if defined(USE_CPP_FILESYSTEM) if (convertExisting) { if (jsonLogFormat) { ConvertLogFilesToJson(logDirectory); } else if (csvLogFormat) { ConvertLogFilesToCsv(logDirectory); } else { //FilterLogFiles(logDirectory); } return 0; } #endif OpenLogFiles(); if (serial) { if (comPort.size() == 0 || comPort == "*") { comPort = findPixhawk(); if (comPort == "") { printf("### Error: PX4 not found on your SerialPort, or it is not available"); return 1; } } } try { if (unitTest) { UnitTests test; test.RunAll(comPort, baudRate); return 0; } if (!connect()) { return 1; } if (!setupDrone()) { return 1; } return console(initScript); } catch (const std::exception& e) { printf("Exception: %s\n", e.what()); } CloseLogFiles(); }
AirSim/MavLinkCom/MavLinkTest/main.cpp/0
{ "file_path": "AirSim/MavLinkCom/MavLinkTest/main.cpp", "repo_id": "AirSim", "token_count": 27971 }
27
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef commn_utils_type_utils_hpp #define commn_utils_type_utils_hpp #include <type_traits> #include <valarray> namespace mavlink_utils { namespace type_utils { //from: https://raw.githubusercontent.com/louisdx/cxx-prettyprint/master/prettyprint.hpp //also see https://gist.github.com/louisdx/1076849 namespace detail { // SFINAE type trait to detect whether T::const_iterator exists. struct sfinae_base { using yes = char; using no = yes[2]; }; template <typename T> struct has_const_iterator : private sfinae_base { private: template <typename C> static yes& test(typename C::const_iterator*); template <typename C> static no& test(...); public: static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes); using type = T; void dummy(); //for GCC to suppress -Wctor-dtor-privacy }; template <typename T> struct has_begin_end : private sfinae_base { private: template <typename C> static yes& f(typename std::enable_if< std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::begin)), typename C::const_iterator (C::*)() const>::value>::type*); template <typename C> static no& f(...); // using template parameter symbol 'D' instead of 'C' as a workaround for // VS2017 compiler issue (internal compiler error) starting 15.9.X releases. template <typename D> static yes& g(typename std::enable_if< std::is_same<decltype(static_cast<typename D::const_iterator (D::*)() const>(&D::end)), typename D::const_iterator (D::*)() const>::value, void>::type*); template <typename D> static no& g(...); public: static bool const beg_value = sizeof(f<T>(nullptr)) == sizeof(yes); static bool const end_value = sizeof(g<T>(nullptr)) == sizeof(yes); void dummy(); //for GCC to suppress -Wctor-dtor-privacy }; } // namespace detail // Basic is_container template; specialize to derive from std::true_type for all desired container types template <typename T> struct is_container : public std::integral_constant<bool, detail::has_const_iterator<T>::value && detail::has_begin_end<T>::beg_value && detail::has_begin_end<T>::end_value> { }; template <typename T, std::size_t N> struct is_container<T[N]> : std::true_type { }; template <std::size_t N> struct is_container<char[N]> : std::false_type { }; template <typename T> struct is_container<std::valarray<T>> : std::true_type { }; template <typename T1, typename T2> struct is_container<std::pair<T1, T2>> : std::true_type { }; template <typename... Args> struct is_container<std::tuple<Args...>> : std::true_type { }; } } //namespace #endif
AirSim/MavLinkCom/common_utils/type_utils.hpp/0
{ "file_path": "AirSim/MavLinkCom/common_utils/type_utils.hpp", "repo_id": "AirSim", "token_count": 1507 }
28
#pragma once // clang-format off #if defined(MAVLINK_USE_CXX_NAMESPACE) namespace mavlink { #elif defined(__cplusplus) extern "C" { #endif // Visual Studio versions before 2010 don't have stdint.h, so we just error out. #if (defined _MSC_VER) && (_MSC_VER < 1600) #error "The C-MAVLink implementation requires Visual Studio 2010 or greater" #endif #include <stdint.h> /** * * CALCULATE THE CHECKSUM * */ #define X25_INIT_CRC 0xffff #define X25_VALIDATE_CRC 0xf0b8 #ifndef HAVE_CRC_ACCUMULATE /** * @brief Accumulate the X.25 CRC by adding one char at a time. * * The checksum function adds the hash of one char at a time to the * 16 bit checksum (uint16_t). * * @param data new char to hash * @param crcAccum the already accumulated checksum **/ static inline void crc_accumulate(uint8_t data, uint16_t *crcAccum) { /*Accumulate one byte of data into the CRC*/ uint8_t tmp; tmp = data ^ (uint8_t)(*crcAccum &0xff); tmp ^= (tmp<<4); *crcAccum = (*crcAccum>>8) ^ (tmp<<8) ^ (tmp <<3) ^ (tmp>>4); } #endif /** * @brief Initiliaze the buffer for the X.25 CRC * * @param crcAccum the 16 bit X.25 CRC */ static inline void crc_init(uint16_t* crcAccum) { *crcAccum = X25_INIT_CRC; } /** * @brief Calculates the X.25 checksum on a byte buffer * * @param pBuffer buffer containing the byte array to hash * @param length length of the byte array * @return the checksum over the buffer bytes **/ static inline uint16_t crc_calculate(const uint8_t* pBuffer, uint16_t length) { uint16_t crcTmp; crc_init(&crcTmp); while (length--) { crc_accumulate(*pBuffer++, &crcTmp); } return crcTmp; } /** * @brief Accumulate the X.25 CRC by adding an array of bytes * * The checksum function adds the hash of one char at a time to the * 16 bit checksum (uint16_t). * * @param data new bytes to hash * @param crcAccum the already accumulated checksum **/ static inline void crc_accumulate_buffer(uint16_t *crcAccum, const char *pBuffer, uint16_t length) { const uint8_t *p = (const uint8_t *)pBuffer; while (length--) { crc_accumulate(*p++, crcAccum); } } #if defined(MAVLINK_USE_CXX_NAMESPACE) || defined(__cplusplus) } #endif // clang-format on
AirSim/MavLinkCom/mavlink/checksum.h/0
{ "file_path": "AirSim/MavLinkCom/mavlink/checksum.h", "repo_id": "AirSim", "token_count": 939 }
29
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "StrictMode.hpp" STRICT_MODE_OFF #define MAVLINK_PACKED #include "../mavlink/common/mavlink.h" #include "../mavlink/mavlink_types.h" #include "../mavlink/mavlink_helpers.h" STRICT_MODE_ON #include "MavLinkConnection.hpp" #include "MavLinkMessageBase.hpp" #include "Utils.hpp" #include <sstream> #include <cmath> using namespace mavlink_utils; using namespace mavlinkcom; int MavLinkMessage::update_checksum() { bool mavlink1 = protocol_version != 2; uint8_t header_len = MAVLINK_CORE_HEADER_LEN + 1; uint8_t buf[MAVLINK_CORE_HEADER_LEN + 1]; if (mavlink1) { magic = MAVLINK_STX_MAVLINK1; header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN + 1; } else { magic = MAVLINK_STX; } incompat_flags = 0; compat_flags = 0; // pack the payload buffer. char* payload = reinterpret_cast<char*>(&payload64[0]); int len = this->len; // calculate checksum const mavlink_msg_entry_t* entry = mavlink_get_msg_entry(msgid); uint8_t crc_extra = 0; int msglen = 0; if (entry != nullptr) { crc_extra = entry->crc_extra; msglen = entry->min_msg_len; } if (msgid == MavLinkTelemetry::kMessageId) { msglen = MavLinkTelemetry::MessageLength; // mavlink doesn't know about our custom telemetry message. } if (len != msglen) { // mavlink2 supports trimming the payload of trailing zeros so the messages // are variable length as a result. if (mavlink1) { throw std::runtime_error(Utils::stringf("Message length %d doesn't match expected length%d\n", len, msglen)); } } len = mavlink1 ? msglen : _mav_trim_payload(payload, msglen); this->len = len; // form the header as a byte array for the crc buf[0] = this->magic; buf[1] = this->len; if (mavlink1) { buf[2] = this->seq; buf[3] = this->sysid; buf[4] = this->compid; buf[5] = this->msgid & 0xFF; } else { buf[2] = this->incompat_flags; buf[3] = this->compat_flags; buf[4] = this->seq; buf[5] = this->sysid; buf[6] = this->compid; buf[7] = this->msgid & 0xFF; buf[8] = (this->msgid >> 8) & 0xFF; buf[9] = (this->msgid >> 16) & 0xFF; } this->checksum = crc_calculate(&buf[1], header_len - 1); crc_accumulate_buffer(&this->checksum, payload, len); crc_accumulate(crc_extra, &this->checksum); return len + header_len + 2; } void MavLinkMessageBase::decode(const MavLinkMessage& msg) { // unpack the message... this->msgid = msg.msgid; this->protocol_version = msg.protocol_version; unpack(reinterpret_cast<const char*>(msg.payload64)); } void MavLinkMessageBase::encode(MavLinkMessage& msg) const { msg.msgid = this->msgid; msg.sysid = this->sysid; msg.compid = this->compid; msg.protocol_version = this->protocol_version; // pack the payload buffer. int len = this->pack(reinterpret_cast<char*>(msg.payload64)); msg.len = len; } void MavLinkMessageBase::pack_uint8_t(char* buffer, const uint8_t* field, int offset) const { buffer[offset] = *reinterpret_cast<const char*>(field); } void MavLinkMessageBase::pack_int8_t(char* buffer, const int8_t* field, int offset) const { buffer[offset] = *reinterpret_cast<const char*>(field); } void MavLinkMessageBase::pack_int16_t(char* buffer, const int16_t* field, int offset) const { STRICT_MODE_OFF _mav_put_int16_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_uint16_t(char* buffer, const uint16_t* field, int offset) const { STRICT_MODE_OFF _mav_put_uint16_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_uint32_t(char* buffer, const uint32_t* field, int offset) const { STRICT_MODE_OFF _mav_put_uint32_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_int32_t(char* buffer, const int32_t* field, int offset) const { STRICT_MODE_OFF _mav_put_int32_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_uint64_t(char* buffer, const uint64_t* field, int offset) const { STRICT_MODE_OFF _mav_put_uint64_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_int64_t(char* buffer, const int64_t* field, int offset) const { STRICT_MODE_OFF _mav_put_int64_t(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_float(char* buffer, const float* field, int offset) const { STRICT_MODE_OFF _mav_put_float(buffer, offset, *field); STRICT_MODE_ON } void MavLinkMessageBase::pack_char_array(int len, char* buffer, const char* field, int offset) const { STRICT_MODE_OFF _mav_put_char_array(buffer, offset, field, len); STRICT_MODE_ON } void MavLinkMessageBase::pack_uint8_t_array(int len, char* buffer, const uint8_t* field, int offset) const { STRICT_MODE_OFF _mav_put_uint8_t_array(buffer, offset, field, len); STRICT_MODE_ON } void MavLinkMessageBase::pack_int8_t_array(int len, char* buffer, const int8_t* field, int offset) const { STRICT_MODE_OFF _mav_put_int8_t_array(buffer, offset, field, len); STRICT_MODE_ON } void MavLinkMessageBase::pack_uint16_t_array(int len, char* buffer, const uint16_t* field, int offset) const { STRICT_MODE_OFF _mav_put_uint16_t_array(buffer, offset, field, len); STRICT_MODE_ON } void MavLinkMessageBase::pack_int16_t_array(int len, char* buffer, const int16_t* field, int offset) const { STRICT_MODE_OFF _mav_put_int16_t_array(buffer, offset, field, len); STRICT_MODE_ON } void MavLinkMessageBase::pack_float_array(int len, char* buffer, const float* field, int offset) const { STRICT_MODE_OFF _mav_put_float_array(buffer, offset, field, len); STRICT_MODE_ON } #if MAVLINK_NEED_BYTE_SWAP #define _mav_get_uint16_t(buf, wire_offset, b) byte_swap_2(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int16_t(buf, wire_offset, b) byte_swap_2(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_uint32_t(buf, wire_offset, b) byte_swap_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int32_t(buf, wire_offset, b) byte_swap_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_uint64_t(buf, wire_offset, b) byte_swap_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int64_t(buf, wire_offset, b) byte_swap_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_float(buf, wire_offset, b) byte_swap_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_double(buf, wire_offset, b) byte_swap_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #elif !MAVLINK_ALIGNED_FIELDS #define _mav_get_uint16_t(buf, wire_offset, b) byte_copy_2(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int16_t(buf, wire_offset, b) byte_copy_2(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_uint32_t(buf, wire_offset, b) byte_copy_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int32_t(buf, wire_offset, b) byte_copy_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_uint64_t(buf, wire_offset, b) byte_copy_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_int64_t(buf, wire_offset, b) byte_copy_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_float(buf, wire_offset, b) byte_copy_4(reinterpret_cast<char*>(b), &buf[wire_offset], ) #define _mav_get_double(buf, wire_offset, b) byte_copy_8(reinterpret_cast<char*>(b), &buf[wire_offset], ) #else #define _mav_get_uint16_t(buf, wire_offset, b) *b = *reinterpret_cast<const uint16_t*>(&buf[wire_offset]) #define _mav_get_int16_t(buf, wire_offset, b) *b = *reinterpret_cast<const int16_t*>(&buf[wire_offset]) #define _mav_get_uint32_t(buf, wire_offset, b) *b = *reinterpret_cast<const uint32_t*>(&buf[wire_offset]) #define _mav_get_int32_t(buf, wire_offset, b) *b = *reinterpret_cast<const int32_t*>(&buf[wire_offset]) #define _mav_get_uint64_t(buf, wire_offset, b) *b = *reinterpret_cast<const uint64_t*>(&buf[wire_offset]) #define _mav_get_int64_t(buf, wire_offset, b) *b = *reinterpret_cast<const int64_t*>(&buf[wire_offset]) #define _mav_get_float(buf, wire_offset, b) *b = *reinterpret_cast<const float*>(&buf[wire_offset]) #define _mav_get_double(buf, wire_offset, b) *b = *reinterpret_cast<const double*>(&buf[wire_offset]) #endif void MavLinkMessageBase::unpack_uint8_t(const char* buffer, uint8_t* field, int offset) { *reinterpret_cast<char*>(field) = buffer[offset]; } void MavLinkMessageBase::unpack_int8_t(const char* buffer, int8_t* field, int offset) { *reinterpret_cast<char*>(field) = buffer[offset]; } void MavLinkMessageBase::unpack_int16_t(const char* buffer, int16_t* field, int offset) { _mav_get_int16_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint16_t(const char* buffer, uint16_t* field, int offset) { _mav_get_uint16_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint32_t(const char* buffer, uint32_t* field, int offset) { _mav_get_uint32_t(buffer, offset, field); } void MavLinkMessageBase::unpack_int32_t(const char* buffer, int32_t* field, int offset) { _mav_get_int32_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint64_t(const char* buffer, uint64_t* field, int offset) { _mav_get_uint64_t(buffer, offset, field); } void MavLinkMessageBase::unpack_int64_t(const char* buffer, int64_t* field, int offset) { _mav_get_int64_t(buffer, offset, field); } void MavLinkMessageBase::unpack_float(const char* buffer, float* field, int offset) { _mav_get_float(buffer, offset, field); } void MavLinkMessageBase::unpack_char_array(int len, const char* buffer, char* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_uint8_t_array(int len, const char* buffer, uint8_t* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_int8_t_array(int len, const char* buffer, int8_t* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_uint16_t_array(int len, const char* buffer, uint16_t* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_uint16_t(buffer, offset, field); offset += sizeof(uint16_t); field++; } } void MavLinkMessageBase::unpack_int16_t_array(int len, const char* buffer, int16_t* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_int16_t(buffer, offset, field); offset += sizeof(int16_t); field++; } } void MavLinkMessageBase::unpack_float_array(int len, const char* buffer, float* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_float(buffer, offset, field); offset += sizeof(float); field++; } } int MavLinkTelemetry::pack(char* buffer) const { pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->messages_sent), 0); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->messages_received), 4); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->messages_handled), 8); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->crc_errors), 12); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->handler_microseconds), 16); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->render_time), 20); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->wifi_rssi), 24); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->update_rate), 28); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->actuation_delay), 32); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->sensor_rate), 36); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->lock_step_resets), 40); pack_int32_t(buffer, reinterpret_cast<const int32_t*>(&this->update_time), 44); return MavLinkTelemetry::MessageLength; } int MavLinkTelemetry::unpack(const char* buffer) { unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->messages_sent), 0); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->messages_received), 4); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->messages_handled), 8); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->crc_errors), 12); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->handler_microseconds), 16); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->render_time), 20); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->wifi_rssi), 24); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->update_rate), 28); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->actuation_delay), 32); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->sensor_rate), 36); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->lock_step_resets), 40); unpack_int32_t(buffer, reinterpret_cast<int32_t*>(&this->update_time), 44); return MavLinkTelemetry::MessageLength; } std::string MavLinkMessageBase::char_array_tostring(int len, const char* field) { int i = 0; for (i = 0; i < len; i++) { if (field[i] == '\0') break; } return std::string(field, i); } std::string MavLinkMessageBase::float_tostring(float value) { // json can't handle "nan", so we convert it to null. if (std::isnan(value) || std::isinf(value)) { return "null"; } std::ostringstream s; s << value; return s.str(); } template <class T> class BinaryArray { public: static std::string toString(int len, const T* field) { std::ostringstream line; for (int i = 0; i < len; i++) { line << field[i]; if (i + 1 < len) { line << ", "; } } return line.str(); } }; std::string MavLinkMessageBase::uint8_t_array_tostring(int len, const uint8_t* field) { // ostringstream tries to convert uint8_t to 'char' which is not what we want here. std::ostringstream line; for (int i = 0; i < len; i++) { line << static_cast<unsigned int>(field[i]); if (i + 1 < len) { line << ", "; } } return line.str(); } std::string MavLinkMessageBase::int8_t_array_tostring(int len, const int8_t* field) { // ostringstream tries to convert int8_t to 'char' which is not what we want here. std::ostringstream line; for (int i = 0; i < len; i++) { line << static_cast<int>(field[i]); if (i + 1 < len) { line << ", "; } } return line.str(); } std::string MavLinkMessageBase::int16_t_array_tostring(int len, const int16_t* field) { return BinaryArray<int16_t>::toString(len, field); } std::string MavLinkMessageBase::uint16_t_array_tostring(int len, const uint16_t* field) { return BinaryArray<uint16_t>::toString(len, field); } std::string MavLinkMessageBase::float_array_tostring(int len, const float* field) { std::ostringstream line; for (int i = 0; i < len; i++) { line << float_tostring(field[i]); if (i + 1 < len) { line << ", "; } } return line.str(); }
AirSim/MavLinkCom/src/MavLinkMessageBase.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/MavLinkMessageBase.cpp", "repo_id": "AirSim", "token_count": 6533 }
30
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "MavLinkTcpServerImpl.hpp" #include "../serial_com/TcpClientPort.hpp" using namespace mavlinkcom_impl; MavLinkTcpServerImpl::MavLinkTcpServerImpl(const std::string& local_addr, int local_port) { local_address_ = local_addr; local_port_ = local_port; } MavLinkTcpServerImpl::~MavLinkTcpServerImpl() { } std::shared_ptr<MavLinkConnection> MavLinkTcpServerImpl::acceptTcp(const std::string& nodeName) { accept_node_name_ = nodeName; std::shared_ptr<TcpClientPort> result = std::make_shared<TcpClientPort>(); result->accept(local_address_, local_port_); auto con = std::make_shared<MavLinkConnection>(); con->startListening(nodeName, result); return con; }
AirSim/MavLinkCom/src/impl/MavLinkTcpServerImpl.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/impl/MavLinkTcpServerImpl.cpp", "repo_id": "AirSim", "token_count": 289 }
31
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "Utils.hpp" #include "TcpClientPort.hpp" #include <stdio.h> #include <string.h> #include "SocketInit.hpp" #include "wifi.h" using namespace mavlink_utils; #ifdef _WIN32 // windows #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> // Need to link with Ws2_32.lib #pragma comment(lib, "Ws2_32.lib") typedef int socklen_t; static bool socket_initialized_ = false; inline int GetSocketError() { return WSAGetLastError(); } #else // posix #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <cerrno> #include <fcntl.h> #include <netdb.h> #include <errno.h> #include <unistd.h> #include <arpa/inet.h> typedef int SOCKET; const int INVALID_SOCKET = -1; const int ERROR_ACCESS_DENIED = EACCES; inline int GetSocketError() { return errno; } const int SOCKET_ERROR = -1; #define E_NOT_SUFFICIENT_BUFFER ENOMEM #endif class TcpClientPort::TcpSocketImpl { SocketInit init; SOCKET sock = INVALID_SOCKET; SOCKET accept_sock = INVALID_SOCKET; sockaddr_in localaddr; sockaddr_in remoteaddr; bool closed_ = true; public: bool isClosed() { return closed_; } int getRssi(const char* ifaceName) { return getWifiRssi(static_cast<int>(sock), ifaceName); } static void resolveAddress(const std::string& ipAddress, int port, sockaddr_in& addr) { struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; addr.sin_family = AF_INET; addr.sin_port = htons(port); bool found = false; struct addrinfo* result = NULL; std::string serviceName = std::to_string(port); int rc = getaddrinfo(ipAddress.c_str(), serviceName.c_str(), &hints, &result); if (rc != 0) { auto msg = Utils::stringf("TcpClientPort getaddrinfo failed with error: %d\n", rc); throw std::runtime_error(msg); } for (struct addrinfo* ptr = result; ptr != NULL; ptr = ptr->ai_next) { if (ptr->ai_family == AF_INET && ptr->ai_socktype == SOCK_STREAM && ptr->ai_protocol == IPPROTO_TCP) { // found it! sockaddr_in* sptr = reinterpret_cast<sockaddr_in*>(ptr->ai_addr); addr.sin_family = sptr->sin_family; addr.sin_addr.s_addr = sptr->sin_addr.s_addr; addr.sin_port = sptr->sin_port; found = true; break; } } freeaddrinfo(result); if (!found) { auto msg = Utils::stringf("TcpClientPort could not resolve ip address for '%s:%d'\n", ipAddress.c_str(), port); throw std::runtime_error(msg); } } int connect(const std::string& localHost, int localPort, const std::string& remoteHost, int remotePort) { sock = socket(AF_INET, SOCK_STREAM, 0); resolveAddress(localHost, localPort, localaddr); resolveAddress(remoteHost, remotePort, remoteaddr); // bind socket to local address. socklen_t addrlen = sizeof(sockaddr_in); int rc = bind(sock, reinterpret_cast<sockaddr*>(&localaddr), addrlen); if (rc < 0) { int hr = GetSocketError(); auto msg = Utils::stringf("TcpClientPort socket bind failed with error: %d\n", hr); throw std::runtime_error(msg); } rc = ::connect(sock, reinterpret_cast<sockaddr*>(&remoteaddr), addrlen); if (rc != 0) { int hr = GetSocketError(); auto msg = Utils::stringf("TcpClientPort socket connect failed with error: %d\n", hr); throw std::runtime_error(msg); } closed_ = false; return 0; } void accept(const std::string& localHost, int localPort) { accept_sock = socket(AF_INET, SOCK_STREAM, 0); resolveAddress(localHost, localPort, localaddr); // bind socket to local address. socklen_t addrlen = sizeof(sockaddr_in); int rc = ::bind(accept_sock, reinterpret_cast<sockaddr*>(&localaddr), addrlen); if (rc < 0) { int hr = GetSocketError(); auto msg = Utils::stringf("TcpClientPort socket bind failed with error: %d\n", hr); throw std::runtime_error(msg); } // start listening for incoming connection rc = ::listen(accept_sock, 1); if (rc < 0) { int hr = GetSocketError(); auto msg = Utils::stringf("TcpClientPort socket listen failed with error: %d\n", hr); throw std::runtime_error(msg); } // accept 1 sock = ::accept(accept_sock, reinterpret_cast<sockaddr*>(&remoteaddr), &addrlen); if (sock == INVALID_SOCKET) { int hr = GetSocketError(); auto msg = Utils::stringf("TcpClientPort accept failed with error: %d\n", hr); throw std::runtime_error(msg); } #ifdef _WIN32 // don't need to accept any more, so we can close this one. ::closesocket(accept_sock); #else int fd = static_cast<int>(accept_sock); ::close(fd); #endif accept_sock = INVALID_SOCKET; closed_ = false; } void setNonBlocking() { #ifdef _WIN32 unsigned long mode = 1; int rc = ioctlsocket(sock, FIONBIO, &mode); #else int fd = static_cast<int>(sock); int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { auto msg = Utils::stringf("fcntl failed with error: %d\n", errno); throw std::runtime_error(msg); } flags |= O_NONBLOCK; int rc = fcntl(fd, F_SETFL, flags); #endif if (rc != 0) { rc = GetSocketError(); auto msg = Utils::stringf("TcpClientPort setNonBlocking failed with error: %d\n", rc); throw std::runtime_error(msg); } } void setNoDelay() { int flags = 1; #ifdef _WIN32 int rc = ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&flags), sizeof(flags)); #else int fd = static_cast<int>(sock); int rc = ::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&flags), sizeof(flags)); #endif if (rc != 0) { rc = GetSocketError(); auto msg = Utils::stringf("TcpClientPort set TCP_NODELAY failed: %d\n", rc); throw std::runtime_error(msg); } } // write to the serial port int write(const uint8_t* ptr, int count) { int hr = send(sock, reinterpret_cast<const char*>(ptr), count, 0); if (hr == SOCKET_ERROR) { hr = checkerror(); auto msg = Utils::stringf("TcpClientPort socket send failed with error: %d\n", hr); throw std::runtime_error(msg); } return hr; } int checkerror() { int hr = GetSocketError(); #ifdef _WIN32 if (hr == WSAECONNRESET) { close(); } #else if (hr == ECONNREFUSED || hr == ENOTCONN) { close(); } #endif return hr; } int read(uint8_t* result, int bytesToRead) { int bytesRead = 0; // try and receive something, up until port is closed anyway. while (!closed_) { int rc = recv(sock, reinterpret_cast<char*>(result), bytesToRead, 0); if (rc < 0) { int hr = checkerror(); #ifdef _WIN32 if (hr == WSAEMSGSIZE) { // message was too large for the buffer, no problem, return what we have. } else if (hr == ERROR_IO_PENDING) { // try again - this can happen if server recreates the socket on their side. continue; } else if (hr == WSAEINTR) { // skip this, it is was interrupted, and if user is closing the port closed_ will be true. continue; } else #else if (hr == EINTR) { // try again - this can happen if server recreates the socket on their side. continue; } else #endif { return -1; } } if (rc == 0) { return -1; } else { return rc; } } return -1; } void close() { closed_ = true; if (sock != INVALID_SOCKET) { #ifdef _WIN32 closesocket(sock); #else int fd = static_cast<int>(sock); ::close(fd); #endif sock = INVALID_SOCKET; } if (accept_sock != INVALID_SOCKET) { #ifdef _WIN32 closesocket(accept_sock); #else int fd = static_cast<int>(accept_sock); ::close(fd); #endif accept_sock = INVALID_SOCKET; } } std::string remoteAddress() { return inet_ntoa(remoteaddr.sin_addr); } int remotePort() { return ntohs(remoteaddr.sin_port); } }; //----------------------------------------------------------------------------------------- TcpClientPort::TcpClientPort() { impl_.reset(new TcpSocketImpl()); } TcpClientPort::~TcpClientPort() { close(); } void TcpClientPort::close() { impl_->close(); } void TcpClientPort::connect(const std::string& localHost, int localPort, const std::string& remoteHost, int remotePort) { impl_->connect(localHost, localPort, remoteHost, remotePort); } void TcpClientPort::accept(const std::string& localHost, int localPort) { impl_->accept(localHost, localPort); } int TcpClientPort::write(const uint8_t* ptr, int count) { return impl_->write(ptr, count); } int TcpClientPort::read(uint8_t* buffer, int bytesToRead) { return impl_->read(buffer, bytesToRead); } bool TcpClientPort::isClosed() { return impl_->isClosed(); } std::string TcpClientPort::remoteAddress() { return impl_->remoteAddress(); } int TcpClientPort::remotePort() { return impl_->remotePort(); } int TcpClientPort::getRssi(const char* ifaceName) { return impl_->getRssi(ifaceName); } void TcpClientPort::setNoDelay() { impl_->setNoDelay(); } void TcpClientPort::setNonBlocking() { impl_->setNonBlocking(); }
AirSim/MavLinkCom/src/serial_com/TcpClientPort.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/serial_com/TcpClientPort.cpp", "repo_id": "AirSim", "token_count": 5048 }
32
import numpy as np #pip install numpy import math import time import sys import os import inspect import types import re import logging from .types import * def string_to_uint8_array(bstr): return np.fromstring(bstr, np.uint8) def string_to_float_array(bstr): return np.fromstring(bstr, np.float32) def list_to_2d_float_array(flst, width, height): return np.reshape(np.asarray(flst, np.float32), (height, width)) def get_pfm_array(response): return list_to_2d_float_array(response.image_data_float, response.width, response.height) def get_public_fields(obj): return [attr for attr in dir(obj) if not (attr.startswith("_") or inspect.isbuiltin(attr) or inspect.isfunction(attr) or inspect.ismethod(attr))] def to_dict(obj): return dict([attr, getattr(obj, attr)] for attr in get_public_fields(obj)) def to_str(obj): return str(to_dict(obj)) def write_file(filename, bstr): """ Write binary data to file. Used for writing compressed PNG images """ with open(filename, 'wb') as afile: afile.write(bstr) # helper method for converting getOrientation to roll/pitch/yaw # https:#en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles def to_eularian_angles(q): z = q.z_val y = q.y_val x = q.x_val w = q.w_val ysqr = y * y # roll (x-axis rotation) t0 = +2.0 * (w*x + y*z) t1 = +1.0 - 2.0*(x*x + ysqr) roll = math.atan2(t0, t1) # pitch (y-axis rotation) t2 = +2.0 * (w*y - z*x) if (t2 > 1.0): t2 = 1 if (t2 < -1.0): t2 = -1.0 pitch = math.asin(t2) # yaw (z-axis rotation) t3 = +2.0 * (w*z + x*y) t4 = +1.0 - 2.0 * (ysqr + z*z) yaw = math.atan2(t3, t4) return (pitch, roll, yaw) def to_quaternion(pitch, roll, yaw): t0 = math.cos(yaw * 0.5) t1 = math.sin(yaw * 0.5) t2 = math.cos(roll * 0.5) t3 = math.sin(roll * 0.5) t4 = math.cos(pitch * 0.5) t5 = math.sin(pitch * 0.5) q = Quaternionr() q.w_val = t0 * t2 * t4 + t1 * t3 * t5 #w q.x_val = t0 * t3 * t4 - t1 * t2 * t5 #x q.y_val = t0 * t2 * t5 + t1 * t3 * t4 #y q.z_val = t1 * t2 * t4 - t0 * t3 * t5 #z return q def wait_key(message = ''): ''' Wait for a key press on the console and return it. ''' if message != '': print (message) result = None if os.name == 'nt': import msvcrt result = msvcrt.getch() else: import termios fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) try: result = sys.stdin.read(1) except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) return result def read_pfm(file): """ Read a pfm file """ file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() header = str(bytes.decode(header, encoding='utf-8')) if header == 'PF': color = True elif header == 'Pf': color = False else: raise Exception('Not a PFM file.') temp_str = str(bytes.decode(file.readline(), encoding='utf-8')) dim_match = re.match(r'^(\d+)\s(\d+)\s$', temp_str) if dim_match: width, height = map(int, dim_match.groups()) else: raise Exception('Malformed PFM header.') scale = float(file.readline().rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width) data = np.reshape(data, shape) # DEY: I don't know why this was there. file.close() return data, scale def write_pfm(file, image, scale=1): """ Write a pfm file """ file = open(file, 'wb') color = None if image.dtype.name != 'float32': raise Exception('Image dtype must be float32.') if len(image.shape) == 3 and image.shape[2] == 3: # color image color = True elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # grayscale color = False else: raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.') file.write('PF\n'.encode('utf-8') if color else 'Pf\n'.encode('utf-8')) temp_str = '%d %d\n' % (image.shape[1], image.shape[0]) file.write(temp_str.encode('utf-8')) endian = image.dtype.byteorder if endian == '<' or endian == '=' and sys.byteorder == 'little': scale = -scale temp_str = '%f\n' % scale file.write(temp_str.encode('utf-8')) image.tofile(file) def write_png(filename, image): """ image must be numpy array H X W X channels """ import cv2 # pip install opencv-python ret = cv2.imwrite(filename, image) if not ret: logging.error(f"Writing PNG file {filename} failed")
AirSim/PythonClient/airsim/utils.py/0
{ "file_path": "AirSim/PythonClient/airsim/utils.py", "repo_id": "AirSim", "token_count": 2497 }
33
import numpy import cv2 import time import sys import os import random import glob from airsim import * def rotation_matrix_from_angles(pry): pitch = pry[0] roll = pry[1] yaw = pry[2] sy = numpy.sin(yaw) cy = numpy.cos(yaw) sp = numpy.sin(pitch) cp = numpy.cos(pitch) sr = numpy.sin(roll) cr = numpy.cos(roll) Rx = numpy.array([ [1, 0, 0], [0, cr, -sr], [0, sr, cr] ]) Ry = numpy.array([ [cp, 0, sp], [0, 1, 0], [-sp, 0, cp] ]) Rz = numpy.array([ [cy, -sy, 0], [sy, cy, 0], [0, 0, 1] ]) #Roll is applied first, then pitch, then yaw. RyRx = numpy.matmul(Ry, Rx) return numpy.matmul(Rz, RyRx) def project_3d_point_to_screen(subjectXYZ, camXYZ, camQuaternion, camProjMatrix4x4, imageWidthHeight): #Turn the camera position into a column vector. camPosition = numpy.transpose([camXYZ]) #Convert the camera's quaternion rotation to yaw, pitch, roll angles. pitchRollYaw = utils.to_eularian_angles(camQuaternion) #Create a rotation matrix from camera pitch, roll, and yaw angles. camRotation = rotation_matrix_from_angles(pitchRollYaw) #Change coordinates to get subjectXYZ in the camera's local coordinate system. XYZW = numpy.transpose([subjectXYZ]) XYZW = numpy.add(XYZW, -camPosition) print("XYZW: " + str(XYZW)) XYZW = numpy.matmul(numpy.transpose(camRotation), XYZW) print("XYZW derot: " + str(XYZW)) #Recreate the perspective projection of the camera. XYZW = numpy.concatenate([XYZW, [[1]]]) XYZW = numpy.matmul(camProjMatrix4x4, XYZW) XYZW = XYZW / XYZW[3] #Move origin to the upper-left corner of the screen and multiply by size to get pixel values. Note that screen is in y,-z plane. normX = (1 - XYZW[0]) / 2 normY = (1 + XYZW[1]) / 2 return numpy.array([ imageWidthHeight[0] * normX, imageWidthHeight[1] * normY ]).reshape(2,) def get_image(x, y, z, pitch, roll, yaw, client): """ title:: get_image description:: Capture images (as numpy arrays) from a certain position. inputs:: x x position in meters y y position in meters z altitude in meters; remember NED, so should be negative to be above ground pitch angle (in radians); in computer vision mode, this is camera angle roll angle (in radians) yaw angle (in radians) client connection to AirSim (e.g., client = MultirotorClient() for UAV) returns:: position AirSim position vector (access values with x_val, y_val, z_val) angle AirSim quaternion ("angles") im segmentation or IR image, depending upon palette in use (3 bands) imScene scene image (3 bands) author:: Elizabeth Bondi Shital Shah """ #Set pose and sleep after to ensure the pose sticks before capturing image. client.simSetVehiclePose(Pose(Vector3r(x, y, z), \ to_quaternion(pitch, roll, yaw)), True) time.sleep(0.1) #Capture segmentation (IR) and scene images. responses = \ client.simGetImages([ImageRequest("0", ImageType.Infrared, False, False), ImageRequest("0", ImageType.Scene, \ False, False), ImageRequest("0", ImageType.Segmentation, \ False, False)]) #Change images into numpy arrays. img1d = numpy.fromstring(responses[0].image_data_uint8, dtype=numpy.uint8) im = img1d.reshape(responses[0].height, responses[0].width, 4) img1dscene = numpy.fromstring(responses[1].image_data_uint8, dtype=numpy.uint8) imScene = img1dscene.reshape(responses[1].height, responses[1].width, 4) return Vector3r(x, y, z), to_quaternion(pitch, roll, yaw),\ im[:,:,:3], imScene[:,:,:3] #get rid of alpha channel def main(client, objectList, pitch=numpy.radians(270), #image straight down roll=0, yaw=0, z=-122, writeIR=True, writeScene=False, irFolder='', sceneFolder=''): """ title:: main description:: Follow objects of interest and record images while following. inputs:: client connection to AirSim (e.g., client = MultirotorClient() for UAV) objectList list of tag names within the AirSim environment, corresponding to objects to follow (add tags by clicking on object, going to Details, Actor, and Tags, then add component) pitch angle (in radians); in computer vision mode, this is camera angle roll angle (in radians) yaw angle (in radians) z altitude in meters; remember NED, so should be negative to be above ground write if True, will write out the images folder path to a particular folder that should be used (then within that folder, expected folders are ir and scene) author:: Elizabeth Bondi """ i = 0 for o in objectList: startTime = time.time() elapsedTime = 0 pose = client.simGetObjectPose(o); #Capture images for a certain amount of time in seconds (half hour now) while elapsedTime < 1800: #Capture image - pose.position x_val access may change w/ AirSim #version (pose.position.x_val new, pose.position[b'x_val'] old) vector, angle, ir, scene = get_image(pose.position.x_val, pose.position.y_val, z, pitch, roll, yaw, client) #Convert color scene image to BGR for write out with cv2. r,g,b = cv2.split(scene) scene = cv2.merge((b,g,r)) if writeIR: cv2.imwrite(irFolder+'ir_'+str(i).zfill(5)+'.png', ir) if writeScene: cv2.imwrite(sceneFolder+'scene_'+str(i).zfill(5)+'.png', scene) i += 1 elapsedTime = time.time() - startTime pose = client.simGetObjectPose(o); camInfo = client.simGetCameraInfo("0") object_xy_in_pic = project_3d_point_to_screen( [pose.position.x_val, pose.position.y_val, pose.position.z_val], [camInfo.pose.position.x_val, camInfo.pose.position.y_val, camInfo.pose.position.z_val], camInfo.pose.orientation, camInfo.proj_mat.matrix, ir.shape[:2][::-1] ) print("Object projected to pixel\n{!s}.".format(object_xy_in_pic)) if __name__ == '__main__': #Connect to AirSim, UAV mode. client = MultirotorClient() client.confirmConnection() #Look for objects with names that match a regular expression. poacherList = client.simListSceneObjects('.*?Poacher.*?') elephantList = client.simListSceneObjects('.*?Elephant.*?') crocList = client.simListSceneObjects('.*?Croc.*?') hippoList = client.simListSceneObjects('.*?Hippo.*?') objectList = elephantList #Sample calls to main, varying camera angle and altitude. #straight down, 400ft main(client, objectList, irFolder=r'auto\winter\400ft\down') #straight down, 200ft main(client, objectList, z=-61, irFolder=r'auto\winter\200ft\down') #45 degrees, 200ft -- note that often object won't be scene since position #is set exactly to object's main(client, objectList, z=-61, pitch=numpy.radians(315), irFolder=r'auto\winter\200ft\45') #45 degrees, 400ft -- note that often object won't be scene since position #is set exactly to object's main(client, objectList, pitch=numpy.radians(315), irFolder=r'auto\winter\400ft\45')
AirSim/PythonClient/computer_vision/capture_ir_segmentation.py/0
{ "file_path": "AirSim/PythonClient/computer_vision/capture_ir_segmentation.py", "repo_id": "AirSim", "token_count": 4177 }
34
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
AirSim/PythonClient/docs/Makefile/0
{ "file_path": "AirSim/PythonClient/docs/Makefile", "repo_id": "AirSim", "token_count": 237 }
35
# Imitation Learning This section is about training a model to steer our Formula car using imitation learning. The code in this section is based on the [Autonomous Driving Cookbook](https://github.com/Microsoft/AutonomousDrivingCookbook/tree/master/AirSimE2EDeepLearning) from Airsim and it's highly recommended to read the tutorial first. ## Prerequisites * Operating system: Windows 10 * GPU: Nvidia GTX 1080 or higher (recommended) * Software: Unreal Engine 4.24 and Visual Studio 2019 (see [upgrade instructions](../../docs/unreal_upgrade.md)) * Development: CUDA 9.0 and python 3.5. * Python libraries: Keras 2.1.2, TensorFlow 1.6.0. * Note: Newer versions of keras or tensorflow are recommended but can cause syntax errors. ## What's inside ![imitation learning](https://github.com/microsoft/airsim/wiki/images/technion/imitation_learning_example.gif) *Driving in simulation using trained imitation learning model, based on recorded data* Imitation learning includes the usage of labeled data as input to a training algorithm with the purpose of having the algorithm imitate the actions of people who recorded the data. ![diagram](https://github.com/microsoft/airsim/wiki/images/technion/imitation_diagram.PNG) This diagram is represented by these files: **cook_data.py** This file is responsible for preparing .h5 dataset files for the training procedure. The code rely on having two adjacent folders: 'raw_data' - contains folders of recorded data by airsim's recording method. 'cooked_data' - empty folder to store the .h5 files. The flag "COOK_ALL_DATA" gives the option to choose all subfolders, or exclude some of them. **train_model.py** This file is responsible to train a model using the .h5 dataset files. The code rely on having two adjacent folders: 'cooked_data' - contains the .h5 dataset files. 'models' - empty folder to store the generated models. The file will preprocess the data, add augmentations and create a neural network model that predicts the next steering angle. **drive_model.py** This file connects to the simulation in order to upload a trained model and drive using it. By using the predicted steering value, the code calculates related control parameters and maintain driving with steady velocities. ## Training Tips We recommend on using augmentation and recording techniques. We give here an example for two methods: - [CycleLight](https://github.com/Microsoft/AirSim/wiki/graphic_features) - Animation of a day light cycle in a changeable, potentially very short period of time. - Shifted images - Altering the camera’s position to the right or the left of the car, so that it can record images in extreme conditions. To simulate driving back to the center from those extreme situations, post-process the recorded angle of the steering accordingly (manually).
AirSim/PythonClient/imitation_learning/README.md/0
{ "file_path": "AirSim/PythonClient/imitation_learning/README.md", "repo_id": "AirSim", "token_count": 779 }
36
import airsim from datetime import datetime ''' Simple script with settings to create a high-resolution camera, and fetching it Settings used- { "SettingsVersion": 1.2, "SimMode": "Multirotor", "Vehicles" : { "Drone1" : { "VehicleType" : "SimpleFlight", "AutoCreate" : true, "Cameras" : { "high_res": { "CaptureSettings" : [ { "ImageType" : 0, "Width" : 4320, "Height" : 2160 } ], "X": 0.50, "Y": 0.00, "Z": 0.10, "Pitch": 0.0, "Roll": 0.0, "Yaw": 0.0 }, "low_res": { "CaptureSettings" : [ { "ImageType" : 0, "Width" : 256, "Height" : 144 } ], "X": 0.50, "Y": 0.00, "Z": 0.10, "Pitch": 0.0, "Roll": 0.0, "Yaw": 0.0 } } } } } ''' client = airsim.VehicleClient() client.confirmConnection() framecounter = 1 prevtimestamp = datetime.now() while(framecounter <= 500): if framecounter%150 == 0: client.simGetImages([airsim.ImageRequest("high_res", airsim.ImageType.Scene, False, False)]) print("High resolution image captured.") if framecounter%30 == 0: now = datetime.now() print(f"Time spent for 30 frames: {now-prevtimestamp}") prevtimestamp = now client.simGetImages([airsim.ImageRequest("low_res", airsim.ImageType.Scene, False, False)]) framecounter += 1
AirSim/PythonClient/multirotor/high_res_camera.py/0
{ "file_path": "AirSim/PythonClient/multirotor/high_res_camera.py", "repo_id": "AirSim", "token_count": 1039 }
37
# Please add "EnableTrace": true to your setting.json as shown below # { # "SettingsVersion": 1.2, # "SimMode": "Multirotor", # "Vehicles": { # "Drone": { # "VehicleType": "SimpleFlight", # "EnableTrace": true # } # } # } import setup_path import airsim import time # connect to the AirSim simulator client = airsim.MultirotorClient() client.confirmConnection() client.enableApiControl(True) client.armDisarm(True) client.takeoffAsync().join() client.hoverAsync().join() vehicleControl = client.moveByVelocityAsync(1, 1, 0, 12) client.simSetTraceLine([1.0, 0.0, 0.0, 1.0], 5) time.sleep(2) client.simSetTraceLine([0.0, 1.0, 0.0, 0.8], 10) time.sleep(2) client.simSetTraceLine([0.0, 0.0, 1.0, 0.6], 20) time.sleep(2) client.simSetTraceLine([1.0, 1.0, 0.0, 0.4], 30) time.sleep(2) client.simSetTraceLine([0.0, 1.0, 1.0, 0.2], 40) time.sleep(2) client.simSetTraceLine([1.0, 0.0, 1.0, 0.1], 50) time.sleep(2) vehicleControl.join() client.armDisarm(False) client.takeoffAsync().join() client.enableApiControl(False)
AirSim/PythonClient/multirotor/set_trace_line.py/0
{ "file_path": "AirSim/PythonClient/multirotor/set_trace_line.py", "repo_id": "AirSim", "token_count": 470 }
38
import setup_path import gym import airgym import time from stable_baselines3 import DQN from stable_baselines3.common.monitor import Monitor from stable_baselines3.common.vec_env import DummyVecEnv, VecTransposeImage from stable_baselines3.common.evaluation import evaluate_policy from stable_baselines3.common.callbacks import EvalCallback # Create a DummyVecEnv for main airsim gym env env = DummyVecEnv( [ lambda: Monitor( gym.make( "airgym:airsim-car-sample-v0", ip_address="127.0.0.1", image_shape=(84, 84, 1), ) ) ] ) # Wrap env as VecTransposeImage to allow SB to handle frame observations env = VecTransposeImage(env) # Initialize RL algorithm type and parameters model = DQN( "CnnPolicy", env, learning_rate=0.00025, verbose=1, batch_size=32, train_freq=4, target_update_interval=10000, learning_starts=200000, buffer_size=500000, max_grad_norm=10, exploration_fraction=0.1, exploration_final_eps=0.01, device="cuda", tensorboard_log="./tb_logs/", ) # Create an evaluation callback with the same env, called every 10000 iterations callbacks = [] eval_callback = EvalCallback( env, callback_on_new_best=None, n_eval_episodes=5, best_model_save_path=".", log_path=".", eval_freq=10000, ) callbacks.append(eval_callback) kwargs = {} kwargs["callback"] = callbacks # Train for a certain number of timesteps model.learn( total_timesteps=5e5, tb_log_name="dqn_airsim_car_run_" + str(time.time()), **kwargs ) # Save policy weights model.save("dqn_airsim_car_policy")
AirSim/PythonClient/reinforcement_learning/dqn_car.py/0
{ "file_path": "AirSim/PythonClient/reinforcement_learning/dqn_car.py", "repo_id": "AirSim", "token_count": 682 }
39
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // by Sudipta Sinha // adapted for AirSim by Matthias Mueller #pragma once #include "../sgmstereo/sgmstereo.h" #include "SGMOptions.h" #include <vector> class CStateStereo { private: float downSampleFactor; std::string outputDir; int inputFrameWidth, inputFrameHeight; int ndisps; int minDisp; int maxDisp; int confThreshold; SGMStereo* sgmStereo; public: int processingFrameWidth, processingFrameHeight; CStateStereo(); ~CStateStereo(); void Initialize(SGMOptions& params, int m = 144, int n = 256); void CleanUp(); void ProcessFrameAirSim(int frameCounter, float& dtime, const std::vector<uint8_t>& left_image, const std::vector<uint8_t>& right_image); float GetLeftDisparity(float x, float y); float* dispMap; unsigned char* confMap; };
AirSim/SGM/src/stereoPipeline/StateStereo.h/0
{ "file_path": "AirSim/SGM/src/stereoPipeline/StateStereo.h", "repo_id": "AirSim", "token_count": 328 }
40
#include "SimHUD.h" #include "../PInvokeWrapper.h" #include "../Vehicles/Car/SimModeCar.h" #include "../Vehicles/Multirotor/SimModeWorldMultiRotor.h" SimHUD::SimHUD(std::string sim_mode_name, int port_number) : sim_mode_name_(sim_mode_name), port_number_(port_number) { server_started_Successfully_ = false; } void SimHUD::BeginPlay() { try { initializeSettings(); createSimMode(); if (simmode_) simmode_->startApiServer(); server_started_Successfully_ = true; } catch (std::exception& ex) { PrintLogMessage("Error at startup: ", ex.what(), "", ErrorLogSeverity::Error); } } void SimHUD::Tick(float DeltaSeconds) { if (simmode_) { simmode_->Tick(DeltaSeconds); } } void SimHUD::EndPlay() { if (simmode_) { simmode_->EndPlay(); simmode_->stopApiServer(); } if (simmode_) { delete simmode_; simmode_ = nullptr; } } void SimHUD::initializeSettings() { std::string settingsText; if (getSettingsText(settingsText)) AirSimSettings::initializeSettings(settingsText); else AirSimSettings::createDefaultSettingsFile(); AirSimSettings::singleton().load(std::bind(&SimHUD::getSimModeFromUser, this)); for (const auto& warning : AirSimSettings::singleton().warning_messages) { PrintLogMessage(warning.c_str(), "LogDebugLevel::Failure", "", ErrorLogSeverity::Error); } for (const auto& error : AirSimSettings::singleton().error_messages) { PrintLogMessage(error.c_str(), "settings.json", "", ErrorLogSeverity::Error); } } const std::vector<SimHUD::AirSimSettings::SubwindowSetting>& SimHUD::getSubWindowSettings() const { return AirSimSettings::singleton().subwindow_settings; } std::vector<SimHUD::AirSimSettings::SubwindowSetting>& SimHUD::getSubWindowSettings() { return AirSimSettings::singleton().subwindow_settings; } SimModeBase* SimHUD::GetSimMode() { return simmode_; } std::string SimHUD::getSimModeFromUser() { return sim_mode_name_; } void SimHUD::createSimMode() { std::string simmode_name = AirSimSettings::singleton().simmode_name; if (simmode_name == "Multirotor") simmode_ = new SimModeWorldMultiRotor(port_number_); else if (simmode_name == "Car") simmode_ = new SimModeCar(port_number_); simmode_->BeginPlay(); } // Attempts to parse the settings text from one of multiple locations. // First, check the command line for settings provided via "-s" or "--settings" arguments // Next, check the executable's working directory for the settings file. // Finally, check the user's documents folder. // If the settings file cannot be read, throw an exception bool SimHUD::getSettingsText(std::string& settingsText) { return ( readSettingsTextFromFile(msr::airlib::Settings::getExecutableFullPath("settings.json"), settingsText) || readSettingsTextFromFile(msr::airlib::Settings::Settings::getUserDirectoryFullPath("settings.json"), settingsText)); } bool SimHUD::readSettingsTextFromFile(std::string settingsFilepath, std::string& settingsText) { std::ifstream file(settingsFilepath); if (!file.fail()) { std::stringstream buffer; buffer << file.rdbuf(); settingsText = buffer.str(); PrintLogMessage("Loaded settings from ", settingsFilepath.c_str(), "", ErrorLogSeverity::Information); return true; } else { PrintLogMessage("Cannot read settings file ", settingsFilepath.c_str(), "", ErrorLogSeverity::Error); } return false; }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/SimHUD/SimHUD.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/SimHUD/SimHUD.cpp", "repo_id": "AirSim", "token_count": 1329 }
41
#include "CarPawn.h" #define LOCTEXT_NAMESPACE "VehiclePawn" CarPawn::CarPawn(std::string car_name) : car_name_(car_name) { is_low_friction_ = false; } #undef LOCTEXT_NAMESPACE
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Car/CarPawn.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Car/CarPawn.cpp", "repo_id": "AirSim", "token_count": 89 }
42
#include "WorldSimApi.h" #include "PInvokeWrapper.h" #include "UnityUtilities.hpp" WorldSimApi::WorldSimApi(SimModeBase* simmode) : simmode_(simmode) { } WorldSimApi::~WorldSimApi() { } bool WorldSimApi::isPaused() const { return simmode_->isPaused(); } void WorldSimApi::reset() { simmode_->reset(); } void WorldSimApi::pause(bool is_paused) { simmode_->pause(is_paused); } void WorldSimApi::continueForTime(double seconds) { simmode_->continueForTime(seconds); } void WorldSimApi::continueForFrames(uint32_t frames) { simmode_->continueForFrames(frames); } void WorldSimApi::setTimeOfDay(bool is_enabled, const std::string& start_datetime, bool is_start_datetime_dst, float celestial_clock_speed, float update_interval_secs, bool move_sun) { simmode_->setTimeOfDay(is_enabled, start_datetime, is_start_datetime_dst, celestial_clock_speed, update_interval_secs, move_sun); } bool WorldSimApi::setSegmentationObjectID(const std::string& mesh_name, int object_id, bool is_name_regex) { return SetSegmentationObjectId(mesh_name.c_str(), object_id, is_name_regex); } int WorldSimApi::getSegmentationObjectID(const std::string& mesh_name) const { return GetSegmentationObjectId(mesh_name.c_str()); } void WorldSimApi::printLogMessage(const std::string& message, const std::string& message_param, unsigned char severity) { PrintLogMessage(message.c_str(), message_param.c_str(), "", severity); } bool WorldSimApi::setLightIntensity(const std::string& light_name, float intensity) { throw std::invalid_argument(common_utils::Utils::stringf( "setLightIntensity is not supported on unity") .c_str()); return false; } std::unique_ptr<std::vector<std::string>> WorldSimApi::swapTextures(const std::string& tag, int tex_id, int component_id, int material_id) { std::unique_ptr<std::vector<std::string>> result; throw std::invalid_argument(common_utils::Utils::stringf( "swapTextures is not supported on unity") .c_str()); return result; } bool WorldSimApi::setObjectMaterialFromTexture(const std::string& object_name, const std::string& texture_path, const int component_id) { throw std::invalid_argument(common_utils::Utils::stringf( "setObjectMaterialFromTexture is not supported on unity") .c_str()); return false; } bool WorldSimApi::setObjectMaterial(const std::string& object_name, const std::string& material_name, const int component_id) { throw std::invalid_argument(common_utils::Utils::stringf( "setObjectMaterial is not supported on unity") .c_str()); return false; } std::vector<std::string> WorldSimApi::listSceneObjects(const std::string& name_regex) const { std::vector<std::string> result; throw std::invalid_argument(common_utils::Utils::stringf( "simListSceneObject is not supported on unity") .c_str()); return result; } WorldSimApi::Pose WorldSimApi::getObjectPose(const std::string& object_name) const { AirSimUnity::AirSimPose airSimPose = GetPose(object_name.c_str()); return UnityUtilities::Convert_to_Pose(airSimPose); } msr::airlib::Vector3r WorldSimApi::getObjectScale(const std::string& object_name) const { return Vector3r(); } msr::airlib::Vector3r WorldSimApi::getObjectScaleInternal(const std::string& object_name) const { return Vector3r(); } bool WorldSimApi::setObjectScale(const std::string& object_name, const Vector3r& scale) { return false; } bool WorldSimApi::setObjectPose(const std::string& object_name, const WorldSimApi::Pose& pose, bool teleport) { AirSimUnity::AirSimPose airSimPose = UnityUtilities::Convert_to_AirSimPose(pose); return SetPose(airSimPose, false, object_name.c_str()); } bool WorldSimApi::runConsoleCommand(const std::string& command) { throw std::invalid_argument(common_utils::Utils::stringf( "simrunConsoleCommand is not supported on unity") .c_str()); return false; } void WorldSimApi::enableWeather(bool enable) { unused(enable); //TODO: implement weather for Unity } void WorldSimApi::setWeatherParameter(WeatherParameter param, float val) { unused(param); unused(val); //TODO: implement weather for Unity } bool WorldSimApi::createVoxelGrid(const Vector3r& position, const int& x_size, const int& y_size, const int& z_size, const float& res, const std::string& output_file) { return false; } //----------------Plotting APIs-----------/ void WorldSimApi::simFlushPersistentMarkers() { throw std::invalid_argument(common_utils::Utils::stringf( "simFlushPersistentMarkers is not supported on unity") .c_str()); } void WorldSimApi::simPlotPoints(const std::vector<Vector3r>& points, const std::vector<float>& color_rgba, float size, float duration, bool is_persistent) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotPoints is not supported on unity") .c_str()); } void WorldSimApi::simPlotLineStrip(const std::vector<Vector3r>& points, const std::vector<float>& color_rgba, float thickness, float duration, bool is_persistent) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotLineStrip is not supported on unity") .c_str()); } void WorldSimApi::simPlotLineList(const std::vector<Vector3r>& points, const std::vector<float>& color_rgba, float thickness, float duration, bool is_persistent) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotLineList is not supported on unity") .c_str()); } void WorldSimApi::simPlotArrows(const std::vector<Vector3r>& points_start, const std::vector<Vector3r>& points_end, const std::vector<float>& color_rgba, float thickness, float arrow_size, float duration, bool is_persistent) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotArrows is not supported on unity") .c_str()); } void WorldSimApi::simPlotStrings(const std::vector<std::string>& strings, const std::vector<Vector3r>& positions, float scale, const std::vector<float>& color_rgba, float duration) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotStrings is not supported on unity") .c_str()); } void WorldSimApi::simPlotTransforms(const std::vector<Pose>& poses, float scale, float thickness, float duration, bool is_persistent) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotTransforms is not supported on unity") .c_str()); } void WorldSimApi::simPlotTransformsWithNames(const std::vector<Pose>& poses, const std::vector<std::string>& names, float tf_scale, float tf_thickness, float text_scale, const std::vector<float>& text_color_rgba, float duration) { throw std::invalid_argument(common_utils::Utils::stringf( "simPlotTransformsWithNames is not supported on unity") .c_str()); } std::vector<WorldSimApi::MeshPositionVertexBuffersResponse> WorldSimApi::getMeshPositionVertexBuffers() const { std::vector<MeshPositionVertexBuffersResponse> result; throw std::invalid_argument(common_utils::Utils::stringf( "getMeshPositionVertexBuffers is not supported on unity") .c_str()); return result; } // Recording APIs void WorldSimApi::startRecording() { throw std::invalid_argument(common_utils::Utils::stringf( "startRecording is not supported on unity") .c_str()); } void WorldSimApi::stopRecording() { throw std::invalid_argument(common_utils::Utils::stringf( "stopRecording is not supported on unity") .c_str()); } bool WorldSimApi::isRecording() const { throw std::invalid_argument(common_utils::Utils::stringf( "isRecording is not supported on unity") .c_str()); return false; } void WorldSimApi::setWind(const Vector3r& wind) const { simmode_->setWind(wind); } std::vector<std::string> WorldSimApi::listVehicles() const { auto vehicle_names = (simmode_->getApiProvider()->getVehicleSimApis()).keys(); // Remove '' from the list, representing default vehicle auto position = std::find(vehicle_names.begin(), vehicle_names.end(), ""); if (position != vehicle_names.end()) vehicle_names.erase(position); return vehicle_names; } bool WorldSimApi::addVehicle(const std::string& vehicle_name, const std::string& vehicle_type, const WorldSimApi::Pose& pose, const std::string& pawn_path) { throw std::invalid_argument(common_utils::Utils::stringf( "addVehicle is not supported on unity") .c_str()); return false; } std::string WorldSimApi::getSettingsString() const { return msr::airlib::AirSimSettings::singleton().settings_text_; } bool WorldSimApi::testLineOfSightBetweenPoints(const msr::airlib::GeoPoint& point1, const msr::airlib::GeoPoint& point2) const { unused(point1); unused(point2); throw std::invalid_argument(common_utils::Utils::stringf( "testLineOfSightBetweenPoints is not supported on unity") .c_str()); return false; } std::vector<msr::airlib::GeoPoint> WorldSimApi::getWorldExtents() const { std::vector<msr::airlib::GeoPoint> result; throw std::invalid_argument(common_utils::Utils::stringf( "getWorldExtents is not supported on unity") .c_str()); return result; } msr::airlib::CameraInfo WorldSimApi::getCameraInfo(const CameraDetails& camera_details) const { if (camera_details.external) throw std::invalid_argument(common_utils::Utils::stringf("external field is not supported on Unity Image APIs").c_str()); AirSimCameraInfo airsim_camera_info = GetCameraInfo(camera_details.camera_name.c_str(), camera_details.vehicle_name.c_str()); // Into Unity msr::airlib::CameraInfo camera_info; camera_info.pose = UnityUtilities::Convert_to_Pose(airsim_camera_info.pose); camera_info.fov = airsim_camera_info.fov; return camera_info; } void WorldSimApi::setCameraPose(const msr::airlib::Pose& pose, const CameraDetails& camera_details) { if (camera_details.external) throw std::invalid_argument(common_utils::Utils::stringf("external field is not supported on Unity Image APIs").c_str()); SetCameraPose(camera_details.camera_name.c_str(), UnityUtilities::Convert_to_AirSimPose(pose), camera_details.vehicle_name.c_str()); } void WorldSimApi::setCameraFoV(float fov_degrees, const CameraDetails& camera_details) { if (camera_details.external) throw std::invalid_argument(common_utils::Utils::stringf("external field is not supported on Unity Image APIs").c_str()); SetCameraFoV(camera_details.camera_name.c_str(), fov_degrees, camera_details.vehicle_name.c_str()); } void WorldSimApi::setDistortionParam(const std::string& param_name, float value, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf("setDistortionParam is not supported on unity").c_str()); } std::vector<float> WorldSimApi::getDistortionParams(const CameraDetails& camera_details) const { throw std::invalid_argument(common_utils::Utils::stringf("getDistortionParams is not supported on unity").c_str()); std::vector<float> params(5, 0.0); return params; } std::vector<WorldSimApi::ImageCaptureBase::ImageResponse> WorldSimApi::getImages( const std::vector<ImageCaptureBase::ImageRequest>& requests, const std::string& vehicle_name, bool external) const { std::vector<ImageCaptureBase::ImageResponse> responses; const ImageCaptureBase* camera = simmode_->getVehicleSimApi(vehicle_name)->getImageCapture(); camera->getImages(requests, responses); return responses; } std::vector<uint8_t> WorldSimApi::getImage(ImageCaptureBase::ImageType image_type, const CameraDetails& camera_details) const { std::vector<ImageCaptureBase::ImageRequest> request{ ImageCaptureBase::ImageRequest(camera_details.camera_name, image_type) }; const auto& response = getImages(request, camera_details.vehicle_name, camera_details.external); if (response.size() > 0) return response.at(0).image_data_uint8; else return std::vector<uint8_t>(); } //CinemAirSim std::vector<std::string> WorldSimApi::getPresetLensSettings(const CameraDetails& camera_details) { std::vector<std::string> result; throw std::invalid_argument(common_utils::Utils::stringf( "getPresetLensSettings is not supported on unity") .c_str()); return result; } std::string WorldSimApi::getLensSettings(const CameraDetails& camera_details) { std::string result; throw std::invalid_argument(common_utils::Utils::stringf( "getLensSettings is not supported on unity") .c_str()); return result; } void WorldSimApi::setPresetLensSettings(std::string preset, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "setPresetLensSettings is not supported on unity") .c_str()); } std::vector<std::string> WorldSimApi::getPresetFilmbackSettings(const CameraDetails& camera_details) { std::vector<std::string> result; throw std::invalid_argument(common_utils::Utils::stringf( "getPresetFilmbackSettings is not supported on unity") .c_str()); return result; } void WorldSimApi::setPresetFilmbackSettings(std::string preset, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "setPresetFilmbackSettings is not supported on unity") .c_str()); } std::string WorldSimApi::getFilmbackSettings(const CameraDetails& camera_details) { std::string result; throw std::invalid_argument(common_utils::Utils::stringf( "getFilmbackSettings is not supported on unity") .c_str()); return result; } float WorldSimApi::setFilmbackSettings(float width, float height, const CameraDetails& camera_details) { float result; throw std::invalid_argument(common_utils::Utils::stringf( "setFilmbackSettings is not supported on unity") .c_str()); return result; } float WorldSimApi::getFocalLength(const CameraDetails& camera_details) { float result; throw std::invalid_argument(common_utils::Utils::stringf( "getFocalLength is not supported on unity") .c_str()); return result; } void WorldSimApi::setFocalLength(float focal_length, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "setFocalLength is not supported on unity") .c_str()); } void WorldSimApi::enableManualFocus(bool enable, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "enableManualFocus is not supported on unity") .c_str()); } float WorldSimApi::getFocusDistance(const CameraDetails& camera_details) { float result; throw std::invalid_argument(common_utils::Utils::stringf( "getFocusDistance is not supported on unity") .c_str()); return result; } void WorldSimApi::setFocusDistance(float focus_distance, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "setFocusDistance is not supported on unity") .c_str()); } float WorldSimApi::getFocusAperture(const CameraDetails& camera_details) { float result; throw std::invalid_argument(common_utils::Utils::stringf( "getFocusAperture is not supported on unity") .c_str()); return result; } void WorldSimApi::setFocusAperture(float focus_aperture, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "setFocusAperture is not supported on unity") .c_str()); } void WorldSimApi::enableFocusPlane(bool enable, const CameraDetails& camera_details) { throw std::invalid_argument(common_utils::Utils::stringf( "enableFocusPlane is not supported on unity") .c_str()); } std::string WorldSimApi::getCurrentFieldOfView(const CameraDetails& camera_details) { std::string result; throw std::invalid_argument(common_utils::Utils::stringf( "getCurrentFieldOfView is not supported on unity") .c_str()); return result; } //End CinemAirSim void WorldSimApi::addDetectionFilterMeshName(ImageCaptureBase::ImageType image_type, const std::string& mesh_name, const CameraDetails& camera_details) { unused(camera_details); unused(image_type); unused(mesh_name); throw std::invalid_argument(common_utils::Utils::stringf( "addDetectionFilterMeshName is not supported on unity") .c_str()); } void WorldSimApi::setDetectionFilterRadius(ImageCaptureBase::ImageType image_type, float radius_cm, const CameraDetails& camera_details) { unused(camera_details); unused(image_type); unused(radius_cm); throw std::invalid_argument(common_utils::Utils::stringf( "setDetectionFilterRadius is not supported on unity") .c_str()); } void WorldSimApi::clearDetectionMeshNames(ImageCaptureBase::ImageType image_type, const CameraDetails& camera_details) { unused(camera_details); unused(image_type); throw std::invalid_argument(common_utils::Utils::stringf( "clearDetectionMeshNames is not supported on unity") .c_str()); } std::vector<msr::airlib::DetectionInfo> WorldSimApi::getDetections(ImageCaptureBase::ImageType image_type, const CameraDetails& camera_details) { unused(camera_details); unused(image_type); throw std::invalid_argument(common_utils::Utils::stringf( "getDetections is not supported on unity") .c_str()); return std::vector<msr::airlib::DetectionInfo>(); } std::vector<std::string> WorldSimApi::listAssets() const { throw std::invalid_argument(common_utils::Utils::stringf( "listAssets API is not supported on Unity") .c_str()); return {}; } #pragma endregion
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/WorldSimApi.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/WorldSimApi.cpp", "repo_id": "AirSim", "token_count": 8839 }
43
fileFormatVersion: 2 guid: 62e76ff4f9e9bb44ea9c9ad2d67bdf98 timeCreated: 1443785993 licenseType: Store NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Propeller.mat.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Propeller.mat.meta", "repo_id": "AirSim", "token_count": 74 }
44
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &1069380937563562 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4015438019020906} - component: {fileID: 114413233081440058} - component: {fileID: 114251186709661246} m_Layer: 0 m_Name: EventSystem m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4015438019020906 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1069380937563562} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224535373885583630} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &114413233081440058 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1069380937563562} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3} m_Name: m_EditorClassIdentifier: m_FirstSelected: {fileID: 0} m_sendNavigationEvents: 1 m_DragThreshold: 10 --- !u!114 &114251186709661246 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1069380937563562} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalAxis: Horizontal m_VerticalAxis: Vertical m_SubmitButton: Submit m_CancelButton: Cancel m_InputActionsPerSecond: 10 m_RepeatDelay: 0.5 m_ForceModuleActive: 0 --- !u!1 &1206396816893358 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224308620163404540} - component: {fileID: 222123361651003022} - component: {fileID: 114998391819878890} m_Layer: 0 m_Name: Window3Image m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224308620163404540 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1206396816893358} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224908474901092230} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222123361651003022 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1206396816893358} m_CullTransparentMesh: 0 --- !u!114 &114998391819878890 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1206396816893358} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 8400000, guid: ca5a26a47741d2943bf1ca546bffb563, type: 2} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1228585519725970 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224684424382713112} - component: {fileID: 222190390066084978} - component: {fileID: 114740860229242950} m_Layer: 0 m_Name: Mask m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 0 --- !u!224 &224684424382713112 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1228585519725970} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224126773406121108} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222190390066084978 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1228585519725970} m_CullTransparentMesh: 0 --- !u!114 &114740860229242950 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1228585519725970} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1296802242975818 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224516580684169586} - component: {fileID: 222167338431205460} - component: {fileID: 114360822029985820} m_Layer: 0 m_Name: Text m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224516580684169586 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1296802242975818} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224486508223297500} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -20, y: -20} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222167338431205460 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1296802242975818} m_CullTransparentMesh: 0 --- !u!114 &114360822029985820 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1296802242975818} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.8773585, g: 0.8773585, b: 0.8773585, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 m_FontStyle: 1 m_BestFit: 1 m_MinSize: 10 m_MaxSize: 100 m_Alignment: 4 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: REC --- !u!1 &1396758521746238 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224684853938259454} - component: {fileID: 222170339468931566} - component: {fileID: 114810904825029540} m_Layer: 0 m_Name: Window1Image m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224684853938259454 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1396758521746238} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224668013321730738} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222170339468931566 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1396758521746238} m_CullTransparentMesh: 0 --- !u!114 &114810904825029540 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1396758521746238} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 8400000, guid: 3e2f16f77d6e1f248a7373bf0b951154, type: 2} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1404643369445172 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224406708302152076} - component: {fileID: 222021764812721688} - component: {fileID: 114059459554751028} m_Layer: 0 m_Name: Mask m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 0 --- !u!224 &224406708302152076 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1404643369445172} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224668013321730738} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222021764812721688 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1404643369445172} m_CullTransparentMesh: 0 --- !u!114 &114059459554751028 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1404643369445172} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1681168450629630 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224486508223297500} - component: {fileID: 222659468696730338} - component: {fileID: 114078040055249558} - component: {fileID: 114859874301012300} m_Layer: 0 m_Name: Record Button m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224486508223297500 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1681168450629630} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 224516580684169586} m_Father: {fileID: 224535373885583630} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.95, y: 0} m_AnchorMax: {x: 1, y: 0.1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -20, y: -20} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222659468696730338 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1681168450629630} m_CullTransparentMesh: 0 --- !u!114 &114078040055249558 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1681168450629630} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 2800000, guid: 12d610e2b2de6f14085327514252885e, type: 3} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!114 &114859874301012300 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1681168450629630} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: m_Mode: 3 m_SelectOnUp: {fileID: 0} m_SelectOnDown: {fileID: 0} m_SelectOnLeft: {fileID: 0} m_SelectOnRight: {fileID: 0} m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 114078040055249558} m_OnClick: m_PersistentCalls: m_Calls: - m_Target: {fileID: 114549485821928442} m_MethodName: ToggleRecording m_Mode: 1 m_Arguments: m_ObjectArgument: {fileID: 0} m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine m_IntArgument: 0 m_FloatArgument: 0 m_StringArgument: m_BoolArgument: 0 m_CallState: 2 --- !u!1 &1705292672280186 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224908474901092230} - component: {fileID: 222777456024021596} - component: {fileID: 114150005707971758} m_Layer: 0 m_Name: Window3 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224908474901092230 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1705292672280186} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 224078156062550704} - {fileID: 224308620163404540} m_Father: {fileID: 224535373885583630} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.6, y: 0} m_AnchorMax: {x: 0.9, y: 0.3} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -60, y: -30} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222777456024021596 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1705292672280186} m_CullTransparentMesh: 0 --- !u!114 &114150005707971758 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1705292672280186} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1848574268329360 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224205079563942886} - component: {fileID: 222996712108555964} - component: {fileID: 114986855983756936} m_Layer: 0 m_Name: Window2Image m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224205079563942886 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1848574268329360} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224126773406121108} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222996712108555964 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1848574268329360} m_CullTransparentMesh: 0 --- !u!114 &114986855983756936 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1848574268329360} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 8400000, guid: b1339334589473548b8a4359d6e72454, type: 2} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1873149298506654 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224078156062550704} - component: {fileID: 222103938122928036} - component: {fileID: 114744319565536910} m_Layer: 0 m_Name: Mask m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 0 --- !u!224 &224078156062550704 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1873149298506654} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 224908474901092230} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -6, y: -6} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222103938122928036 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1873149298506654} m_CullTransparentMesh: 0 --- !u!114 &114744319565536910 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1873149298506654} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1920437084883568 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224668013321730738} - component: {fileID: 222473737896211438} - component: {fileID: 114373534000765292} m_Layer: 0 m_Name: Window1 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224668013321730738 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1920437084883568} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 224406708302152076} - {fileID: 224684853938259454} m_Father: {fileID: 224535373885583630} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 0.3, y: 0.3} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -60, y: -30} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222473737896211438 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1920437084883568} m_CullTransparentMesh: 0 --- !u!114 &114373534000765292 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1920437084883568} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1926854741530346 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224126773406121108} - component: {fileID: 222923852511235180} - component: {fileID: 114724352752641148} m_Layer: 0 m_Name: Window2 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224126773406121108 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1926854741530346} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 224684424382713112} - {fileID: 224205079563942886} m_Father: {fileID: 224535373885583630} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.3, y: 0} m_AnchorMax: {x: 0.6, y: 0.3} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: -60, y: -30} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &222923852511235180 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1926854741530346} m_CullTransparentMesh: 0 --- !u!114 &114724352752641148 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1926854741530346} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 0 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Texture: {fileID: 0} m_UVRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 --- !u!1 &1989548626978598 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 224535373885583630} - component: {fileID: 223715515085500104} - component: {fileID: 114156839986646644} - component: {fileID: 114266238957765196} - component: {fileID: 114549485821928442} m_Layer: 0 m_Name: AirSimHUD m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &224535373885583630 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1989548626978598} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 0, y: 0, z: 0} m_Children: - {fileID: 224668013321730738} - {fileID: 224126773406121108} - {fileID: 224908474901092230} - {fileID: 224486508223297500} - {fileID: 4015438019020906} - {fileID: 1813847732} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 0, y: 0} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0, y: 0} --- !u!223 &223715515085500104 Canvas: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1989548626978598} m_Enabled: 1 serializedVersion: 3 m_RenderMode: 0 m_Camera: {fileID: 0} m_PlaneDistance: 100 m_PixelPerfect: 0 m_ReceivesEvents: 1 m_OverrideSorting: 0 m_OverridePixelPerfect: 0 m_SortingBucketNormalizedSize: 0 m_AdditionalShaderChannelsFlag: 0 m_SortingLayerID: 0 m_SortingOrder: 1 m_TargetDisplay: 0 --- !u!114 &114156839986646644 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1989548626978598} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 0cd44c1031e13a943bb63640046fad76, type: 3} m_Name: m_EditorClassIdentifier: m_UiScaleMode: 0 m_ReferencePixelsPerUnit: 100 m_ScaleFactor: 1 m_ReferenceResolution: {x: 800, y: 600} m_ScreenMatchMode: 0 m_MatchWidthOrHeight: 0 m_PhysicalUnit: 3 m_FallbackScreenDPI: 96 m_DefaultSpriteDPI: 96 m_DynamicPixelsPerUnit: 1 --- !u!114 &114266238957765196 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1989548626978598} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreReversedGraphics: 1 m_BlockingObjects: 0 m_BlockingMask: serializedVersion: 2 m_Bits: 4294967295 --- !u!114 &114549485821928442 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1989548626978598} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: e5aab8c89e05aff4984935a42cdc8072, type: 3} m_Name: m_EditorClassIdentifier: --- !u!1001 &2161695230989484835 PrefabInstance: m_ObjectHideFlags: 0 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 224535373885583630} m_Modifications: - target: {fileID: 2161695231376071340, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMin.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695231376071340, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695231376071340, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282896, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_Name value: WeatherHUD objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalPosition.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalPosition.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalPosition.z value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalRotation.w value: 1 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_RootOrder value: 5 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchoredPosition.x value: 30 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchoredPosition.y value: -15 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_SizeDelta.x value: 270 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_SizeDelta.y value: 200 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMin.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMin.y value: 1 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.y value: 1 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_Pivot.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_Pivot.y value: 1 objectReference: {fileID: 0} - target: {fileID: 2161695232971817516, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 2161695232971817516, guid: 2996349a160687b439f7dad6573ec62c, type: 3} propertyPath: m_AnchorMax.y value: 0 objectReference: {fileID: 0} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 2996349a160687b439f7dad6573ec62c, type: 3} --- !u!224 &1813847732 stripped RectTransform: m_CorrespondingSourceObject: {fileID: 2161695232802282903, guid: 2996349a160687b439f7dad6573ec62c, type: 3} m_PrefabInstance: {fileID: 2161695230989484835} m_PrefabAsset: {fileID: 0}
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimHUD.prefab/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimHUD.prefab", "repo_id": "AirSim", "token_count": 16427 }
45
fileFormatVersion: 2 guid: 23c9850d88ee1d446994346dd4737fc7 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts.meta", "repo_id": "AirSim", "token_count": 67 }
46